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(PREDEF_DECL_TRANSLATION_UNIT_ID,
5105 Context.getTranslationUnitDecl());
5106
5107 // FIXME: Find a better way to deal with collisions between these
5108 // built-in types. Right now, we just ignore the problem.
5109
5110 // Load the special types.
5111 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5112 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5113 if (!Context.CFConstantStringTypeDecl)
5114 Context.setCFConstantStringType(GetType(String));
5115 }
5116
5117 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5118 QualType FileType = GetType(File);
5119 if (FileType.isNull()) {
5120 Error("FILE type is NULL");
5121 return;
5122 }
5123
5124 if (!Context.FILEDecl) {
5125 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5126 Context.setFILEDecl(Typedef->getDecl());
5127 else {
5128 const TagType *Tag = FileType->getAs<TagType>();
5129 if (!Tag) {
5130 Error("Invalid FILE type in AST file");
5131 return;
5132 }
5133 Context.setFILEDecl(Tag->getDecl());
5134 }
5135 }
5136 }
5137
5138 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5139 QualType Jmp_bufType = GetType(Jmp_buf);
5140 if (Jmp_bufType.isNull()) {
5141 Error("jmp_buf type is NULL");
5142 return;
5143 }
5144
5145 if (!Context.jmp_bufDecl) {
5146 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5147 Context.setjmp_bufDecl(Typedef->getDecl());
5148 else {
5149 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5150 if (!Tag) {
5151 Error("Invalid jmp_buf type in AST file");
5152 return;
5153 }
5154 Context.setjmp_bufDecl(Tag->getDecl());
5155 }
5156 }
5157 }
5158
5159 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5160 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5161 if (Sigjmp_bufType.isNull()) {
5162 Error("sigjmp_buf type is NULL");
5163 return;
5164 }
5165
5166 if (!Context.sigjmp_bufDecl) {
5167 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5168 Context.setsigjmp_bufDecl(Typedef->getDecl());
5169 else {
5170 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5171 assert(Tag && "Invalid sigjmp_buf type in AST file");
5172 Context.setsigjmp_bufDecl(Tag->getDecl());
5173 }
5174 }
5175 }
5176
5177 if (unsigned ObjCIdRedef
5178 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5179 if (Context.ObjCIdRedefinitionType.isNull())
5180 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5181 }
5182
5183 if (unsigned ObjCClassRedef
5184 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
5185 if (Context.ObjCClassRedefinitionType.isNull())
5186 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5187 }
5188
5189 if (unsigned ObjCSelRedef
5190 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5191 if (Context.ObjCSelRedefinitionType.isNull())
5192 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5193 }
5194
5195 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5196 QualType Ucontext_tType = GetType(Ucontext_t);
5197 if (Ucontext_tType.isNull()) {
5198 Error("ucontext_t type is NULL");
5199 return;
5200 }
5201
5202 if (!Context.ucontext_tDecl) {
5203 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5204 Context.setucontext_tDecl(Typedef->getDecl());
5205 else {
5206 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5207 assert(Tag && "Invalid ucontext_t type in AST file");
5208 Context.setucontext_tDecl(Tag->getDecl());
5209 }
5210 }
5211 }
5212 }
5213
5214 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5215
5216 // If there were any CUDA special declarations, deserialize them.
5217 if (!CUDASpecialDeclRefs.empty()) {
5218 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5220 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5221 }
5222
5223 // Re-export any modules that were imported by a non-module AST file.
5224 // FIXME: This does not make macro-only imports visible again.
5225 for (auto &Import : PendingImportedModules) {
5226 if (Module *Imported = getSubmodule(Import.ID)) {
5227 makeModuleVisible(Imported, Module::AllVisible,
5228 /*ImportLoc=*/Import.ImportLoc);
5229 if (Import.ImportLoc.isValid())
5230 PP.makeModuleVisible(Imported, Import.ImportLoc);
5231 // This updates visibility for Preprocessor only. For Sema, which can be
5232 // nullptr here, we do the same later, in UpdateSema().
5233 }
5234 }
5235
5236 // Hand off these modules to Sema.
5237 PendingImportedModulesSema.append(PendingImportedModules);
5238 PendingImportedModules.clear();
5239}
5240
5242 // Nothing to do for now.
5243}
5244
5245/// Reads and return the signature record from \p PCH's control block, or
5246/// else returns 0.
5248 BitstreamCursor Stream(PCH);
5249 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5250 // FIXME this drops the error on the floor.
5251 consumeError(std::move(Err));
5252 return ASTFileSignature();
5253 }
5254
5255 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5257 return ASTFileSignature();
5258
5259 // Scan for SIGNATURE inside the diagnostic options block.
5261 while (true) {
5263 Stream.advanceSkippingSubblocks();
5264 if (!MaybeEntry) {
5265 // FIXME this drops the error on the floor.
5266 consumeError(MaybeEntry.takeError());
5267 return ASTFileSignature();
5268 }
5269 llvm::BitstreamEntry Entry = MaybeEntry.get();
5270
5271 if (Entry.Kind != llvm::BitstreamEntry::Record)
5272 return ASTFileSignature();
5273
5274 Record.clear();
5275 StringRef Blob;
5276 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5277 if (!MaybeRecord) {
5278 // FIXME this drops the error on the floor.
5279 consumeError(MaybeRecord.takeError());
5280 return ASTFileSignature();
5281 }
5282 if (SIGNATURE == MaybeRecord.get()) {
5283 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5284 assert(Signature != ASTFileSignature::createDummy() &&
5285 "Dummy AST file signature not backpatched in ASTWriter.");
5286 return Signature;
5287 }
5288 }
5289}
5290
5291/// Retrieve the name of the original source file name
5292/// directly from the AST file, without actually loading the AST
5293/// file.
5295 const std::string &ASTFileName, FileManager &FileMgr,
5296 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5297 // Open the AST file.
5298 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5299 /*RequiresNullTerminator=*/false);
5300 if (!Buffer) {
5301 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5302 << ASTFileName << Buffer.getError().message();
5303 return std::string();
5304 }
5305
5306 // Initialize the stream
5307 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5308
5309 // Sniff for the signature.
5310 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5311 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5312 return std::string();
5313 }
5314
5315 // Scan for the CONTROL_BLOCK_ID block.
5316 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5317 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5318 return std::string();
5319 }
5320
5321 // Scan for ORIGINAL_FILE inside the control block.
5323 while (true) {
5325 Stream.advanceSkippingSubblocks();
5326 if (!MaybeEntry) {
5327 // FIXME this drops errors on the floor.
5328 consumeError(MaybeEntry.takeError());
5329 return std::string();
5330 }
5331 llvm::BitstreamEntry Entry = MaybeEntry.get();
5332
5333 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5334 return std::string();
5335
5336 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5337 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5338 return std::string();
5339 }
5340
5341 Record.clear();
5342 StringRef Blob;
5343 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5344 if (!MaybeRecord) {
5345 // FIXME this drops the errors on the floor.
5346 consumeError(MaybeRecord.takeError());
5347 return std::string();
5348 }
5349 if (ORIGINAL_FILE == MaybeRecord.get())
5350 return Blob.str();
5351 }
5352}
5353
5354namespace {
5355
5356 class SimplePCHValidator : public ASTReaderListener {
5357 const LangOptions &ExistingLangOpts;
5358 const TargetOptions &ExistingTargetOpts;
5359 const PreprocessorOptions &ExistingPPOpts;
5360 std::string ExistingModuleCachePath;
5361 FileManager &FileMgr;
5362 bool StrictOptionMatches;
5363
5364 public:
5365 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5366 const TargetOptions &ExistingTargetOpts,
5367 const PreprocessorOptions &ExistingPPOpts,
5368 StringRef ExistingModuleCachePath, FileManager &FileMgr,
5369 bool StrictOptionMatches)
5370 : ExistingLangOpts(ExistingLangOpts),
5371 ExistingTargetOpts(ExistingTargetOpts),
5372 ExistingPPOpts(ExistingPPOpts),
5373 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5374 StrictOptionMatches(StrictOptionMatches) {}
5375
5376 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5377 bool AllowCompatibleDifferences) override {
5378 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5379 AllowCompatibleDifferences);
5380 }
5381
5382 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5383 bool AllowCompatibleDifferences) override {
5384 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5385 AllowCompatibleDifferences);
5386 }
5387
5388 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5389 StringRef SpecificModuleCachePath,
5390 bool Complain) override {
5391 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5392 ExistingModuleCachePath, nullptr,
5393 ExistingLangOpts, ExistingPPOpts);
5394 }
5395
5396 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5397 bool ReadMacros, bool Complain,
5398 std::string &SuggestedPredefines) override {
5400 PPOpts, ExistingPPOpts, ReadMacros, /*Diags=*/nullptr, FileMgr,
5401 SuggestedPredefines, ExistingLangOpts,
5402 StrictOptionMatches ? OptionValidateStrictMatches
5404 }
5405 };
5406
5407} // namespace
5408
5410 StringRef Filename, FileManager &FileMgr,
5411 const InMemoryModuleCache &ModuleCache,
5412 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5413 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5414 unsigned ClientLoadCapabilities) {
5415 // Open the AST file.
5416 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5417 llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
5418 if (!Buffer) {
5419 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5420 // read again later, but we do not have the context here to determine if it
5421 // is safe to change the result of InMemoryModuleCache::getPCMState().
5422
5423 // FIXME: This allows use of the VFS; we do not allow use of the
5424 // VFS when actually loading a module.
5425 auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5426 if (!BufferOrErr)
5427 return true;
5428 OwnedBuffer = std::move(*BufferOrErr);
5429 Buffer = OwnedBuffer.get();
5430 }
5431
5432 // Initialize the stream
5433 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5434 BitstreamCursor Stream(Bytes);
5435
5436 // Sniff for the signature.
5437 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5438 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5439 return true;
5440 }
5441
5442 // Scan for the CONTROL_BLOCK_ID block.
5444 return true;
5445
5446 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5447 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5448 bool NeedsImports = Listener.needsImportVisitation();
5449 BitstreamCursor InputFilesCursor;
5450 uint64_t InputFilesOffsetBase = 0;
5451
5453 std::string ModuleDir;
5454 bool DoneWithControlBlock = false;
5455 while (!DoneWithControlBlock) {
5456 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5457 if (!MaybeEntry) {
5458 // FIXME this drops the error on the floor.
5459 consumeError(MaybeEntry.takeError());
5460 return true;
5461 }
5462 llvm::BitstreamEntry Entry = MaybeEntry.get();
5463
5464 switch (Entry.Kind) {
5465 case llvm::BitstreamEntry::SubBlock: {
5466 switch (Entry.ID) {
5467 case OPTIONS_BLOCK_ID: {
5468 std::string IgnoredSuggestedPredefines;
5469 if (ReadOptionsBlock(Stream, ClientLoadCapabilities,
5470 /*AllowCompatibleConfigurationMismatch*/ false,
5471 Listener, IgnoredSuggestedPredefines) != Success)
5472 return true;
5473 break;
5474 }
5475
5477 InputFilesCursor = Stream;
5478 if (llvm::Error Err = Stream.SkipBlock()) {
5479 // FIXME this drops the error on the floor.
5480 consumeError(std::move(Err));
5481 return true;
5482 }
5483 if (NeedsInputFiles &&
5484 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5485 return true;
5486 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5487 break;
5488
5489 default:
5490 if (llvm::Error Err = Stream.SkipBlock()) {
5491 // FIXME this drops the error on the floor.
5492 consumeError(std::move(Err));
5493 return true;
5494 }
5495 break;
5496 }
5497
5498 continue;
5499 }
5500
5501 case llvm::BitstreamEntry::EndBlock:
5502 DoneWithControlBlock = true;
5503 break;
5504
5505 case llvm::BitstreamEntry::Error:
5506 return true;
5507
5508 case llvm::BitstreamEntry::Record:
5509 break;
5510 }
5511
5512 if (DoneWithControlBlock) break;
5513
5514 Record.clear();
5515 StringRef Blob;
5516 Expected<unsigned> MaybeRecCode =
5517 Stream.readRecord(Entry.ID, Record, &Blob);
5518 if (!MaybeRecCode) {
5519 // FIXME this drops the error.
5520 return Failure;
5521 }
5522 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5523 case METADATA:
5524 if (Record[0] != VERSION_MAJOR)
5525 return true;
5526 if (Listener.ReadFullVersionInformation(Blob))
5527 return true;
5528 break;
5529 case MODULE_NAME:
5530 Listener.ReadModuleName(Blob);
5531 break;
5532 case MODULE_DIRECTORY:
5533 ModuleDir = std::string(Blob);
5534 break;
5535 case MODULE_MAP_FILE: {
5536 unsigned Idx = 0;
5537 auto Path = ReadString(Record, Idx);
5538 ResolveImportedPath(Path, ModuleDir);
5539 Listener.ReadModuleMapFile(Path);
5540 break;
5541 }
5542 case INPUT_FILE_OFFSETS: {
5543 if (!NeedsInputFiles)
5544 break;
5545
5546 unsigned NumInputFiles = Record[0];
5547 unsigned NumUserFiles = Record[1];
5548 const llvm::support::unaligned_uint64_t *InputFileOffs =
5549 (const llvm::support::unaligned_uint64_t *)Blob.data();
5550 for (unsigned I = 0; I != NumInputFiles; ++I) {
5551 // Go find this input file.
5552 bool isSystemFile = I >= NumUserFiles;
5553
5554 if (isSystemFile && !NeedsSystemInputFiles)
5555 break; // the rest are system input files
5556
5557 BitstreamCursor &Cursor = InputFilesCursor;
5558 SavedStreamPosition SavedPosition(Cursor);
5559 if (llvm::Error Err =
5560 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5561 // FIXME this drops errors on the floor.
5562 consumeError(std::move(Err));
5563 }
5564
5565 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5566 if (!MaybeCode) {
5567 // FIXME this drops errors on the floor.
5568 consumeError(MaybeCode.takeError());
5569 }
5570 unsigned Code = MaybeCode.get();
5571
5573 StringRef Blob;
5574 bool shouldContinue = false;
5575 Expected<unsigned> MaybeRecordType =
5576 Cursor.readRecord(Code, Record, &Blob);
5577 if (!MaybeRecordType) {
5578 // FIXME this drops errors on the floor.
5579 consumeError(MaybeRecordType.takeError());
5580 }
5581 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5582 case INPUT_FILE_HASH:
5583 break;
5584 case INPUT_FILE:
5585 bool Overridden = static_cast<bool>(Record[3]);
5586 std::string Filename = std::string(Blob);
5587 ResolveImportedPath(Filename, ModuleDir);
5588 shouldContinue = Listener.visitInputFile(
5589 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5590 break;
5591 }
5592 if (!shouldContinue)
5593 break;
5594 }
5595 break;
5596 }
5597
5598 case IMPORTS: {
5599 if (!NeedsImports)
5600 break;
5601
5602 unsigned Idx = 0, N = Record.size();
5603 while (Idx < N) {
5604 // Read information about the AST file.
5605
5606 // Skip Kind
5607 Idx++;
5608 bool IsStandardCXXModule = Record[Idx++];
5609
5610 // Skip ImportLoc
5611 Idx++;
5612
5613 // In C++20 Modules, we don't record the path to imported
5614 // modules in the BMI files.
5615 if (IsStandardCXXModule) {
5616 std::string ModuleName = ReadString(Record, Idx);
5617 Listener.visitImport(ModuleName, /*Filename=*/"");
5618 continue;
5619 }
5620
5621 // Skip Size, ModTime and Signature
5622 Idx += 1 + 1 + ASTFileSignature::size;
5623 std::string ModuleName = ReadString(Record, Idx);
5624 std::string Filename = ReadString(Record, Idx);
5625 ResolveImportedPath(Filename, ModuleDir);
5626 Listener.visitImport(ModuleName, Filename);
5627 }
5628 break;
5629 }
5630
5631 default:
5632 // No other validation to perform.
5633 break;
5634 }
5635 }
5636
5637 // Look for module file extension blocks, if requested.
5638 if (FindModuleFileExtensions) {
5639 BitstreamCursor SavedStream = Stream;
5640 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5641 bool DoneWithExtensionBlock = false;
5642 while (!DoneWithExtensionBlock) {
5643 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5644 if (!MaybeEntry) {
5645 // FIXME this drops the error.
5646 return true;
5647 }
5648 llvm::BitstreamEntry Entry = MaybeEntry.get();
5649
5650 switch (Entry.Kind) {
5651 case llvm::BitstreamEntry::SubBlock:
5652 if (llvm::Error Err = Stream.SkipBlock()) {
5653 // FIXME this drops the error on the floor.
5654 consumeError(std::move(Err));
5655 return true;
5656 }
5657 continue;
5658
5659 case llvm::BitstreamEntry::EndBlock:
5660 DoneWithExtensionBlock = true;
5661 continue;
5662
5663 case llvm::BitstreamEntry::Error:
5664 return true;
5665
5666 case llvm::BitstreamEntry::Record:
5667 break;
5668 }
5669
5670 Record.clear();
5671 StringRef Blob;
5672 Expected<unsigned> MaybeRecCode =
5673 Stream.readRecord(Entry.ID, Record, &Blob);
5674 if (!MaybeRecCode) {
5675 // FIXME this drops the error.
5676 return true;
5677 }
5678 switch (MaybeRecCode.get()) {
5679 case EXTENSION_METADATA: {
5681 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5682 return true;
5683
5684 Listener.readModuleFileExtension(Metadata);
5685 break;
5686 }
5687 }
5688 }
5689 }
5690 Stream = SavedStream;
5691 }
5692
5693 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5694 if (readUnhashedControlBlockImpl(
5695 nullptr, Bytes, ClientLoadCapabilities,
5696 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5697 ValidateDiagnosticOptions) != Success)
5698 return true;
5699
5700 return false;
5701}
5702
5704 const InMemoryModuleCache &ModuleCache,
5705 const PCHContainerReader &PCHContainerRdr,
5706 const LangOptions &LangOpts,
5707 const TargetOptions &TargetOpts,
5708 const PreprocessorOptions &PPOpts,
5709 StringRef ExistingModuleCachePath,
5710 bool RequireStrictOptionMatches) {
5711 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5712 ExistingModuleCachePath, FileMgr,
5713 RequireStrictOptionMatches);
5714 return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
5715 PCHContainerRdr,
5716 /*FindModuleFileExtensions=*/false, validator,
5717 /*ValidateDiagnosticOptions=*/true);
5718}
5719
5720llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5721 unsigned ClientLoadCapabilities) {
5722 // Enter the submodule block.
5723 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5724 return Err;
5725
5726 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5727 bool First = true;
5728 Module *CurrentModule = nullptr;
5729 RecordData Record;
5730 while (true) {
5732 F.Stream.advanceSkippingSubblocks();
5733 if (!MaybeEntry)
5734 return MaybeEntry.takeError();
5735 llvm::BitstreamEntry Entry = MaybeEntry.get();
5736
5737 switch (Entry.Kind) {
5738 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5739 case llvm::BitstreamEntry::Error:
5740 return llvm::createStringError(std::errc::illegal_byte_sequence,
5741 "malformed block record in AST file");
5742 case llvm::BitstreamEntry::EndBlock:
5743 return llvm::Error::success();
5744 case llvm::BitstreamEntry::Record:
5745 // The interesting case.
5746 break;
5747 }
5748
5749 // Read a record.
5750 StringRef Blob;
5751 Record.clear();
5752 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5753 if (!MaybeKind)
5754 return MaybeKind.takeError();
5755 unsigned Kind = MaybeKind.get();
5756
5757 if ((Kind == SUBMODULE_METADATA) != First)
5758 return llvm::createStringError(
5759 std::errc::illegal_byte_sequence,
5760 "submodule metadata record should be at beginning of block");
5761 First = false;
5762
5763 // Submodule information is only valid if we have a current module.
5764 // FIXME: Should we error on these cases?
5765 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5766 Kind != SUBMODULE_DEFINITION)
5767 continue;
5768
5769 switch (Kind) {
5770 default: // Default behavior: ignore.
5771 break;
5772
5773 case SUBMODULE_DEFINITION: {
5774 if (Record.size() < 13)
5775 return llvm::createStringError(std::errc::illegal_byte_sequence,
5776 "malformed module definition");
5777
5778 StringRef Name = Blob;
5779 unsigned Idx = 0;
5780 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5781 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5783 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
5784 bool IsFramework = Record[Idx++];
5785 bool IsExplicit = Record[Idx++];
5786 bool IsSystem = Record[Idx++];
5787 bool IsExternC = Record[Idx++];
5788 bool InferSubmodules = Record[Idx++];
5789 bool InferExplicitSubmodules = Record[Idx++];
5790 bool InferExportWildcard = Record[Idx++];
5791 bool ConfigMacrosExhaustive = Record[Idx++];
5792 bool ModuleMapIsPrivate = Record[Idx++];
5793 bool NamedModuleHasInit = Record[Idx++];
5794
5795 Module *ParentModule = nullptr;
5796 if (Parent)
5797 ParentModule = getSubmodule(Parent);
5798
5799 // Retrieve this (sub)module from the module map, creating it if
5800 // necessary.
5801 CurrentModule =
5802 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5803 .first;
5804
5805 // FIXME: Call ModMap.setInferredModuleAllowedBy()
5806
5807 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5808 if (GlobalIndex >= SubmodulesLoaded.size() ||
5809 SubmodulesLoaded[GlobalIndex])
5810 return llvm::createStringError(std::errc::invalid_argument,
5811 "too many submodules");
5812
5813 if (!ParentModule) {
5814 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
5815 // Don't emit module relocation error if we have -fno-validate-pch
5816 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5818 CurFile != F.File) {
5819 auto ConflictError =
5820 PartialDiagnostic(diag::err_module_file_conflict,
5821 ContextObj->DiagAllocator)
5822 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5823 << F.File.getName();
5824 return DiagnosticError::create(CurrentImportLoc, ConflictError);
5825 }
5826 }
5827
5828 F.DidReadTopLevelSubmodule = true;
5829 CurrentModule->setASTFile(F.File);
5830 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5831 }
5832
5833 CurrentModule->Kind = Kind;
5834 CurrentModule->DefinitionLoc = DefinitionLoc;
5835 CurrentModule->Signature = F.Signature;
5836 CurrentModule->IsFromModuleFile = true;
5837 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5838 CurrentModule->IsExternC = IsExternC;
5839 CurrentModule->InferSubmodules = InferSubmodules;
5840 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5841 CurrentModule->InferExportWildcard = InferExportWildcard;
5842 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5843 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5844 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
5845 if (DeserializationListener)
5846 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5847
5848 SubmodulesLoaded[GlobalIndex] = CurrentModule;
5849
5850 // Clear out data that will be replaced by what is in the module file.
5851 CurrentModule->LinkLibraries.clear();
5852 CurrentModule->ConfigMacros.clear();
5853 CurrentModule->UnresolvedConflicts.clear();
5854 CurrentModule->Conflicts.clear();
5855
5856 // The module is available unless it's missing a requirement; relevant
5857 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5858 // Missing headers that were present when the module was built do not
5859 // make it unavailable -- if we got this far, this must be an explicitly
5860 // imported module file.
5861 CurrentModule->Requirements.clear();
5862 CurrentModule->MissingHeaders.clear();
5863 CurrentModule->IsUnimportable =
5864 ParentModule && ParentModule->IsUnimportable;
5865 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
5866 break;
5867 }
5868
5870 // FIXME: This doesn't work for framework modules as `Filename` is the
5871 // name as written in the module file and does not include
5872 // `Headers/`, so this path will never exist.
5873 std::string Filename = std::string(Blob);
5874 ResolveImportedPath(F, Filename);
5875 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
5876 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
5877 // FIXME: NameAsWritten
5878 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
5879 }
5880 // Note that it's too late at this point to return out of date if the
5881 // name from the PCM doesn't match up with the one in the module map,
5882 // but also quite unlikely since we will have already checked the
5883 // modification time and size of the module map file itself.
5884 }
5885 break;
5886 }
5887
5888 case SUBMODULE_HEADER:
5891 // We lazily associate headers with their modules via the HeaderInfo table.
5892 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5893 // of complete filenames or remove it entirely.
5894 break;
5895
5898 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5899 // them here.
5900 break;
5901
5902 case SUBMODULE_TOPHEADER: {
5903 std::string HeaderName(Blob);
5904 ResolveImportedPath(F, HeaderName);
5905 CurrentModule->addTopHeaderFilename(HeaderName);
5906 break;
5907 }
5908
5910 // See comments in SUBMODULE_UMBRELLA_HEADER
5911 std::string Dirname = std::string(Blob);
5912 ResolveImportedPath(F, Dirname);
5913 if (auto Umbrella =
5914 PP.getFileManager().getOptionalDirectoryRef(Dirname)) {
5915 if (!CurrentModule->getUmbrellaDirAsWritten()) {
5916 // FIXME: NameAsWritten
5917 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
5918 }
5919 }
5920 break;
5921 }
5922
5923 case SUBMODULE_METADATA: {
5924 F.BaseSubmoduleID = getTotalNumSubmodules();
5926 unsigned LocalBaseSubmoduleID = Record[1];
5927 if (F.LocalNumSubmodules > 0) {
5928 // Introduce the global -> local mapping for submodules within this
5929 // module.
5930 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5931
5932 // Introduce the local -> global mapping for submodules within this
5933 // module.
5935 std::make_pair(LocalBaseSubmoduleID,
5936 F.BaseSubmoduleID - LocalBaseSubmoduleID));
5937
5938 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5939 }
5940 break;
5941 }
5942
5943 case SUBMODULE_IMPORTS:
5944 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5945 UnresolvedModuleRef Unresolved;
5946 Unresolved.File = &F;
5947 Unresolved.Mod = CurrentModule;
5948 Unresolved.ID = Record[Idx];
5949 Unresolved.Kind = UnresolvedModuleRef::Import;
5950 Unresolved.IsWildcard = false;
5951 UnresolvedModuleRefs.push_back(Unresolved);
5952 }
5953 break;
5954
5956 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5957 UnresolvedModuleRef Unresolved;
5958 Unresolved.File = &F;
5959 Unresolved.Mod = CurrentModule;
5960 Unresolved.ID = Record[Idx];
5961 Unresolved.Kind = UnresolvedModuleRef::Affecting;
5962 Unresolved.IsWildcard = false;
5963 UnresolvedModuleRefs.push_back(Unresolved);
5964 }
5965 break;
5966
5967 case SUBMODULE_EXPORTS:
5968 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5969 UnresolvedModuleRef Unresolved;
5970 Unresolved.File = &F;
5971 Unresolved.Mod = CurrentModule;
5972 Unresolved.ID = Record[Idx];
5973 Unresolved.Kind = UnresolvedModuleRef::Export;
5974 Unresolved.IsWildcard = Record[Idx + 1];
5975 UnresolvedModuleRefs.push_back(Unresolved);
5976 }
5977
5978 // Once we've loaded the set of exports, there's no reason to keep
5979 // the parsed, unresolved exports around.
5980 CurrentModule->UnresolvedExports.clear();
5981 break;
5982
5983 case SUBMODULE_REQUIRES:
5984 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5985 PP.getTargetInfo());
5986 break;
5987
5989 ModMap.resolveLinkAsDependencies(CurrentModule);
5990 CurrentModule->LinkLibraries.push_back(
5991 Module::LinkLibrary(std::string(Blob), Record[0]));
5992 break;
5993
5995 CurrentModule->ConfigMacros.push_back(Blob.str());
5996 break;
5997
5998 case SUBMODULE_CONFLICT: {
5999 UnresolvedModuleRef Unresolved;
6000 Unresolved.File = &F;
6001 Unresolved.Mod = CurrentModule;
6002 Unresolved.ID = Record[0];
6003 Unresolved.Kind = UnresolvedModuleRef::Conflict;
6004 Unresolved.IsWildcard = false;
6005 Unresolved.String = Blob;
6006 UnresolvedModuleRefs.push_back(Unresolved);
6007 break;
6008 }
6009
6011 if (!ContextObj)
6012 break;
6014 for (auto &ID : Record)
6015 Inits.push_back(getGlobalDeclID(F, LocalDeclID(ID)).get());
6016 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6017 break;
6018 }
6019
6021 CurrentModule->ExportAsModule = Blob.str();
6022 ModMap.addLinkAsDependency(CurrentModule);
6023 break;
6024 }
6025 }
6026}
6027
6028/// Parse the record that corresponds to a LangOptions data
6029/// structure.
6030///
6031/// This routine parses the language options from the AST file and then gives
6032/// them to the AST listener if one is set.
6033///
6034/// \returns true if the listener deems the file unacceptable, false otherwise.
6035bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6036 bool Complain,
6037 ASTReaderListener &Listener,
6038 bool AllowCompatibleDifferences) {
6039 LangOptions LangOpts;
6040 unsigned Idx = 0;
6041#define LANGOPT(Name, Bits, Default, Description) \
6042 LangOpts.Name = Record[Idx++];
6043#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
6044 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6045#include "clang/Basic/LangOptions.def"
6046#define SANITIZER(NAME, ID) \
6047 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6048#include "clang/Basic/Sanitizers.def"
6049
6050 for (unsigned N = Record[Idx++]; N; --N)
6051 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6052
6053 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6054 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6055 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6056
6057 LangOpts.CurrentModule = ReadString(Record, Idx);
6058
6059 // Comment options.
6060 for (unsigned N = Record[Idx++]; N; --N) {
6061 LangOpts.CommentOpts.BlockCommandNames.push_back(
6062 ReadString(Record, Idx));
6063 }
6064 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6065
6066 // OpenMP offloading options.
6067 for (unsigned N = Record[Idx++]; N; --N) {
6068 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6069 }
6070
6071 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6072
6073 return Listener.ReadLanguageOptions(LangOpts, Complain,
6074 AllowCompatibleDifferences);
6075}
6076
6077bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
6078 ASTReaderListener &Listener,
6079 bool AllowCompatibleDifferences) {
6080 unsigned Idx = 0;
6081 TargetOptions TargetOpts;
6082 TargetOpts.Triple = ReadString(Record, Idx);
6083 TargetOpts.CPU = ReadString(Record, Idx);
6084 TargetOpts.TuneCPU = ReadString(Record, Idx);
6085 TargetOpts.ABI = ReadString(Record, Idx);
6086 for (unsigned N = Record[Idx++]; N; --N) {
6087 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6088 }
6089 for (unsigned N = Record[Idx++]; N; --N) {
6090 TargetOpts.Features.push_back(ReadString(Record, Idx));
6091 }
6092
6093 return Listener.ReadTargetOptions(TargetOpts, Complain,
6094 AllowCompatibleDifferences);
6095}
6096
6097bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
6098 ASTReaderListener &Listener) {
6100 unsigned Idx = 0;
6101#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
6102#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6103 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
6104#include "clang/Basic/DiagnosticOptions.def"
6105
6106 for (unsigned N = Record[Idx++]; N; --N)
6107 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
6108 for (unsigned N = Record[Idx++]; N; --N)
6109 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
6110
6111 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
6112}
6113
6114bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6115 ASTReaderListener &Listener) {
6116 FileSystemOptions FSOpts;
6117 unsigned Idx = 0;
6118 FSOpts.WorkingDir = ReadString(Record, Idx);
6119 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6120}
6121
6122bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6123 bool Complain,
6124 ASTReaderListener &Listener) {
6125 HeaderSearchOptions HSOpts;
6126 unsigned Idx = 0;
6127 HSOpts.Sysroot = ReadString(Record, Idx);
6128
6129 HSOpts.ResourceDir = ReadString(Record, Idx);
6130 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6131 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6132 HSOpts.DisableModuleHash = Record[Idx++];
6133 HSOpts.ImplicitModuleMaps = Record[Idx++];
6134 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6135 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6136 HSOpts.UseBuiltinIncludes = Record[Idx++];
6137 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6138 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6139 HSOpts.UseLibcxx = Record[Idx++];
6140 std::string SpecificModuleCachePath = ReadString(Record, Idx);
6141
6142 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
6143 Complain);
6144}
6145
6146bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6147 ASTReaderListener &Listener) {
6148 HeaderSearchOptions HSOpts;
6149 unsigned Idx = 0;
6150
6151 // Include entries.
6152 for (unsigned N = Record[Idx++]; N; --N) {
6153 std::string Path = ReadString(Record, Idx);
6155 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6156 bool IsFramework = Record[Idx++];
6157 bool IgnoreSysRoot = Record[Idx++];
6158 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6159 IgnoreSysRoot);
6160 }
6161
6162 // System header prefixes.
6163 for (unsigned N = Record[Idx++]; N; --N) {
6164 std::string Prefix = ReadString(Record, Idx);
6165 bool IsSystemHeader = Record[Idx++];
6166 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6167 }
6168
6169 // VFS overlay files.
6170 for (unsigned N = Record[Idx++]; N; --N) {
6171 std::string VFSOverlayFile = ReadString(Record, Idx);
6172 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6173 }
6174
6175 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6176}
6177
6178bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6179 bool Complain,
6180 ASTReaderListener &Listener,
6181 std::string &SuggestedPredefines) {
6182 PreprocessorOptions PPOpts;
6183 unsigned Idx = 0;
6184
6185 // Macro definitions/undefs
6186 bool ReadMacros = Record[Idx++];
6187 if (ReadMacros) {
6188 for (unsigned N = Record[Idx++]; N; --N) {
6189 std::string Macro = ReadString(Record, Idx);
6190 bool IsUndef = Record[Idx++];
6191 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6192 }
6193 }
6194
6195 // Includes
6196 for (unsigned N = Record[Idx++]; N; --N) {
6197 PPOpts.Includes.push_back(ReadString(Record, Idx));
6198 }
6199
6200 // Macro Includes
6201 for (unsigned N = Record[Idx++]; N; --N) {
6202 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6203 }
6204
6205 PPOpts.UsePredefines = Record[Idx++];
6206 PPOpts.DetailedRecord = Record[Idx++];
6207 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6209 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6210 SuggestedPredefines.clear();
6211 return Listener.ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
6212 SuggestedPredefines);
6213}
6214
6215std::pair<ModuleFile *, unsigned>
6216ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6217 GlobalPreprocessedEntityMapType::iterator
6218 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6219 assert(I != GlobalPreprocessedEntityMap.end() &&
6220 "Corrupted global preprocessed entity map");
6221 ModuleFile *M = I->second;
6222 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6223 return std::make_pair(M, LocalIndex);
6224}
6225
6226llvm::iterator_range<PreprocessingRecord::iterator>
6227ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6228 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6229 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6231
6232 return llvm::make_range(PreprocessingRecord::iterator(),
6234}
6235
6236bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6237 unsigned int ClientLoadCapabilities) {
6238 return ClientLoadCapabilities & ARR_OutOfDate &&
6239 !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
6240}
6241
6242llvm::iterator_range<ASTReader::ModuleDeclIterator>
6244 return llvm::make_range(
6245 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6246 ModuleDeclIterator(this, &Mod,
6248}
6249
6251 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6252 assert(I != GlobalSkippedRangeMap.end() &&
6253 "Corrupted global skipped range map");
6254 ModuleFile *M = I->second;
6255 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6256 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6257 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6258 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
6259 TranslateSourceLocation(*M, RawRange.getEnd()));
6260 assert(Range.isValid());
6261 return Range;
6262}
6263
6265 PreprocessedEntityID PPID = Index+1;
6266 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6267 ModuleFile &M = *PPInfo.first;
6268 unsigned LocalIndex = PPInfo.second;
6269 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6270
6271 if (!PP.getPreprocessingRecord()) {
6272 Error("no preprocessing record");
6273 return nullptr;
6274 }
6275
6277 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6278 M.MacroOffsetsBase + PPOffs.BitOffset)) {
6279 Error(std::move(Err));
6280 return nullptr;
6281 }
6282
6284 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6285 if (!MaybeEntry) {
6286 Error(MaybeEntry.takeError());
6287 return nullptr;
6288 }
6289 llvm::BitstreamEntry Entry = MaybeEntry.get();
6290
6291 if (Entry.Kind != llvm::BitstreamEntry::Record)
6292 return nullptr;
6293
6294 // Read the record.
6295 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
6296 TranslateSourceLocation(M, PPOffs.getEnd()));
6297 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6298 StringRef Blob;
6300 Expected<unsigned> MaybeRecType =
6301 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6302 if (!MaybeRecType) {
6303 Error(MaybeRecType.takeError());
6304 return nullptr;
6305 }
6306 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6307 case PPD_MACRO_EXPANSION: {
6308 bool isBuiltin = Record[0];
6309 IdentifierInfo *Name = nullptr;
6310 MacroDefinitionRecord *Def = nullptr;
6311 if (isBuiltin)
6312 Name = getLocalIdentifier(M, Record[1]);
6313 else {
6314 PreprocessedEntityID GlobalID =
6315 getGlobalPreprocessedEntityID(M, Record[1]);
6316 Def = cast<MacroDefinitionRecord>(
6317 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6318 }
6319
6320 MacroExpansion *ME;
6321 if (isBuiltin)
6322 ME = new (PPRec) MacroExpansion(Name, Range);
6323 else
6324 ME = new (PPRec) MacroExpansion(Def, Range);
6325
6326 return ME;
6327 }
6328
6329 case PPD_MACRO_DEFINITION: {
6330 // Decode the identifier info and then check again; if the macro is
6331 // still defined and associated with the identifier,
6332 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6333 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6334
6335 if (DeserializationListener)
6336 DeserializationListener->MacroDefinitionRead(PPID, MD);
6337
6338 return MD;
6339 }
6340
6342 const char *FullFileNameStart = Blob.data() + Record[0];
6343 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6345 if (!FullFileName.empty())
6346 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6347
6348 // FIXME: Stable encoding
6350 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6352 = new (PPRec) InclusionDirective(PPRec, Kind,
6353 StringRef(Blob.data(), Record[0]),
6354 Record[1], Record[3],
6355 File,
6356 Range);
6357 return ID;
6358 }
6359 }
6360
6361 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6362}
6363
6364/// Find the next module that contains entities and return the ID
6365/// of the first entry.
6366///
6367/// \param SLocMapI points at a chunk of a module that contains no
6368/// preprocessed entities or the entities it contains are not the ones we are
6369/// looking for.
6370PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6371 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6372 ++SLocMapI;
6373 for (GlobalSLocOffsetMapType::const_iterator
6374 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6375 ModuleFile &M = *SLocMapI->second;
6377 return M.BasePreprocessedEntityID;
6378 }
6379
6380 return getTotalNumPreprocessedEntities();
6381}
6382
6383namespace {
6384
6385struct PPEntityComp {
6386 const ASTReader &Reader;
6387 ModuleFile &M;
6388
6389 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6390
6391 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6392 SourceLocation LHS = getLoc(L);
6393 SourceLocation RHS = getLoc(R);
6394 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6395 }
6396
6397 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6398 SourceLocation LHS = getLoc(L);
6399 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6400 }
6401
6402 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6403 SourceLocation RHS = getLoc(R);
6404 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6405 }
6406
6407 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6408 return Reader.TranslateSourceLocation(M, PPE.getBegin());
6409 }
6410};
6411
6412} // namespace
6413
6414PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6415 bool EndsAfter) const {
6416 if (SourceMgr.isLocalSourceLocation(Loc))
6417 return getTotalNumPreprocessedEntities();
6418
6419 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6420 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6421 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6422 "Corrupted global sloc offset map");
6423
6424 if (SLocMapI->second->NumPreprocessedEntities == 0)
6425 return findNextPreprocessedEntity(SLocMapI);
6426
6427 ModuleFile &M = *SLocMapI->second;
6428
6429 using pp_iterator = const PPEntityOffset *;
6430
6431 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6432 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6433
6434 size_t Count = M.NumPreprocessedEntities;
6435 size_t Half;
6436 pp_iterator First = pp_begin;
6437 pp_iterator PPI;
6438
6439 if (EndsAfter) {
6440 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6441 PPEntityComp(*this, M));
6442 } else {
6443 // Do a binary search manually instead of using std::lower_bound because
6444 // The end locations of entities may be unordered (when a macro expansion
6445 // is inside another macro argument), but for this case it is not important
6446 // whether we get the first macro expansion or its containing macro.
6447 while (Count > 0) {
6448 Half = Count / 2;
6449 PPI = First;
6450 std::advance(PPI, Half);
6451 if (SourceMgr.isBeforeInTranslationUnit(
6452 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
6453 First = PPI;
6454 ++First;
6455 Count = Count - Half - 1;
6456 } else
6457 Count = Half;
6458 }
6459 }
6460
6461 if (PPI == pp_end)
6462 return findNextPreprocessedEntity(SLocMapI);
6463
6464 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6465}
6466
6467/// Returns a pair of [Begin, End) indices of preallocated
6468/// preprocessed entities that \arg Range encompasses.
6469std::pair<unsigned, unsigned>
6471 if (Range.isInvalid())
6472 return std::make_pair(0,0);
6473 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6474
6475 PreprocessedEntityID BeginID =
6476 findPreprocessedEntity(Range.getBegin(), false);
6477 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6478 return std::make_pair(BeginID, EndID);
6479}
6480
6481/// Optionally returns true or false if the preallocated preprocessed
6482/// entity with index \arg Index came from file \arg FID.
6483std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6484 FileID FID) {
6485 if (FID.isInvalid())
6486 return false;
6487
6488 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6489 ModuleFile &M = *PPInfo.first;
6490 unsigned LocalIndex = PPInfo.second;
6491 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6492
6493 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
6494 if (Loc.isInvalid())
6495 return false;
6496
6497 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6498 return true;
6499 else
6500 return false;
6501}
6502
6503namespace {
6504
6505 /// Visitor used to search for information about a header file.
6506 class HeaderFileInfoVisitor {
6507 FileEntryRef FE;
6508 std::optional<HeaderFileInfo> HFI;
6509
6510 public:
6511 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
6512
6513 bool operator()(ModuleFile &M) {
6516 if (!Table)
6517 return false;
6518
6519 // Look in the on-disk hash table for an entry for this file name.
6520 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6521 if (Pos == Table->end())
6522 return false;
6523
6524 HFI = *Pos;
6525 return true;
6526 }
6527
6528 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6529 };
6530
6531} // namespace
6532
6534 HeaderFileInfoVisitor Visitor(FE);
6535 ModuleMgr.visit(Visitor);
6536 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6537 return *HFI;
6538
6539 return HeaderFileInfo();
6540}
6541
6543 using DiagState = DiagnosticsEngine::DiagState;
6545
6546 for (ModuleFile &F : ModuleMgr) {
6547 unsigned Idx = 0;
6548 auto &Record = F.PragmaDiagMappings;
6549 if (Record.empty())
6550 continue;
6551
6552 DiagStates.clear();
6553
6554 auto ReadDiagState = [&](const DiagState &BasedOn,
6555 bool IncludeNonPragmaStates) {
6556 unsigned BackrefID = Record[Idx++];
6557 if (BackrefID != 0)
6558 return DiagStates[BackrefID - 1];
6559
6560 // A new DiagState was created here.
6561 Diag.DiagStates.push_back(BasedOn);
6562 DiagState *NewState = &Diag.DiagStates.back();
6563 DiagStates.push_back(NewState);
6564 unsigned Size = Record[Idx++];
6565 assert(Idx + Size * 2 <= Record.size() &&
6566 "Invalid data, not enough diag/map pairs");
6567 while (Size--) {
6568 unsigned DiagID = Record[Idx++];
6569 DiagnosticMapping NewMapping =
6571 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6572 continue;
6573
6574 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6575
6576 // If this mapping was specified as a warning but the severity was
6577 // upgraded due to diagnostic settings, simulate the current diagnostic
6578 // settings (and use a warning).
6579 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6581 NewMapping.setUpgradedFromWarning(false);
6582 }
6583
6584 Mapping = NewMapping;
6585 }
6586 return NewState;
6587 };
6588
6589 // Read the first state.
6590 DiagState *FirstState;
6591 if (F.Kind == MK_ImplicitModule) {
6592 // Implicitly-built modules are reused with different diagnostic
6593 // settings. Use the initial diagnostic state from Diag to simulate this
6594 // compilation's diagnostic settings.
6595 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6596 DiagStates.push_back(FirstState);
6597
6598 // Skip the initial diagnostic state from the serialized module.
6599 assert(Record[1] == 0 &&
6600 "Invalid data, unexpected backref in initial state");
6601 Idx = 3 + Record[2] * 2;
6602 assert(Idx < Record.size() &&
6603 "Invalid data, not enough state change pairs in initial state");
6604 } else if (F.isModule()) {
6605 // For an explicit module, preserve the flags from the module build
6606 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6607 // -Wblah flags.
6608 unsigned Flags = Record[Idx++];
6609 DiagState Initial;
6610 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6611 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6612 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6613 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6614 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6615 Initial.ExtBehavior = (diag::Severity)Flags;
6616 FirstState = ReadDiagState(Initial, true);
6617
6618 assert(F.OriginalSourceFileID.isValid());
6619
6620 // Set up the root buffer of the module to start with the initial
6621 // diagnostic state of the module itself, to cover files that contain no
6622 // explicit transitions (for which we did not serialize anything).
6623 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6624 .StateTransitions.push_back({FirstState, 0});
6625 } else {
6626 // For prefix ASTs, start with whatever the user configured on the
6627 // command line.
6628 Idx++; // Skip flags.
6629 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
6630 }
6631
6632 // Read the state transitions.
6633 unsigned NumLocations = Record[Idx++];
6634 while (NumLocations--) {
6635 assert(Idx < Record.size() &&
6636 "Invalid data, missing pragma diagnostic states");
6637 FileID FID = ReadFileID(F, Record, Idx);
6638 assert(FID.isValid() && "invalid FileID for transition");
6639 unsigned Transitions = Record[Idx++];
6640
6641 // Note that we don't need to set up Parent/ParentOffset here, because
6642 // we won't be changing the diagnostic state within imported FileIDs
6643 // (other than perhaps appending to the main source file, which has no
6644 // parent).
6645 auto &F = Diag.DiagStatesByLoc.Files[FID];
6646 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6647 for (unsigned I = 0; I != Transitions; ++I) {
6648 unsigned Offset = Record[Idx++];
6649 auto *State = ReadDiagState(*FirstState, false);
6650 F.StateTransitions.push_back({State, Offset});
6651 }
6652 }
6653
6654 // Read the final state.
6655 assert(Idx < Record.size() &&
6656 "Invalid data, missing final pragma diagnostic state");
6657 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
6658 auto *CurState = ReadDiagState(*FirstState, false);
6659
6660 if (!F.isModule()) {
6661 Diag.DiagStatesByLoc.CurDiagState = CurState;
6662 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6663
6664 // Preserve the property that the imaginary root file describes the
6665 // current state.
6666 FileID NullFile;
6667 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6668 if (T.empty())
6669 T.push_back({CurState, 0});
6670 else
6671 T[0].State = CurState;
6672 }
6673
6674 // Don't try to read these mappings again.
6675 Record.clear();
6676 }
6677}
6678
6679/// Get the correct cursor and offset for loading a type.
6680ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6681 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6682 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6683 ModuleFile *M = I->second;
6684 return RecordLocation(
6685 M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() +
6687}
6688
6689static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6690 switch (code) {
6691#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6692 case TYPE_##CODE_ID: return Type::CLASS_ID;
6693#include "clang/Serialization/TypeBitCodes.def"
6694 default:
6695 return std::nullopt;
6696 }
6697}
6698
6699/// Read and return the type with the given index..
6700///
6701/// The index is the type ID, shifted and minus the number of predefs. This
6702/// routine actually reads the record corresponding to the type at the given
6703/// location. It is a helper routine for GetType, which deals with reading type
6704/// IDs.
6705QualType ASTReader::readTypeRecord(unsigned Index) {
6706 assert(ContextObj && "reading type with no AST context");
6707 ASTContext &Context = *ContextObj;
6708 RecordLocation Loc = TypeCursorForIndex(Index);
6709 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6710
6711 // Keep track of where we are in the stream, then jump back there
6712 // after reading this type.
6713 SavedStreamPosition SavedPosition(DeclsCursor);
6714
6715 ReadingKindTracker ReadingKind(Read_Type, *this);
6716
6717 // Note that we are loading a type record.
6718 Deserializing AType(this);
6719
6720 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6721 Error(std::move(Err));
6722 return QualType();
6723 }
6724 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6725 if (!RawCode) {
6726 Error(RawCode.takeError());
6727 return QualType();
6728 }
6729
6730 ASTRecordReader Record(*this, *Loc.F);
6731 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6732 if (!Code) {
6733 Error(Code.takeError());
6734 return QualType();
6735 }
6736 if (Code.get() == TYPE_EXT_QUAL) {
6737 QualType baseType = Record.readQualType();
6738 Qualifiers quals = Record.readQualifiers();
6739 return Context.getQualifiedType(baseType, quals);
6740 }
6741
6742 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6743 if (!maybeClass) {
6744 Error("Unexpected code for type");
6745 return QualType();
6746 }
6747
6749 return TypeReader.read(*maybeClass);
6750}
6751
6752namespace clang {
6753
6754class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6756
6757 ASTRecordReader &Reader;
6758 LocSeq *Seq;
6759
6760 SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
6761 SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
6762
6763 TypeSourceInfo *GetTypeSourceInfo() {
6764 return Reader.readTypeSourceInfo();
6765 }
6766
6767 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6768 return Reader.readNestedNameSpecifierLoc();
6769 }
6770
6771 Attr *ReadAttr() {
6772 return Reader.readAttr();
6773 }
6774
6775public:
6777 : Reader(Reader), Seq(Seq) {}
6778
6779 // We want compile-time assurance that we've enumerated all of
6780 // these, so unfortunately we have to declare them first, then
6781 // define them out-of-line.
6782#define ABSTRACT_TYPELOC(CLASS, PARENT)
6783#define TYPELOC(CLASS, PARENT) \
6784 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6785#include "clang/AST/TypeLocNodes.def"
6786
6787 void VisitFunctionTypeLoc(FunctionTypeLoc);
6788 void VisitArrayTypeLoc(ArrayTypeLoc);
6789};
6790
6791} // namespace clang
6792
6793void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6794 // nothing to do
6795}
6796
6797void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6798 TL.setBuiltinLoc(readSourceLocation());
6799 if (TL.needsExtraLocalData()) {
6800 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6801 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6802 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6803 TL.setModeAttr(Reader.readInt());
6804 }
6805}
6806
6807void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6808 TL.setNameLoc(readSourceLocation());
6809}
6810
6811void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6812 TL.setStarLoc(readSourceLocation());
6813}
6814
6815void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6816 // nothing to do
6817}
6818
6819void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6820 // nothing to do
6821}
6822
6823void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6824 // nothing to do
6825}
6826
6827void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6828 TL.setExpansionLoc(readSourceLocation());
6829}
6830
6831void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6832 TL.setCaretLoc(readSourceLocation());
6833}
6834
6835void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6836 TL.setAmpLoc(readSourceLocation());
6837}
6838
6839void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6840 TL.setAmpAmpLoc(readSourceLocation());
6841}
6842
6843void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6844 TL.setStarLoc(readSourceLocation());
6845 TL.setClassTInfo(GetTypeSourceInfo());
6846}
6847
6849 TL.setLBracketLoc(readSourceLocation());
6850 TL.setRBracketLoc(readSourceLocation());
6851 if (Reader.readBool())
6852 TL.setSizeExpr(Reader.readExpr());
6853 else
6854 TL.setSizeExpr(nullptr);
6855}
6856
6857void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6858 VisitArrayTypeLoc(TL);
6859}
6860
6861void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6862 VisitArrayTypeLoc(TL);
6863}
6864
6865void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6866 VisitArrayTypeLoc(TL);
6867}
6868
6869void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6871 VisitArrayTypeLoc(TL);
6872}
6873
6874void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6876
6877 TL.setAttrNameLoc(readSourceLocation());
6878 TL.setAttrOperandParensRange(readSourceRange());
6879 TL.setAttrExprOperand(Reader.readExpr());
6880}
6881
6882void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6884 TL.setNameLoc(readSourceLocation());
6885}
6886
6887void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6888 TL.setNameLoc(readSourceLocation());
6889}
6890
6891void TypeLocReader::VisitDependentVectorTypeLoc(
6893 TL.setNameLoc(readSourceLocation());
6894}
6895
6896void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6897 TL.setNameLoc(readSourceLocation());
6898}
6899
6900void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6901 TL.setAttrNameLoc(readSourceLocation());
6902 TL.setAttrOperandParensRange(readSourceRange());
6903 TL.setAttrRowOperand(Reader.readExpr());
6904 TL.setAttrColumnOperand(Reader.readExpr());
6905}
6906
6907void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6909 TL.setAttrNameLoc(readSourceLocation());
6910 TL.setAttrOperandParensRange(readSourceRange());
6911 TL.setAttrRowOperand(Reader.readExpr());
6912 TL.setAttrColumnOperand(Reader.readExpr());
6913}
6914
6916 TL.setLocalRangeBegin(readSourceLocation());
6917 TL.setLParenLoc(readSourceLocation());
6918 TL.setRParenLoc(readSourceLocation());
6919 TL.setExceptionSpecRange(readSourceRange());
6920 TL.setLocalRangeEnd(readSourceLocation());
6921 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6922 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6923 }
6924}
6925
6926void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6927 VisitFunctionTypeLoc(TL);
6928}
6929
6930void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6931 VisitFunctionTypeLoc(TL);
6932}
6933
6934void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6935 TL.setNameLoc(readSourceLocation());
6936}
6937
6938void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
6939 TL.setNameLoc(readSourceLocation());
6940}
6941
6942void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6943 TL.setNameLoc(readSourceLocation());
6944}
6945
6946void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6947 TL.setTypeofLoc(readSourceLocation());
6948 TL.setLParenLoc(readSourceLocation());
6949 TL.setRParenLoc(readSourceLocation());
6950}
6951
6952void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6953 TL.setTypeofLoc(readSourceLocation());
6954 TL.setLParenLoc(readSourceLocation());
6955 TL.setRParenLoc(readSourceLocation());
6956 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
6957}
6958
6959void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6960 TL.setDecltypeLoc(readSourceLocation());
6961 TL.setRParenLoc(readSourceLocation());
6962}
6963
6964void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6965 TL.setEllipsisLoc(readSourceLocation());
6966}
6967
6968void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6969 TL.setKWLoc(readSourceLocation());
6970 TL.setLParenLoc(readSourceLocation());
6971 TL.setRParenLoc(readSourceLocation());
6972 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6973}
6974
6976 auto NNS = readNestedNameSpecifierLoc();
6977 auto TemplateKWLoc = readSourceLocation();
6978 auto ConceptNameLoc = readDeclarationNameInfo();
6979 auto FoundDecl = readDeclAs<NamedDecl>();
6980 auto NamedConcept = readDeclAs<ConceptDecl>();
6981 auto *CR = ConceptReference::Create(
6982 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
6983 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
6984 return CR;
6985}
6986
6987void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6988 TL.setNameLoc(readSourceLocation());
6989 if (Reader.readBool())
6990 TL.setConceptReference(Reader.readConceptReference());
6991 if (Reader.readBool())
6992 TL.setRParenLoc(readSourceLocation());
6993}
6994
6995void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6997 TL.setTemplateNameLoc(readSourceLocation());
6998}
6999
7000void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7001 TL.setNameLoc(readSourceLocation());
7002}
7003
7004void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
7005 TL.setNameLoc(readSourceLocation());
7006}
7007
7008void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7009 TL.setAttr(ReadAttr());
7010}
7011
7012void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7013 // Nothing to do
7014}
7015
7016void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7017 // Nothing to do.
7018}
7019
7020void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7021 TL.setNameLoc(readSourceLocation());
7022}
7023
7024void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7026 TL.setNameLoc(readSourceLocation());
7027}
7028
7029void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7031 TL.setNameLoc(readSourceLocation());
7032}
7033
7034void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7036 TL.setTemplateKeywordLoc(readSourceLocation());
7037 TL.setTemplateNameLoc(readSourceLocation());
7038 TL.setLAngleLoc(readSourceLocation());
7039 TL.setRAngleLoc(readSourceLocation());
7040 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
7041 TL.setArgLocInfo(i,
7042 Reader.readTemplateArgumentLocInfo(
7043 TL.getTypePtr()->template_arguments()[i].getKind()));
7044}
7045
7046void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7047 TL.setLParenLoc(readSourceLocation());
7048 TL.setRParenLoc(readSourceLocation());
7049}
7050
7051void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
7052 TL.setElaboratedKeywordLoc(readSourceLocation());
7053 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7054}
7055
7056void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7057 TL.setNameLoc(readSourceLocation());
7058}
7059
7060void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7061 TL.setElaboratedKeywordLoc(readSourceLocation());
7062 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7063 TL.setNameLoc(readSourceLocation());
7064}
7065
7066void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7068 TL.setElaboratedKeywordLoc(readSourceLocation());
7069 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7070 TL.setTemplateKeywordLoc(readSourceLocation());
7071 TL.setTemplateNameLoc(readSourceLocation());
7072 TL.setLAngleLoc(readSourceLocation());
7073 TL.setRAngleLoc(readSourceLocation());
7074 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7075 TL.setArgLocInfo(I,
7076 Reader.readTemplateArgumentLocInfo(
7077 TL.getTypePtr()->template_arguments()[I].getKind()));
7078}
7079
7080void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7081 TL.setEllipsisLoc(readSourceLocation());
7082}
7083
7084void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7085 TL.setNameLoc(readSourceLocation());
7086 TL.setNameEndLoc(readSourceLocation());
7087}
7088
7089void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7090 if (TL.getNumProtocols()) {
7091 TL.setProtocolLAngleLoc(readSourceLocation());
7092 TL.setProtocolRAngleLoc(readSourceLocation());
7093 }
7094 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7095 TL.setProtocolLoc(i, readSourceLocation());
7096}
7097
7098void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7099 TL.setHasBaseTypeAsWritten(Reader.readBool());
7100 TL.setTypeArgsLAngleLoc(readSourceLocation());
7101 TL.setTypeArgsRAngleLoc(readSourceLocation());
7102 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7103 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7104 TL.setProtocolLAngleLoc(readSourceLocation());
7105 TL.setProtocolRAngleLoc(readSourceLocation());
7106 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7107 TL.setProtocolLoc(i, readSourceLocation());
7108}
7109
7110void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7111 TL.setStarLoc(readSourceLocation());
7112}
7113
7114void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7115 TL.setKWLoc(readSourceLocation());
7116 TL.setLParenLoc(readSourceLocation());
7117 TL.setRParenLoc(readSourceLocation());
7118}
7119
7120void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7121 TL.setKWLoc(readSourceLocation());
7122}
7123
7124void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7125 TL.setNameLoc(readSourceLocation());
7126}
7127void TypeLocReader::VisitDependentBitIntTypeLoc(
7129 TL.setNameLoc(readSourceLocation());
7130}
7131
7133 LocSeq::State Seq(ParentSeq);
7134 TypeLocReader TLR(*this, Seq);
7135 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7136 TLR.Visit(TL);
7137}
7138
7140 QualType InfoTy = readType();
7141 if (InfoTy.isNull())
7142 return nullptr;
7143
7144 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7145 readTypeLoc(TInfo->getTypeLoc());
7146 return TInfo;
7147}
7148
7150 assert(ContextObj && "reading type with no AST context");
7151 ASTContext &Context = *ContextObj;
7152
7153 unsigned FastQuals = ID & Qualifiers::FastMask;
7154 unsigned Index = ID >> Qualifiers::FastWidth;
7155
7156 if (Index < NUM_PREDEF_TYPE_IDS) {
7157 QualType T;
7158 switch ((PredefinedTypeIDs)Index) {
7160 // We should never use this one.
7161 llvm_unreachable("Invalid predefined type");
7162 break;
7164 return QualType();
7166 T = Context.VoidTy;
7167 break;
7169 T = Context.BoolTy;
7170 break;
7173 // FIXME: Check that the signedness of CharTy is correct!
7174 T = Context.CharTy;
7175 break;
7177 T = Context.UnsignedCharTy;
7178 break;
7180 T = Context.UnsignedShortTy;
7181 break;
7183 T = Context.UnsignedIntTy;
7184 break;
7186 T = Context.UnsignedLongTy;
7187 break;
7189 T = Context.UnsignedLongLongTy;
7190 break;
7192 T = Context.UnsignedInt128Ty;
7193 break;
7195 T = Context.SignedCharTy;
7196 break;
7198 T = Context.WCharTy;
7199 break;
7201 T = Context.ShortTy;
7202 break;
7203 case PREDEF_TYPE_INT_ID:
7204 T = Context.IntTy;
7205 break;
7207 T = Context.LongTy;
7208 break;
7210 T = Context.LongLongTy;
7211 break;
7213 T = Context.Int128Ty;
7214 break;
7216 T = Context.BFloat16Ty;
7217 break;
7219 T = Context.HalfTy;
7220 break;
7222 T = Context.FloatTy;
7223 break;
7225 T = Context.DoubleTy;
7226 break;
7228 T = Context.LongDoubleTy;
7229 break;
7231 T = Context.ShortAccumTy;
7232 break;
7234 T = Context.AccumTy;
7235 break;
7237 T = Context.LongAccumTy;
7238 break;
7240 T = Context.UnsignedShortAccumTy;
7241 break;
7243 T = Context.UnsignedAccumTy;
7244 break;
7246 T = Context.UnsignedLongAccumTy;
7247 break;
7249 T = Context.ShortFractTy;
7250 break;
7252 T = Context.FractTy;
7253 break;
7255 T = Context.LongFractTy;
7256 break;
7258 T = Context.UnsignedShortFractTy;
7259 break;
7261 T = Context.UnsignedFractTy;
7262 break;
7264 T = Context.UnsignedLongFractTy;
7265 break;
7267 T = Context.SatShortAccumTy;
7268 break;
7270 T = Context.SatAccumTy;
7271 break;
7273 T = Context.SatLongAccumTy;
7274 break;
7276 T = Context.SatUnsignedShortAccumTy;
7277 break;
7279 T = Context.SatUnsignedAccumTy;
7280 break;
7282 T = Context.SatUnsignedLongAccumTy;
7283 break;
7285 T = Context.SatShortFractTy;
7286 break;
7288 T = Context.SatFractTy;
7289 break;
7291 T = Context.SatLongFractTy;
7292 break;
7294 T = Context.SatUnsignedShortFractTy;
7295 break;
7297 T = Context.SatUnsignedFractTy;
7298 break;
7300 T = Context.SatUnsignedLongFractTy;
7301 break;
7303 T = Context.Float16Ty;
7304 break;
7306 T = Context.Float128Ty;
7307 break;
7309 T = Context.Ibm128Ty;
7310 break;
7312 T = Context.OverloadTy;
7313 break;
7315 T = Context.BoundMemberTy;
7316 break;
7318 T = Context.PseudoObjectTy;
7319 break;
7321 T = Context.DependentTy;
7322 break;
7324 T = Context.UnknownAnyTy;
7325 break;
7327 T = Context.NullPtrTy;
7328 break;
7330 T = Context.Char8Ty;
7331 break;
7333 T = Context.Char16Ty;
7334 break;
7336 T = Context.Char32Ty;
7337 break;
7339 T = Context.ObjCBuiltinIdTy;
7340 break;
7342 T = Context.ObjCBuiltinClassTy;
7343 break;
7345 T = Context.ObjCBuiltinSelTy;
7346 break;
7347#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7348 case PREDEF_TYPE_##Id##_ID: \
7349 T = Context.SingletonId; \
7350 break;
7351#include "clang/Basic/OpenCLImageTypes.def"
7352#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7353 case PREDEF_TYPE_##Id##_ID: \
7354 T = Context.Id##Ty; \
7355 break;
7356#include "clang/Basic/OpenCLExtensionTypes.def"
7358 T = Context.OCLSamplerTy;
7359 break;
7361 T = Context.OCLEventTy;
7362 break;
7364 T = Context.OCLClkEventTy;
7365 break;
7367 T = Context.OCLQueueTy;
7368 break;
7370 T = Context.OCLReserveIDTy;
7371 break;
7373 T = Context.getAutoDeductType();
7374 break;
7376 T = Context.getAutoRRefDeductType();
7377 break;
7379 T = Context.ARCUnbridgedCastTy;
7380 break;
7382 T = Context.BuiltinFnTy;
7383 break;
7385 T = Context.IncompleteMatrixIdxTy;
7386 break;
7388 T = Context.OMPArraySectionTy;
7389 break;
7391 T = Context.OMPArraySectionTy;
7392 break;
7394 T = Context.OMPIteratorTy;
7395 break;
7396#define SVE_TYPE(Name, Id, SingletonId) \
7397 case PREDEF_TYPE_##Id##_ID: \
7398 T = Context.SingletonId; \
7399 break;
7400#include "clang/Basic/AArch64SVEACLETypes.def"
7401#define PPC_VECTOR_TYPE(Name, Id, Size) \
7402 case PREDEF_TYPE_##Id##_ID: \
7403 T = Context.Id##Ty; \
7404 break;
7405#include "clang/Basic/PPCTypes.def"
7406#define RVV_TYPE(Name, Id, SingletonId) \
7407 case PREDEF_TYPE_##Id##_ID: \
7408 T = Context.SingletonId; \
7409 break;
7410#include "clang/Basic/RISCVVTypes.def"
7411#define WASM_TYPE(Name, Id, SingletonId) \
7412 case PREDEF_TYPE_##Id##_ID: \
7413 T = Context.SingletonId; \
7414 break;
7415#include "clang/Basic/WebAssemblyReferenceTypes.def"
7416 }
7417
7418 assert(!T.isNull() && "Unknown predefined type");
7419 return T.withFastQualifiers(FastQuals);
7420 }
7421
7422 Index -= NUM_PREDEF_TYPE_IDS;
7423 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7424 if (TypesLoaded[Index].isNull()) {
7425 TypesLoaded[Index] = readTypeRecord(Index);
7426 if (TypesLoaded[Index].isNull())
7427 return QualType();
7428
7429 TypesLoaded[Index]->setFromAST();
7430 if (DeserializationListener)
7431 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7432 TypesLoaded[Index]);
7433 }
7434
7435 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7436}
7437
7439 return GetType(getGlobalTypeID(F, LocalID));
7440}
7441
7443ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7444 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7445 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
7446
7447 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7448 return LocalID;
7449
7450 if (!F.ModuleOffsetMap.empty())
7451 ReadModuleOffsetMap(F);
7452
7454 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7455 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
7456
7457 unsigned GlobalIndex = LocalIndex + I->second;
7458 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7459}
7460
7463 switch (Kind) {
7465 return readExpr();
7467 return readTypeSourceInfo();
7469 NestedNameSpecifierLoc QualifierLoc =
7470 readNestedNameSpecifierLoc();
7471 SourceLocation TemplateNameLoc = readSourceLocation();
7472 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7473 TemplateNameLoc, SourceLocation());
7474 }
7476 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7477 SourceLocation TemplateNameLoc = readSourceLocation();
7478 SourceLocation EllipsisLoc = readSourceLocation();
7479 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7480 TemplateNameLoc, EllipsisLoc);
7481 }
7488 // FIXME: Is this right?
7489 return TemplateArgumentLocInfo();
7490 }
7491 llvm_unreachable("unexpected template argument loc");
7492}
7493
7495 TemplateArgument Arg = readTemplateArgument();
7496
7498 if (readBool()) // bool InfoHasSameExpr.
7500 }
7501 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7502}
7503
7506 Result.setLAngleLoc(readSourceLocation());
7507 Result.setRAngleLoc(readSourceLocation());
7508 unsigned NumArgsAsWritten = readInt();
7509 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7510 Result.addArgument(readTemplateArgumentLoc());
7511}
7512
7516 readTemplateArgumentListInfo(Result);
7517 return ASTTemplateArgumentListInfo::Create(getContext(), Result);
7518}
7519
7521 return GetDecl(GlobalDeclID(ID));
7522}
7523
7525 if (NumCurrentElementsDeserializing) {
7526 // We arrange to not care about the complete redeclaration chain while we're
7527 // deserializing. Just remember that the AST has marked this one as complete
7528 // but that it's not actually complete yet, so we know we still need to
7529 // complete it later.
7530 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7531 return;
7532 }
7533
7534 if (!D->getDeclContext()) {
7535 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7536 return;
7537 }
7538
7539 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7540
7541 // If this is a named declaration, complete it by looking it up
7542 // within its context.
7543 //
7544 // FIXME: Merging a function definition should merge
7545 // all mergeable entities within it.
7546 if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
7547 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7548 if (!getContext().getLangOpts().CPlusPlus &&
7549 isa<TranslationUnitDecl>(DC)) {
7550 // Outside of C++, we don't have a lookup table for the TU, so update
7551 // the identifier instead. (For C++ modules, we don't store decls
7552 // in the serialized identifier table, so we do the lookup in the TU.)
7553 auto *II = Name.getAsIdentifierInfo();
7554 assert(II && "non-identifier name in C?");
7555 if (II->isOutOfDate())
7556 updateOutOfDateIdentifier(*II);
7557 } else
7558 DC->lookup(Name);
7559 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7560 // Find all declarations of this kind from the relevant context.
7561 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7562 auto *DC = cast<DeclContext>(DCDecl);
7564 FindExternalLexicalDecls(
7565 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7566 }
7567 }
7568 }
7569
7570 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7571 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7572 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7573 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7574 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7575 if (auto *Template = FD->getPrimaryTemplate())
7576 Template->LoadLazySpecializations();
7577 }
7578}
7579
7582 RecordLocation Loc = getLocalBitOffset(Offset);
7583 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7584 SavedStreamPosition SavedPosition(Cursor);
7585 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7586 Error(std::move(Err));
7587 return nullptr;
7588 }
7589 ReadingKindTracker ReadingKind(Read_Decl, *this);
7590 Deserializing D(this);
7591
7592 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7593 if (!MaybeCode) {
7594 Error(MaybeCode.takeError());
7595 return nullptr;
7596 }
7597 unsigned Code = MaybeCode.get();
7598
7599 ASTRecordReader Record(*this, *Loc.F);
7600 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7601 if (!MaybeRecCode) {
7602 Error(MaybeRecCode.takeError());
7603 return nullptr;
7604 }
7605 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7606 Error("malformed AST file: missing C++ ctor initializers");
7607 return nullptr;
7608 }
7609
7610 return Record.readCXXCtorInitializers();
7611}
7612
7614 assert(ContextObj && "reading base specifiers with no AST context");
7615 ASTContext &Context = *ContextObj;
7616
7617 RecordLocation Loc = getLocalBitOffset(Offset);
7618 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7619 SavedStreamPosition SavedPosition(Cursor);
7620 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7621 Error(std::move(Err));
7622 return nullptr;
7623 }
7624 ReadingKindTracker ReadingKind(Read_Decl, *this);
7625 Deserializing D(this);
7626
7627 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7628 if (!MaybeCode) {
7629 Error(MaybeCode.takeError());
7630 return nullptr;
7631 }
7632 unsigned Code = MaybeCode.get();
7633
7634 ASTRecordReader Record(*this, *Loc.F);
7635 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7636 if (!MaybeRecCode) {
7637 Error(MaybeCode.takeError());
7638 return nullptr;
7639 }
7640 unsigned RecCode = MaybeRecCode.get();
7641
7642 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7643 Error("malformed AST file: missing C++ base specifiers");
7644 return nullptr;
7645 }
7646
7647 unsigned NumBases = Record.readInt();
7648 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7649 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7650 for (unsigned I = 0; I != NumBases; ++I)
7651 Bases[I] = Record.readCXXBaseSpecifier();
7652 return Bases;
7653}
7654
7656 LocalDeclID LocalID) const {
7657 DeclID ID = LocalID.get();
7658 if (ID < NUM_PREDEF_DECL_IDS)
7659 return GlobalDeclID(ID);
7660
7661 if (!F.ModuleOffsetMap.empty())
7662 ReadModuleOffsetMap(F);
7663
7666 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
7667
7668 return GlobalDeclID(ID + I->second);
7669}
7670
7672 ModuleFile &M) const {
7673 // Predefined decls aren't from any module.
7674 if (ID.get() < NUM_PREDEF_DECL_IDS)
7675 return false;
7676
7677 return ID.get() - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7678 ID.get() - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
7679}
7680
7682 if (!D->isFromASTFile())
7683 return nullptr;
7685 GlobalDeclMap.find(GlobalDeclID(D->getGlobalID()));
7686 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7687 return I->second;
7688}
7689
7691 if (ID.get() < NUM_PREDEF_DECL_IDS)
7692 return SourceLocation();
7693
7694 unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7695
7696 if (Index > DeclsLoaded.size()) {
7697 Error("declaration ID out-of-range for AST file");
7698 return SourceLocation();
7699 }
7700
7701 if (Decl *D = DeclsLoaded[Index])
7702 return D->getLocation();
7703
7704 SourceLocation Loc;
7705 DeclCursorForID(ID, Loc);
7706 return Loc;
7707}
7708
7710 switch (ID) {
7712 return nullptr;
7713
7715 return Context.getTranslationUnitDecl();
7716
7718 return Context.getObjCIdDecl();
7719
7721 return Context.getObjCSelDecl();
7722
7724 return Context.getObjCClassDecl();
7725
7727 return Context.getObjCProtocolDecl();
7728
7730 return Context.getInt128Decl();
7731
7733 return Context.getUInt128Decl();
7734
7736 return Context.getObjCInstanceTypeDecl();
7737
7739 return Context.getBuiltinVaListDecl();
7740
7742 return Context.getVaListTagDecl();
7743
7745 return Context.getBuiltinMSVaListDecl();
7746
7748 return Context.getMSGuidTagDecl();
7749
7751 return Context.getExternCContextDecl();
7752
7754 return Context.getMakeIntegerSeqDecl();
7755
7757 return Context.getCFConstantStringDecl();
7758
7760 return Context.getCFConstantStringTagDecl();
7761
7763 return Context.getTypePackElementDecl();
7764 }
7765 llvm_unreachable("PredefinedDeclIDs unknown enum value");
7766}
7767
7769 assert(ContextObj && "reading decl with no AST context");
7770 if (ID.get() < NUM_PREDEF_DECL_IDS) {
7771 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID.get());
7772 if (D) {
7773 // Track that we have merged the declaration with ID \p ID into the
7774 // pre-existing predefined declaration \p D.
7775 auto &Merged = KeyDecls[D->getCanonicalDecl()];
7776 if (Merged.empty())
7777 Merged.push_back(ID);
7778 }
7779 return D;
7780 }
7781
7782 unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7783
7784 if (Index >= DeclsLoaded.size()) {
7785 assert(0 && "declaration ID out-of-range for AST file");
7786 Error("declaration ID out-of-range for AST file");
7787 return nullptr;
7788 }
7789
7790 return DeclsLoaded[Index];
7791}
7792
7794 if (ID.get() < NUM_PREDEF_DECL_IDS)
7795 return GetExistingDecl(ID);
7796
7797 unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7798
7799 if (Index >= DeclsLoaded.size()) {
7800 assert(0 && "declaration ID out-of-range for AST file");
7801 Error("declaration ID out-of-range for AST file");
7802 return nullptr;
7803 }
7804
7805 if (!DeclsLoaded[Index]) {
7806 ReadDeclRecord(ID);
7807 if (DeserializationListener)
7808 DeserializationListener->DeclRead(ID.get(), DeclsLoaded[Index]);
7809 }
7810
7811 return DeclsLoaded[Index];
7812}
7813
7815 GlobalDeclID GlobalID) {
7816 DeclID ID = GlobalID.get();
7817 if (ID < NUM_PREDEF_DECL_IDS)
7818 return ID;
7819
7820 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7821 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7822 ModuleFile *Owner = I->second;
7823
7824 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7825 = M.GlobalToLocalDeclIDs.find(Owner);
7826 if (Pos == M.GlobalToLocalDeclIDs.end())
7827 return 0;
7828
7829 return ID - Owner->BaseDeclID + Pos->second;
7830}
7831
7833 unsigned &Idx) {
7834 if (Idx >= Record.size()) {
7835 Error("Corrupted AST file");
7836 return GlobalDeclID(0);
7837 }
7838
7839 return getGlobalDeclID(F, LocalDeclID(Record[Idx++]));
7840}
7841
7842/// Resolve the offset of a statement into a statement.
7843///
7844/// This operation will read a new statement from the external
7845/// source each time it is called, and is meant to be used via a
7846/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7848 // Switch case IDs are per Decl.
7849 ClearSwitchCaseIDs();
7850
7851 // Offset here is a global offset across the entire chain.
7852 RecordLocation Loc = getLocalBitOffset(Offset);
7853 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7854 Error(std::move(Err));
7855 return nullptr;
7856 }
7857 assert(NumCurrentElementsDeserializing == 0 &&
7858 "should not be called while already deserializing");
7859 Deserializing D(this);
7860 return ReadStmtFromStream(*Loc.F);
7861}
7862
7864 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7865 SmallVectorImpl<Decl *> &Decls) {
7866 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7867
7868 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7869 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7870 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7871 auto K = (Decl::Kind)+LexicalDecls[I];
7872 if (!IsKindWeWant(K))
7873 continue;
7874
7875 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7876
7877 // Don't add predefined declarations to the lexical context more
7878 // than once.
7879 if (ID < NUM_PREDEF_DECL_IDS) {
7880 if (PredefsVisited[ID])
7881 continue;
7882
7883 PredefsVisited[ID] = true;
7884 }
7885
7886 if (Decl *D = GetLocalDecl(*M, LocalDeclID(ID))) {
7887 assert(D->getKind() == K && "wrong kind for lexical decl");
7888 if (!DC->isDeclInLexicalTraversal(D))
7889 Decls.push_back(D);
7890 }
7891 }
7892 };
7893
7894 if (isa<TranslationUnitDecl>(DC)) {
7895 for (const auto &Lexical : TULexicalDecls)
7896 Visit(Lexical.first, Lexical.second);
7897 } else {
7898 auto I = LexicalDecls.find(DC);
7899 if (I != LexicalDecls.end())
7900 Visit(I->second.first, I->second.second);
7901 }
7902
7903 ++NumLexicalDeclContextsRead;
7904}
7905
7906namespace {
7907
7908class DeclIDComp {
7909 ASTReader &Reader;
7910 ModuleFile &Mod;
7911
7912public:
7913 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7914
7915 bool operator()(LocalDeclID L, LocalDeclID R) const {
7916 SourceLocation LHS = getLocation(L);
7917 SourceLocation RHS = getLocation(R);
7918 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7919 }
7920
7921 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7922 SourceLocation RHS = getLocation(R);
7923 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7924 }
7925
7926 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7927 SourceLocation LHS = getLocation(L);
7928 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7929 }
7930
7931 SourceLocation getLocation(LocalDeclID ID) const {
7932 return Reader.getSourceManager().getFileLoc(
7933 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7934 }
7935};
7936
7937} // namespace
7938
7940 unsigned Offset, unsigned Length,
7941 SmallVectorImpl<Decl *> &Decls) {
7942 SourceManager &SM = getSourceManager();
7943
7944 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7945 if (I == FileDeclIDs.end())
7946 return;
7947
7948 FileDeclsInfo &DInfo = I->second;
7949 if (DInfo.Decls.empty())
7950 return;
7951
7953 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7954 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7955
7956 DeclIDComp DIDComp(*this, *DInfo.Mod);
7958 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
7959 if (BeginIt != DInfo.Decls.begin())
7960 --BeginIt;
7961
7962 // If we are pointing at a top-level decl inside an objc container, we need
7963 // to backtrack until we find it otherwise we will fail to report that the
7964 // region overlaps with an objc container.
7965 while (BeginIt != DInfo.Decls.begin() &&
7966 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7967 ->isTopLevelDeclInObjCContainer())
7968 --BeginIt;
7969
7971 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
7972 if (EndIt != DInfo.Decls.end())
7973 ++EndIt;
7974
7976 DIt = BeginIt; DIt != EndIt; ++DIt)
7977 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7978}
7979
7980bool
7982 DeclarationName Name) {
7983 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7984 "DeclContext has no visible decls in storage");
7985 if (!Name)
7986 return false;
7987
7988 auto It = Lookups.find(DC);
7989 if (It == Lookups.end())
7990 return false;
7991
7992 Deserializing LookupResults(this);
7993
7994 // Load the list of declarations.
7997 for (GlobalDeclID ID : It->second.Table.find(Name)) {
7998 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7999 if (ND->getDeclName() == Name && Found.insert(ND).second)
8000 Decls.push_back(ND);
8001 }
8002
8003 ++NumVisibleDeclContextsRead;
8004 SetExternalVisibleDeclsForName(DC, Name, Decls);
8005 return !Decls.empty();
8006}
8007
8009 if (!DC->hasExternalVisibleStorage())
8010 return;
8011
8012 auto It = Lookups.find(DC);
8013 assert(It != Lookups.end() &&
8014 "have external visible storage but no lookup tables");
8015
8016 DeclsMap Decls;
8017
8018 for (GlobalDeclID ID : It->second.Table.findAll()) {
8019 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8020 Decls[ND->getDeclName()].push_back(ND);
8021 }
8022
8023 ++NumVisibleDeclContextsRead;
8024
8025 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8026 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8027 }
8028 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8029}
8030
8033 auto I = Lookups.find(Primary);
8034 return I == Lookups.end() ? nullptr : &I->second;
8035}
8036
8037/// Under non-PCH compilation the consumer receives the objc methods
8038/// before receiving the implementation, and codegen depends on this.
8039/// We simulate this by deserializing and passing to consumer the methods of the
8040/// implementation before passing the deserialized implementation decl.
8042 ASTConsumer *Consumer) {
8043 assert(ImplD && Consumer);
8044
8045 for (auto *I : ImplD->methods())
8046 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8047
8048 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8049}
8050
8051void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8052 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8053 PassObjCImplDeclToConsumer(ImplD, Consumer);
8054 else
8055 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8056}
8057
8059 this->Consumer = Consumer;
8060
8061 if (Consumer)
8062 PassInterestingDeclsToConsumer();
8063
8064 if (DeserializationListener)
8065 DeserializationListener->ReaderInitialized(this);
8066}
8067
8069 std::fprintf(stderr, "*** AST File Statistics:\n");
8070
8071 unsigned NumTypesLoaded =
8072 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8073 unsigned NumDeclsLoaded =
8074 DeclsLoaded.size() -
8075 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8076 unsigned NumIdentifiersLoaded =
8077 IdentifiersLoaded.size() -
8078 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8079 unsigned NumMacrosLoaded =
8080 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8081 unsigned NumSelectorsLoaded =
8082 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8083
8084 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8085 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8086 NumSLocEntriesRead, TotalNumSLocEntries,
8087 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8088 if (!TypesLoaded.empty())
8089 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8090 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8091 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8092 if (!DeclsLoaded.empty())
8093 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8094 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8095 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8096 if (!IdentifiersLoaded.empty())
8097 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8098 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8099 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8100 if (!MacrosLoaded.empty())
8101 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8102 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8103 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8104 if (!SelectorsLoaded.empty())
8105 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8106 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8107 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8108 if (TotalNumStatements)
8109 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8110 NumStatementsRead, TotalNumStatements,
8111 ((float)NumStatementsRead/TotalNumStatements * 100));
8112 if (TotalNumMacros)
8113 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8114 NumMacrosRead, TotalNumMacros,
8115 ((float)NumMacrosRead/TotalNumMacros * 100));
8116 if (TotalLexicalDeclContexts)
8117 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8118 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8119 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8120 * 100));
8121 if (TotalVisibleDeclContexts)
8122 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8123 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8124 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8125 * 100));
8126 if (TotalNumMethodPoolEntries)
8127 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8128 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8129 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8130 * 100));
8131 if (NumMethodPoolLookups)
8132 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8133 NumMethodPoolHits, NumMethodPoolLookups,
8134 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8135 if (NumMethodPoolTableLookups)
8136 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8137 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8138 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8139 * 100.0));
8140 if (NumIdentifierLookupHits)
8141 std::fprintf(stderr,
8142 " %u / %u identifier table lookups succeeded (%f%%)\n",
8143 NumIdentifierLookupHits, NumIdentifierLookups,
8144 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8145
8146 if (GlobalIndex) {
8147 std::fprintf(stderr, "\n");
8148 GlobalIndex->printStats();
8149 }
8150
8151 std::fprintf(stderr, "\n");
8152 dump();
8153 std::fprintf(stderr, "\n");
8154}
8155
8156template<typename Key, typename ModuleFile, unsigned InitialCapacity>
8157LLVM_DUMP_METHOD static void
8158dumpModuleIDMap(StringRef Name,
8159 const ContinuousRangeMap<Key, ModuleFile *,
8160 InitialCapacity> &Map) {
8161 if (Map.begin() == Map.end())
8162 return;
8163
8165
8166 llvm::errs() << Name << ":\n";
8167 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8168 I != IEnd; ++I) {
8169 uint64_t ID = 0;
8170 if constexpr (std::is_integral_v<Key>)
8171 ID = I->first;
8172 else /*GlobalDeclID*/
8173 ID = I->first.get();
8174 llvm::errs() << " " << ID << " -> " << I->second->FileName << "\n";
8175 }
8176}
8177
8178LLVM_DUMP_METHOD void ASTReader::dump() {
8179 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8180 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8181 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8182 dumpModuleIDMap("Global type map", GlobalTypeMap);
8183 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
8184 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
8185 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8186 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8187 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
8188 dumpModuleIDMap("Global preprocessed entity map",
8189 GlobalPreprocessedEntityMap);
8190
8191 llvm::errs() << "\n*** PCH/Modules Loaded:";
8192 for (ModuleFile &M : ModuleMgr)
8193 M.dump();
8194}
8195
8196/// Return the amount of memory used by memory buffers, breaking down
8197/// by heap-backed versus mmap'ed memory.
8199 for (ModuleFile &I : ModuleMgr) {
8200 if (llvm::MemoryBuffer *buf = I.Buffer) {
8201 size_t bytes = buf->getBufferSize();
8202 switch (buf->getBufferKind()) {
8203 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8204 sizes.malloc_bytes += bytes;
8205 break;
8206 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8207 sizes.mmap_bytes += bytes;
8208 break;
8209 }
8210 }
8211 }
8212}
8213
8215 SemaObj = &S;
8216 S.addExternalSource(this);
8217
8218 // Makes sure any declarations that were deserialized "too early"
8219 // still get added to the identifier's declaration chains.
8220 for (GlobalDeclID ID : PreloadedDeclIDs) {
8221 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
8222 pushExternalDeclIntoScope(D, D->getDeclName());
8223 }
8224 PreloadedDeclIDs.clear();
8225
8226 // FIXME: What happens if these are changed by a module import?
8227 if (!FPPragmaOptions.empty()) {
8228 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
8229 FPOptionsOverride NewOverrides =
8230 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
8231 SemaObj->CurFPFeatures =
8232 NewOverrides.applyOverrides(SemaObj->getLangOpts());
8233 }
8234
8235 SemaObj->OpenCLFeatures = OpenCLExtensions;
8236
8237 UpdateSema();
8238}
8239
8241 assert(SemaObj && "no Sema to update");
8242
8243 // Load the offsets of the declarations that Sema references.
8244 // They will be lazily deserialized when needed.
8245 if (!SemaDeclRefs.empty()) {
8246 assert(SemaDeclRefs.size() % 3 == 0);
8247 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
8248 if (!SemaObj->StdNamespace)
8249 SemaObj->StdNamespace = SemaDeclRefs[I].get();
8250 if (!SemaObj->StdBadAlloc)
8251 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].get();
8252 if (!SemaObj->StdAlignValT)
8253 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].get();
8254 }
8255 SemaDeclRefs.clear();
8256 }
8257
8258 // Update the state of pragmas. Use the same API as if we had encountered the
8259 // pragma in the source.
8260 if(OptimizeOffPragmaLocation.isValid())
8261 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
8262 if (PragmaMSStructState != -1)
8263 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
8264 if (PointersToMembersPragmaLocation.isValid()) {
8265 SemaObj->ActOnPragmaMSPointersToMembers(
8267 PragmaMSPointersToMembersState,
8268 PointersToMembersPragmaLocation);
8269 }
8270 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
8271
8272 if (PragmaAlignPackCurrentValue) {
8273 // The bottom of the stack might have a default value. It must be adjusted
8274 // to the current value to ensure that the packing state is preserved after
8275 // popping entries that were included/imported from a PCH/module.
8276 bool DropFirst = false;
8277 if (!PragmaAlignPackStack.empty() &&
8278 PragmaAlignPackStack.front().Location.isInvalid()) {
8279 assert(PragmaAlignPackStack.front().Value ==
8280 SemaObj->AlignPackStack.DefaultValue &&
8281 "Expected a default alignment value");
8282 SemaObj->AlignPackStack.Stack.emplace_back(
8283 PragmaAlignPackStack.front().SlotLabel,
8284 SemaObj->AlignPackStack.CurrentValue,
8285 SemaObj->AlignPackStack.CurrentPragmaLocation,
8286 PragmaAlignPackStack.front().PushLocation);
8287 DropFirst = true;
8288 }
8289 for (const auto &Entry :
8290 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
8291 SemaObj->AlignPackStack.Stack.emplace_back(
8292 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8293 }
8294 if (PragmaAlignPackCurrentLocation.isInvalid()) {
8295 assert(*PragmaAlignPackCurrentValue ==
8296 SemaObj->AlignPackStack.DefaultValue &&
8297 "Expected a default align and pack value");
8298 // Keep the current values.
8299 } else {
8300 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
8301 SemaObj->AlignPackStack.CurrentPragmaLocation =
8302 PragmaAlignPackCurrentLocation;
8303 }
8304 }
8305 if (FpPragmaCurrentValue) {
8306 // The bottom of the stack might have a default value. It must be adjusted
8307 // to the current value to ensure that fp-pragma state is preserved after
8308 // popping entries that were included/imported from a PCH/module.
8309 bool DropFirst = false;
8310 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
8311 assert(FpPragmaStack.front().Value ==
8312 SemaObj->FpPragmaStack.DefaultValue &&
8313 "Expected a default pragma float_control value");
8314 SemaObj->FpPragmaStack.Stack.emplace_back(
8315 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
8316 SemaObj->FpPragmaStack.CurrentPragmaLocation,
8317 FpPragmaStack.front().PushLocation);
8318 DropFirst = true;
8319 }
8320 for (const auto &Entry :
8321 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
8322 SemaObj->FpPragmaStack.Stack.emplace_back(
8323 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8324 if (FpPragmaCurrentLocation.isInvalid()) {
8325 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
8326 "Expected a default pragma float_control value");
8327 // Keep the current values.
8328 } else {
8329 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
8330 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
8331 }
8332 }
8333
8334 // For non-modular AST files, restore visiblity of modules.
8335 for (auto &Import : PendingImportedModulesSema) {
8336 if (Import.ImportLoc.isInvalid())
8337 continue;
8338 if (Module *Imported = getSubmodule(Import.ID)) {
8339 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8340 }
8341 }
8342 PendingImportedModulesSema.clear();
8343}
8344
8346 // Note that we are loading an identifier.
8347 Deserializing AnIdentifier(this);
8348
8349 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
8350 NumIdentifierLookups,
8351 NumIdentifierLookupHits);
8352
8353 // We don't need to do identifier table lookups in C++ modules (we preload
8354 // all interesting declarations, and don't need to use the scope for name
8355 // lookups). Perform the lookup in PCH files, though, since we don't build
8356 // a complete initial identifier table if we're carrying on from a PCH.
8357 if (PP.getLangOpts().CPlusPlus) {
8358 for (auto *F : ModuleMgr.pch_modules())
8359 if (Visitor(*F))
8360 break;
8361 } else {
8362 // If there is a global index, look there first to determine which modules
8363 // provably do not have any results for this identifier.
8365 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8366 if (!loadGlobalIndex()) {
8367 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8368 HitsPtr = &Hits;
8369 }
8370 }
8371
8372 ModuleMgr.visit(Visitor, HitsPtr);
8373 }
8374
8375 IdentifierInfo *II = Visitor.getIdentifierInfo();
8376 markIdentifierUpToDate(II);
8377 return II;
8378}
8379
8380namespace clang {
8381
8382 /// An identifier-lookup iterator that enumerates all of the
8383 /// identifiers stored within a set of AST files.
8385 /// The AST reader whose identifiers are being enumerated.
8386 const ASTReader &Reader;
8387
8388 /// The current index into the chain of AST files stored in
8389 /// the AST reader.
8390 unsigned Index;
8391
8392 /// The current position within the identifier lookup table
8393 /// of the current AST file.
8394 ASTIdentifierLookupTable::key_iterator Current;
8395
8396 /// The end position within the identifier lookup table of
8397 /// the current AST file.
8398 ASTIdentifierLookupTable::key_iterator End;
8399
8400 /// Whether to skip any modules in the ASTReader.
8401 bool SkipModules;
8402
8403 public:
8404 explicit ASTIdentifierIterator(const ASTReader &Reader,
8405 bool SkipModules = false);
8406
8407 StringRef Next() override;
8408 };
8409
8410} // namespace clang
8411
8413 bool SkipModules)
8414 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8415}
8416
8418 while (Current == End) {
8419 // If we have exhausted all of our AST files, we're done.
8420 if (Index == 0)
8421 return StringRef();
8422
8423 --Index;
8424 ModuleFile &F = Reader.ModuleMgr[Index];
8425 if (SkipModules && F.isModule())
8426 continue;
8427
8428 ASTIdentifierLookupTable *IdTable =
8430 Current = IdTable->key_begin();
8431 End = IdTable->key_end();
8432 }
8433
8434 // We have any identifiers remaining in the current AST file; return
8435 // the next one.
8436 StringRef Result = *Current;
8437 ++Current;
8438 return Result;
8439}
8440
8441namespace {
8442
8443/// A utility for appending two IdentifierIterators.
8444class ChainedIdentifierIterator : public IdentifierIterator {
8445 std::unique_ptr<IdentifierIterator> Current;
8446 std::unique_ptr<IdentifierIterator> Queued;
8447
8448public:
8449 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8450 std::unique_ptr<IdentifierIterator> Second)
8451 : Current(std::move(First)), Queued(std::move(Second)) {}
8452
8453 StringRef Next() override {
8454 if (!Current)
8455 return StringRef();
8456
8457 StringRef result = Current->Next();
8458 if (!result.empty())
8459 return result;
8460
8461 // Try the queued iterator, which may itself be empty.
8462 Current.reset();
8463 std::swap(Current, Queued);
8464 return Next();
8465 }
8466};
8467
8468} // namespace
8469
8471 if (!loadGlobalIndex()) {
8472 std::unique_ptr<IdentifierIterator> ReaderIter(
8473 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8474 std::unique_ptr<IdentifierIterator> ModulesIter(
8475 GlobalIndex->createIdentifierIterator());
8476 return new ChainedIdentifierIterator(std::move(ReaderIter),
8477 std::move(ModulesIter));
8478 }
8479
8480 return new ASTIdentifierIterator(*this);
8481}
8482
8483namespace clang {
8484namespace serialization {
8485
8487 ASTReader &Reader;
8488 Selector Sel;
8489 unsigned PriorGeneration;
8490 unsigned InstanceBits = 0;
8491 unsigned FactoryBits = 0;
8492 bool InstanceHasMoreThanOneDecl = false;
8493 bool FactoryHasMoreThanOneDecl = false;
8494 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8495 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8496
8497 public:
8499 unsigned PriorGeneration)
8500 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8501
8503 if (!M.SelectorLookupTable)
8504 return false;
8505
8506 // If we've already searched this module file, skip it now.
8507 if (M.Generation <= PriorGeneration)
8508 return true;
8509
8510 ++Reader.NumMethodPoolTableLookups;
8511 ASTSelectorLookupTable *PoolTable
8513 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8514 if (Pos == PoolTable->end())
8515 return false;
8516
8517 ++Reader.NumMethodPoolTableHits;
8518 ++Reader.NumSelectorsRead;
8519 // FIXME: Not quite happy with the statistics here. We probably should
8520 // disable this tracking when called via LoadSelector.
8521 // Also, should entries without methods count as misses?
8522 ++Reader.NumMethodPoolEntriesRead;
8524 if (Reader.DeserializationListener)
8525 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8526
8527 // Append methods in the reverse order, so that later we can process them
8528 // in the order they appear in the source code by iterating through
8529 // the vector in the reverse order.
8530 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8531 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8532 InstanceBits = Data.InstanceBits;
8533 FactoryBits = Data.FactoryBits;
8534 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8535 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8536 return false;
8537 }
8538
8539 /// Retrieve the instance methods found by this visitor.
8541 return InstanceMethods;
8542 }
8543
8544 /// Retrieve the instance methods found by this visitor.
8546 return FactoryMethods;
8547 }
8548
8549 unsigned getInstanceBits() const { return InstanceBits; }
8550 unsigned getFactoryBits() const { return FactoryBits; }
8551
8553 return InstanceHasMoreThanOneDecl;
8554 }
8555
8556 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8557 };
8558
8559} // namespace serialization
8560} // namespace clang
8561
8562/// Add the given set of methods to the method list.
8564 ObjCMethodList &List) {
8565 for (ObjCMethodDecl *M : llvm::reverse(Methods))
8566 S.addMethodToGlobalList(&List, M);
8567}
8568
8570 // Get the selector generation and update it to the current generation.
8571 unsigned &Generation = SelectorGeneration[Sel];
8572 unsigned PriorGeneration = Generation;
8573 Generation = getGeneration();
8574 SelectorOutOfDate[Sel] = false;
8575
8576 // Search for methods defined with this selector.
8577 ++NumMethodPoolLookups;
8578 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8579 ModuleMgr.visit(Visitor);
8580
8581 if (Visitor.getInstanceMethods().empty() &&
8582 Visitor.getFactoryMethods().empty())
8583 return;
8584
8585 ++NumMethodPoolHits;
8586
8587 if (!getSema())
8588 return;
8589
8590 Sema &S = *getSema();
8592 S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethodPool::Lists()))
8593 .first;
8594
8595 Pos->second.first.setBits(Visitor.getInstanceBits());
8596 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8597 Pos->second.second.setBits(Visitor.getFactoryBits());
8598 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8599
8600 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8601 // when building a module we keep every method individually and may need to
8602 // update hasMoreThanOneDecl as we add the methods.
8603 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8604 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8605}
8606
8608 if (SelectorOutOfDate[Sel])
8609 ReadMethodPool(Sel);
8610}
8611
8614 Namespaces.clear();
8615
8616 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8617 if (NamespaceDecl *Namespace
8618 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8619 Namespaces.push_back(Namespace);
8620 }
8621}
8622
8624 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8625 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8626 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
8627 NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID));
8629 Undefined.insert(std::make_pair(D, Loc));
8630 }
8631 UndefinedButUsed.clear();
8632}
8633
8635 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8636 Exprs) {
8637 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8638 FieldDecl *FD =
8639 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
8640 uint64_t Count = DelayedDeleteExprs[Idx++];
8641 for (uint64_t C = 0; C < Count; ++C) {
8642 SourceLocation DeleteLoc =
8643 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8644 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8645 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8646 }
8647 }
8648}
8649
8651 SmallVectorImpl<VarDecl *> &TentativeDefs) {
8652 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8653 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8654 if (Var)
8655 TentativeDefs.push_back(Var);
8656 }
8657 TentativeDefinitions.clear();
8658}
8659
8662 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8664 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8665 if (D)
8666 Decls.push_back(D);
8667 }
8668 UnusedFileScopedDecls.clear();
8669}
8670
8673 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8675 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8676 if (D)
8677 Decls.push_back(D);
8678 }
8679 DelegatingCtorDecls.clear();
8680}
8681
8683 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8685 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8686 if (D)
8687 Decls.push_back(D);
8688 }
8689 ExtVectorDecls.clear();
8690}
8691
8694 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8695 ++I) {
8696 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8697 GetDecl(UnusedLocalTypedefNameCandidates[I]));
8698 if (D)
8699 Decls.insert(D);
8700 }
8701 UnusedLocalTypedefNameCandidates.clear();
8702}
8703
8706 for (auto I : DeclsToCheckForDeferredDiags) {
8707 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
8708 if (D)
8709 Decls.insert(D);
8710 }
8711 DeclsToCheckForDeferredDiags.clear();
8712}
8713
8715 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8716 if (ReferencedSelectorsData.empty())
8717 return;
8718
8719 // If there are @selector references added them to its pool. This is for
8720 // implementation of -Wselector.
8721 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8722 unsigned I = 0;
8723 while (I < DataSize) {
8724 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8725 SourceLocation SelLoc
8726 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8727 Sels.push_back(std::make_pair(Sel, SelLoc));
8728 }
8729 ReferencedSelectorsData.clear();
8730}
8731
8733 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8734 if (WeakUndeclaredIdentifiers.empty())
8735 return;
8736
8737 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8738 IdentifierInfo *WeakId
8739 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8740 IdentifierInfo *AliasId
8741 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8742 SourceLocation Loc =
8743 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8744 WeakInfo WI(AliasId, Loc);
8745 WeakIDs.push_back(std::make_pair(WeakId, WI));
8746 }
8747 WeakUndeclaredIdentifiers.clear();
8748}
8749
8751 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8753 VTableUse &TableInfo = VTableUses[Idx++];
8754 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
8755 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
8756 VT.DefinitionRequired = TableInfo.Used;
8757 VTables.push_back(VT);
8758 }
8759
8760 VTableUses.clear();
8761}
8762
8764 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8765 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8766 PendingInstantiation &Inst = PendingInstantiations[Idx++];
8767 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
8769
8770 Pending.push_back(std::make_pair(D, Loc));
8771 }
8772 PendingInstantiations.clear();
8773}
8774
8776 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8777 &LPTMap) {
8778 for (auto &LPT : LateParsedTemplates) {
8779 ModuleFile *FMod = LPT.first;
8780 RecordDataImpl &LateParsed = LPT.second;
8781 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
8782 /* In loop */) {
8783 FunctionDecl *FD = cast<FunctionDecl>(
8784 GetLocalDecl(*FMod, LocalDeclID(LateParsed[Idx++])));
8785
8786 auto LT = std::make_unique<LateParsedTemplate>();
8787 LT->D = GetLocalDecl(*FMod, LocalDeclID(LateParsed[Idx++]));
8788 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
8789
8791 assert(F && "No module");
8792
8793 unsigned TokN = LateParsed[Idx++];
8794 LT->Toks.reserve(TokN);
8795 for (unsigned T = 0; T < TokN; ++T)
8796 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
8797
8798 LPTMap.insert(std::make_pair(FD, std::move(LT)));
8799 }
8800 }
8801
8802 LateParsedTemplates.clear();
8803}
8804
8806 if (Lambda->getLambdaContextDecl()) {
8807 // Keep track of this lambda so it can be merged with another lambda that
8808 // is loaded later.
8809 LambdaDeclarationsForMerging.insert(
8811 Lambda->getLambdaIndexInContext()},
8812 const_cast<CXXRecordDecl *>(Lambda)});
8813 }
8814}
8815
8817 // It would be complicated to avoid reading the methods anyway. So don't.
8818 ReadMethodPool(Sel);
8819}
8820
8822 assert(ID && "Non-zero identifier ID required");
8823 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8824 IdentifiersLoaded[ID - 1] = II;
8825 if (DeserializationListener)
8826 DeserializationListener->IdentifierRead(ID, II);
8827}
8828
8829/// Set the globally-visible declarations associated with the given
8830/// identifier.
8831///
8832/// If the AST reader is currently in a state where the given declaration IDs
8833/// cannot safely be resolved, they are queued until it is safe to resolve
8834/// them.
8835///
8836/// \param II an IdentifierInfo that refers to one or more globally-visible
8837/// declarations.
8838///
8839/// \param DeclIDs the set of declaration IDs with the name @p II that are
8840/// visible at global scope.
8841///
8842/// \param Decls if non-null, this vector will be populated with the set of
8843/// deserialized declarations. These declarations will not be pushed into
8844/// scope.
8847 SmallVectorImpl<Decl *> *Decls) {
8848 if (NumCurrentElementsDeserializing && !Decls) {
8849 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8850 return;
8851 }
8852
8853 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8854 if (!SemaObj) {
8855 // Queue this declaration so that it will be added to the
8856 // translation unit scope and identifier's declaration chain
8857 // once a Sema object is known.
8858 PreloadedDeclIDs.push_back(DeclIDs[I]);
8859 continue;
8860 }
8861
8862 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8863
8864 // If we're simply supposed to record the declarations, do so now.
8865 if (Decls) {
8866 Decls->push_back(D);
8867 continue;
8868 }
8869
8870 // Introduce this declaration into the translation-unit scope
8871 // and add it to the declaration chain for this identifier, so
8872 // that (unqualified) name lookup will find it.
8873 pushExternalDeclIntoScope(D, II);
8874 }
8875}
8876
8878 if (ID == 0)
8879 return nullptr;
8880
8881 if (IdentifiersLoaded.empty()) {
8882 Error("no identifier table in AST file");
8883 return nullptr;
8884 }
8885
8886 ID -= 1;
8887 if (!IdentifiersLoaded[ID]) {
8888 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8889 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8890 ModuleFile *M = I->second;
8891 unsigned Index = ID - M->BaseIdentifierID;
8892 const unsigned char *Data =
8894
8895 ASTIdentifierLookupTrait Trait(*this, *M);
8896 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
8897 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
8898 auto &II = PP.getIdentifierTable().get(Key);
8899 IdentifiersLoaded[ID] = &II;
8900 markIdentifierFromAST(*this, II);
8901 if (DeserializationListener)
8902 DeserializationListener->IdentifierRead(ID + 1, &II);
8903 }
8904
8905 return IdentifiersLoaded[ID];
8906}
8907
8909 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8910}
8911
8913 if (LocalID < NUM_PREDEF_IDENT_IDS)
8914 return LocalID;
8915
8916 if (!M.ModuleOffsetMap.empty())
8917 ReadModuleOffsetMap(M);
8918
8921 assert(I != M.IdentifierRemap.end()
8922 && "Invalid index into identifier index remap");
8923
8924 return LocalID + I->second;
8925}
8926
8928 if (ID == 0)
8929 return nullptr;
8930
8931 if (MacrosLoaded.empty()) {
8932 Error("no macro table in AST file");
8933 return nullptr;
8934 }
8935
8937 if (!MacrosLoaded[ID]) {
8939 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8940 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8941 ModuleFile *M = I->second;
8942 unsigned Index = ID - M->BaseMacroID;
8943 MacrosLoaded[ID] =
8944 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
8945
8946 if (DeserializationListener)
8947 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8948 MacrosLoaded[ID]);
8949 }
8950
8951 return MacrosLoaded[ID];
8952}
8953
8955 if (LocalID < NUM_PREDEF_MACRO_IDS)
8956 return LocalID;
8957
8958 if (!M.ModuleOffsetMap.empty())
8959 ReadModuleOffsetMap(M);
8960
8962 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8963 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8964
8965 return LocalID + I->second;
8966}
8967
8970 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8971 return LocalID;
8972
8973 if (!M.ModuleOffsetMap.empty())
8974 ReadModuleOffsetMap(M);
8975
8978 assert(I != M.SubmoduleRemap.end()
8979 && "Invalid index into submodule index remap");
8980
8981 return LocalID + I->second;
8982}
8983
8985 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8986 assert(GlobalID == 0 && "Unhandled global submodule ID");
8987 return nullptr;
8988 }
8989
8990 if (GlobalID > SubmodulesLoaded.size()) {
8991 Error("submodule ID out of range in AST file");
8992 return nullptr;
8993 }
8994
8995 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8996}
8997
8999 return getSubmodule(ID);
9000}
9001
9003 if (ID & 1) {
9004 // It's a module, look it up by submodule ID.
9005 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
9006 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9007 } else {
9008 // It's a prefix (preamble, PCH, ...). Look it up by index.
9009 unsigned IndexFromEnd = ID >> 1;
9010 assert(IndexFromEnd && "got reference to unknown module file");
9011 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9012 }
9013}
9014
9016 if (!M)
9017 return 1;
9018
9019 // For a file representing a module, use the submodule ID of the top-level
9020 // module as the file ID. For any other kind of file, the number of such
9021 // files loaded beforehand will be the same on reload.
9022 // FIXME: Is this true even if we have an explicit module file and a PCH?
9023 if (M->isModule())
9024 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9025
9026 auto PCHModules = getModuleManager().pch_modules();
9027 auto I = llvm::find(PCHModules, M);
9028 assert(I != PCHModules.end() && "emitting reference to unknown file");
9029 return (I - PCHModules.end()) << 1;
9030}
9031
9032std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9033 if (Module *M = getSubmodule(ID))
9034 return ASTSourceDescriptor(*M);
9035
9036 // If there is only a single PCH, return it instead.
9037 // Chained PCH are not supported.
9038 const auto &PCHChain = ModuleMgr.pch_modules();
9039 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9040 ModuleFile &MF = ModuleMgr.getPrimaryModule();
9041 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9042 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9043 return ASTSourceDescriptor(ModuleName,
9044 llvm::sys::path::parent_path(MF.FileName),
9045 FileName, MF.Signature);
9046 }
9047 return std::nullopt;
9048}
9049
9051 auto I = DefinitionSource.find(FD);
9052 if (I == DefinitionSource.end())
9053 return EK_ReplyHazy;
9054 return I->second ? EK_Never : EK_Always;
9055}
9056
9058 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9059}
9060
9062 if (ID == 0)
9063 return Selector();
9064
9065 if (ID > SelectorsLoaded.size()) {
9066 Error("selector ID out of range in AST file");
9067 return Selector();
9068 }
9069
9070 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9071 // Load this selector from the selector table.
9072 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9073 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9074 ModuleFile &M = *I->second;
9075 ASTSelectorLookupTrait Trait(*this, M);
9076 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9077 SelectorsLoaded[ID - 1] =
9078 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9079 if (DeserializationListener)
9080 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9081 }
9082
9083 return SelectorsLoaded[ID - 1];
9084}
9085
9087 return DecodeSelector(ID);
9088}
9089
9091 // ID 0 (the null selector) is considered an external selector.
9092 return getTotalNumSelectors() + 1;
9093}
9094
9096ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9097 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9098 return LocalID;
9099
9100 if (!M.ModuleOffsetMap.empty())
9101 ReadModuleOffsetMap(M);
9102
9105 assert(I != M.SelectorRemap.end()
9106 && "Invalid index into selector index remap");
9107
9108 return LocalID + I->second;
9109}
9110
9113 switch (Name.getNameKind()) {
9118
9121
9125
9132 break;
9133 }
9134 return DeclarationNameLoc();
9135}
9136
9138 DeclarationNameInfo NameInfo;
9139 NameInfo.setName(readDeclarationName());
9140 NameInfo.setLoc(readSourceLocation());
9141 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
9142 return NameInfo;
9143}
9144
9146 return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool());
9147}
9148
9151 unsigned NumTPLists = readInt();
9152 Info.NumTemplParamLists = NumTPLists;
9153 if (NumTPLists) {
9154 Info.TemplParamLists =
9155 new (getContext()) TemplateParameterList *[NumTPLists];
9156 for (unsigned i = 0; i != NumTPLists; ++i)
9158 }
9159}
9160
9163 SourceLocation TemplateLoc = readSourceLocation();
9164 SourceLocation LAngleLoc = readSourceLocation();
9165 SourceLocation RAngleLoc = readSourceLocation();
9166
9167 unsigned NumParams = readInt();
9169 Params.reserve(NumParams);
9170 while (NumParams--)
9171 Params.push_back(readDeclAs<NamedDecl>());
9172
9173 bool HasRequiresClause = readBool();
9174 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
9175
9177 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
9178 return TemplateParams;
9179}
9180
9183 bool Canonicalize) {
9184 unsigned NumTemplateArgs = readInt();
9185 TemplArgs.reserve(NumTemplateArgs);
9186 while (NumTemplateArgs--)
9187 TemplArgs.push_back(readTemplateArgument(Canonicalize));
9188}
9189
9190/// Read a UnresolvedSet structure.
9192 unsigned NumDecls = readInt();
9193 Set.reserve(getContext(), NumDecls);
9194 while (NumDecls--) {
9195 GlobalDeclID ID = readDeclID();
9197 Set.addLazyDecl(getContext(), ID.get(), AS);
9198 }
9199}
9200
9203 bool isVirtual = readBool();
9204 bool isBaseOfClass = readBool();
9205 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
9206 bool inheritConstructors = readBool();
9208 SourceRange Range = readSourceRange();
9209 SourceLocation EllipsisLoc = readSourceLocation();
9210 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
9211 EllipsisLoc);
9212 Result.setInheritConstructors(inheritConstructors);
9213 return Result;
9214}
9215
9218 ASTContext &Context = getContext();
9219 unsigned NumInitializers = readInt();
9220 assert(NumInitializers && "wrote ctor initializers but have no inits");
9221 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
9222 for (unsigned i = 0; i != NumInitializers; ++i) {
9223 TypeSourceInfo *TInfo = nullptr;
9224 bool IsBaseVirtual = false;
9225 FieldDecl *Member = nullptr;
9226 IndirectFieldDecl *IndirectMember = nullptr;
9227
9229 switch (Type) {
9231 TInfo = readTypeSourceInfo();
9232 IsBaseVirtual = readBool();
9233 break;
9234
9236 TInfo = readTypeSourceInfo();
9237 break;
9238
9240 Member = readDeclAs<FieldDecl>();
9241 break;
9242
9244 IndirectMember = readDeclAs<IndirectFieldDecl>();
9245 break;
9246 }
9247
9248 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
9249 Expr *Init = readExpr();
9250 SourceLocation LParenLoc = readSourceLocation();
9251 SourceLocation RParenLoc = readSourceLocation();
9252
9253 CXXCtorInitializer *BOMInit;
9255 BOMInit = new (Context)
9256 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9257 RParenLoc, MemberOrEllipsisLoc);
9259 BOMInit = new (Context)
9260 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
9261 else if (Member)
9262 BOMInit = new (Context)
9263 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9264 Init, RParenLoc);
9265 else
9266 BOMInit = new (Context)
9267 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9268 LParenLoc, Init, RParenLoc);
9269
9270 if (/*IsWritten*/readBool()) {
9271 unsigned SourceOrder = readInt();
9272 BOMInit->setSourceOrder(SourceOrder);
9273 }
9274
9275 CtorInitializers[i] = BOMInit;
9276 }
9277
9278 return CtorInitializers;
9279}
9280
9283 ASTContext &Context = getContext();
9284 unsigned N = readInt();
9286 for (unsigned I = 0; I != N; ++I) {
9287 auto Kind = readNestedNameSpecifierKind();
9288 switch (Kind) {
9291 SourceRange Range = readSourceRange();
9292 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9293 break;
9294 }
9295
9297 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
9298 SourceRange Range = readSourceRange();
9299 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9300 break;
9301 }
9302
9304 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
9305 SourceRange Range = readSourceRange();
9306 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9307 break;
9308 }
9309
9312 bool Template = readBool();
9314 if (!T)
9315 return NestedNameSpecifierLoc();
9316 SourceLocation ColonColonLoc = readSourceLocation();
9317
9318 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
9319 Builder.Extend(Context,
9320 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9321 T->getTypeLoc(), ColonColonLoc);
9322 break;
9323 }
9324
9326 SourceLocation ColonColonLoc = readSourceLocation();
9327 Builder.MakeGlobal(Context, ColonColonLoc);
9328 break;
9329 }
9330
9332 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
9333 SourceRange Range = readSourceRange();
9334 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9335 break;
9336 }
9337 }
9338 }
9339
9340 return Builder.getWithLocInContext(Context);
9341}
9342
9344 unsigned &Idx, LocSeq *Seq) {
9347 return SourceRange(beg, end);
9348}
9349
9351 const StringRef Blob) {
9352 unsigned Count = Record[0];
9353 const char *Byte = Blob.data();
9354 llvm::BitVector Ret = llvm::BitVector(Count, false);
9355 for (unsigned I = 0; I < Count; ++Byte)
9356 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
9357 if (*Byte & (1 << Bit))
9358 Ret[I] = true;
9359 return Ret;
9360}
9361
9362/// Read a floating-point value
9363llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9364 return llvm::APFloat(Sem, readAPInt());
9365}
9366
9367// Read a string
9368std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
9369 unsigned Len = Record[Idx++];
9370 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9371 Idx += Len;
9372 return Result;
9373}
9374
9376 unsigned &Idx) {
9377 std::string Filename = ReadString(Record, Idx);
9379 return Filename;
9380}
9381
9382std::string ASTReader::ReadPath(StringRef BaseDirectory,
9383 const RecordData &Record, unsigned &Idx) {
9384 std::string Filename = ReadString(Record, Idx);
9385 if (!BaseDirectory.empty())
9386 ResolveImportedPath(Filename, BaseDirectory);
9387 return Filename;
9388}
9389
9391 unsigned &Idx) {
9392 unsigned Major = Record[Idx++];
9393 unsigned Minor = Record[Idx++];
9394 unsigned Subminor = Record[Idx++];
9395 if (Minor == 0)
9396 return VersionTuple(Major);
9397 if (Subminor == 0)
9398 return VersionTuple(Major, Minor - 1);
9399 return VersionTuple(Major, Minor - 1, Subminor - 1);
9400}
9401
9403 const RecordData &Record,
9404 unsigned &Idx) {
9405 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9407}
9408
9409DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9410 return Diag(CurrentImportLoc, DiagID);
9411}
9412
9414 return Diags.Report(Loc, DiagID);
9415}
9416
9417/// Retrieve the identifier table associated with the
9418/// preprocessor.
9420 return PP.getIdentifierTable();
9421}
9422
9423/// Record that the given ID maps to the given switch-case
9424/// statement.
9426 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9427 "Already have a SwitchCase with this ID");
9428 (*CurrSwitchCaseStmts)[ID] = SC;
9429}
9430
9431/// Retrieve the switch-case statement with the given ID.
9433 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9434 return (*CurrSwitchCaseStmts)[ID];
9435}
9436
9438 CurrSwitchCaseStmts->clear();
9439}
9440
9442 ASTContext &Context = getContext();
9443 std::vector<RawComment *> Comments;
9444 for (SmallVectorImpl<std::pair<BitstreamCursor,
9445 serialization::ModuleFile *>>::iterator
9446 I = CommentsCursors.begin(),
9447 E = CommentsCursors.end();
9448 I != E; ++I) {
9449 Comments.clear();
9450 BitstreamCursor &Cursor = I->first;
9451 serialization::ModuleFile &F = *I->second;
9452 SavedStreamPosition SavedPosition(Cursor);
9453
9455 while (true) {
9457 Cursor.advanceSkippingSubblocks(
9458 BitstreamCursor::AF_DontPopBlockAtEnd);
9459 if (!MaybeEntry) {
9460 Error(MaybeEntry.takeError());
9461 return;
9462 }
9463 llvm::BitstreamEntry Entry = MaybeEntry.get();
9464
9465 switch (Entry.Kind) {
9466 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9467 case llvm::BitstreamEntry::Error:
9468 Error("malformed block record in AST file");
9469 return;
9470 case llvm::BitstreamEntry::EndBlock:
9471 goto NextCursor;
9472 case llvm::BitstreamEntry::Record:
9473 // The interesting case.
9474 break;
9475 }
9476
9477 // Read a record.
9478 Record.clear();
9479 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9480 if (!MaybeComment) {
9481 Error(MaybeComment.takeError());
9482 return;
9483 }
9484 switch ((CommentRecordTypes)MaybeComment.get()) {
9485 case COMMENTS_RAW_COMMENT: {
9486 unsigned Idx = 0;
9487 SourceRange SR = ReadSourceRange(F, Record, Idx);
9490 bool IsTrailingComment = Record[Idx++];
9491 bool IsAlmostTrailingComment = Record[Idx++];
9492 Comments.push_back(new (Context) RawComment(
9493 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9494 break;
9495 }
9496 }
9497 }
9498 NextCursor:
9499 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9500 FileToOffsetToComment;
9501 for (RawComment *C : Comments) {
9502 SourceLocation CommentLoc = C->getBeginLoc();
9503 if (CommentLoc.isValid()) {
9504 std::pair<FileID, unsigned> Loc =
9505 SourceMgr.getDecomposedLoc(CommentLoc);
9506 if (Loc.first.isValid())
9507 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9508 }
9509 }
9510 }
9511}
9512
9514 serialization::ModuleFile &MF, bool IncludeSystem,
9515 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
9516 bool IsSystem)>
9517 Visitor) {
9518 unsigned NumUserInputs = MF.NumUserInputFiles;
9519 unsigned NumInputs = MF.InputFilesLoaded.size();
9520 assert(NumUserInputs <= NumInputs);
9521 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9522 for (unsigned I = 0; I < N; ++I) {
9523 bool IsSystem = I >= NumUserInputs;
9524 InputFileInfo IFI = getInputFileInfo(MF, I+1);
9525 Visitor(IFI, IsSystem);
9526 }
9527}
9528
9530 bool IncludeSystem, bool Complain,
9531 llvm::function_ref<void(const serialization::InputFile &IF,
9532 bool isSystem)> Visitor) {
9533 unsigned NumUserInputs = MF.NumUserInputFiles;
9534 unsigned NumInputs = MF.InputFilesLoaded.size();
9535 assert(NumUserInputs <= NumInputs);
9536 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9537 for (unsigned I = 0; I < N; ++I) {
9538 bool IsSystem = I >= NumUserInputs;
9539 InputFile IF = getInputFile(MF, I+1, Complain);
9540 Visitor(IF, IsSystem);
9541 }
9542}
9543
9546 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
9547 unsigned NumInputs = MF.InputFilesLoaded.size();
9548 for (unsigned I = 0; I < NumInputs; ++I) {
9549 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
9550 if (IFI.TopLevel && IFI.ModuleMap)
9551 if (auto FE = getInputFile(MF, I + 1).getFile())
9552 Visitor(*FE);
9553 }
9554}
9555
9556void ASTReader::finishPendingActions() {
9557 while (
9558 !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() ||
9559 !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() ||
9560 !PendingDeclChains.empty() || !PendingMacroIDs.empty() ||
9561 !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() ||
9562 !PendingObjCExtensionIvarRedeclarations.empty()) {
9563 // If any identifiers with corresponding top-level declarations have
9564 // been loaded, load those declarations now.
9565 using TopLevelDeclsMap =
9566 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9567 TopLevelDeclsMap TopLevelDecls;
9568
9569 while (!PendingIdentifierInfos.empty()) {
9570 IdentifierInfo *II = PendingIdentifierInfos.back().first;
9572 std::move(PendingIdentifierInfos.back().second);
9573 PendingIdentifierInfos.pop_back();
9574
9575 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9576 }
9577
9578 // Load each function type that we deferred loading because it was a
9579 // deduced type that might refer to a local type declared within itself.
9580 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
9581 auto *FD = PendingDeducedFunctionTypes[I].first;
9582 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
9583
9584 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
9585 // If we gave a function a deduced return type, remember that we need to
9586 // propagate that along the redeclaration chain.
9587 if (DT->isDeduced()) {
9588 PendingDeducedTypeUpdates.insert(
9589 {FD->getCanonicalDecl(), FD->getReturnType()});
9590 continue;
9591 }
9592
9593 // The function has undeduced DeduceType return type. We hope we can
9594 // find the deduced type by iterating the redecls in other modules
9595 // later.
9596 PendingUndeducedFunctionDecls.push_back(FD);
9597 continue;
9598 }
9599 }
9600 PendingDeducedFunctionTypes.clear();
9601
9602 // Load each variable type that we deferred loading because it was a
9603 // deduced type that might refer to a local type declared within itself.
9604 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
9605 auto *VD = PendingDeducedVarTypes[I].first;
9606 VD->setType(GetType(PendingDeducedVarTypes[I].second));
9607 }
9608 PendingDeducedVarTypes.clear();
9609
9610 // For each decl chain that we wanted to complete while deserializing, mark
9611 // it as "still needs to be completed".
9612 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9613 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9614 }
9615 PendingIncompleteDeclChains.clear();
9616
9617 // Load pending declaration chains.
9618 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9619 loadPendingDeclChain(PendingDeclChains[I].first,
9620 PendingDeclChains[I].second);
9621 PendingDeclChains.clear();
9622
9623 // Make the most recent of the top-level declarations visible.
9624 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9625 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9626 IdentifierInfo *II = TLD->first;
9627 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9628 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9629 }
9630 }
9631
9632 // Load any pending macro definitions.
9633 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9634 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9636 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9637 // Initialize the macro history from chained-PCHs ahead of module imports.
9638 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9639 ++IDIdx) {
9640 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9641 if (!Info.M->isModule())
9642 resolvePendingMacro(II, Info);
9643 }
9644 // Handle module imports.
9645 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9646 ++IDIdx) {
9647 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9648 if (Info.M->isModule())
9649 resolvePendingMacro(II, Info);
9650 }
9651 }
9652 PendingMacroIDs.clear();
9653
9654 // Wire up the DeclContexts for Decls that we delayed setting until
9655 // recursive loading is completed.
9656 while (!PendingDeclContextInfos.empty()) {
9657 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9658 PendingDeclContextInfos.pop_front();
9659 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9660 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9661 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9662 }
9663
9664 // Perform any pending declaration updates.
9665 while (!PendingUpdateRecords.empty()) {
9666 auto Update = PendingUpdateRecords.pop_back_val();
9667 ReadingKindTracker ReadingKind(Read_Decl, *this);
9668 loadDeclUpdateRecords(Update);
9669 }
9670
9671 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
9672 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
9673 auto DuplicateIvars =
9674 PendingObjCExtensionIvarRedeclarations.back().second;
9675 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9677 ExtensionsPair.first->getASTContext(),
9678 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
9679 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
9680 /*Complain =*/false,
9681 /*ErrorOnTagTypeMismatch =*/true);
9682 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
9683 // Merge redeclared ivars with their predecessors.
9684 for (auto IvarPair : DuplicateIvars) {
9685 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
9686 // Change semantic DeclContext but keep the lexical one.
9687 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
9688 Ivar->getLexicalDeclContext(),
9689 getContext());
9690 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
9691 }
9692 // Invalidate duplicate extension and the cached ivar list.
9693 ExtensionsPair.first->setInvalidDecl();
9694 ExtensionsPair.second->getClassInterface()
9695 ->getDefinition()
9696 ->setIvarList(nullptr);
9697 } else {
9698 for (auto IvarPair : DuplicateIvars) {
9699 Diag(IvarPair.first->getLocation(),
9700 diag::err_duplicate_ivar_declaration)
9701 << IvarPair.first->getIdentifier();
9702 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
9703 }
9704 }
9705 PendingObjCExtensionIvarRedeclarations.pop_back();
9706 }
9707 }
9708
9709 // At this point, all update records for loaded decls are in place, so any
9710 // fake class definitions should have become real.
9711 assert(PendingFakeDefinitionData.empty() &&
9712 "faked up a class definition but never saw the real one");
9713
9714 // If we deserialized any C++ or Objective-C class definitions, any
9715 // Objective-C protocol definitions, or any redeclarable templates, make sure
9716 // that all redeclarations point to the definitions. Note that this can only
9717 // happen now, after the redeclaration chains have been fully wired.
9718 for (Decl *D : PendingDefinitions) {
9719 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9720 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9721 // Make sure that the TagType points at the definition.
9722 const_cast<TagType*>(TagT)->decl = TD;
9723 }
9724
9725 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9726 for (auto *R = getMostRecentExistingDecl(RD); R;
9727 R = R->getPreviousDecl()) {
9728 assert((R == D) ==
9729 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9730 "declaration thinks it's the definition but it isn't");
9731 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9732 }
9733 }
9734
9735 continue;
9736 }
9737
9738 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9739 // Make sure that the ObjCInterfaceType points at the definition.
9740 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9741 ->Decl = ID;
9742
9743 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9744 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9745
9746 continue;
9747 }
9748
9749 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9750 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9751 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9752
9753 continue;
9754 }
9755
9756 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9757 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9758 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9759 }
9760 PendingDefinitions.clear();
9761
9762 // Load the bodies of any functions or methods we've encountered. We do
9763 // this now (delayed) so that we can be sure that the declaration chains
9764 // have been fully wired up (hasBody relies on this).
9765 // FIXME: We shouldn't require complete redeclaration chains here.
9766 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9767 PBEnd = PendingBodies.end();
9768 PB != PBEnd; ++PB) {
9769 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9770 // For a function defined inline within a class template, force the
9771 // canonical definition to be the one inside the canonical definition of
9772 // the template. This ensures that we instantiate from a correct view
9773 // of the template.
9774 //
9775 // Sadly we can't do this more generally: we can't be sure that all
9776 // copies of an arbitrary class definition will have the same members
9777 // defined (eg, some member functions may not be instantiated, and some
9778 // special members may or may not have been implicitly defined).
9779 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9780 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9781 continue;
9782
9783 // FIXME: Check for =delete/=default?
9784 const FunctionDecl *Defn = nullptr;
9785 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9786 FD->setLazyBody(PB->second);
9787 } else {
9788 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9789 mergeDefinitionVisibility(NonConstDefn, FD);
9790
9791 if (!FD->isLateTemplateParsed() &&
9792 !NonConstDefn->isLateTemplateParsed() &&
9793 // We only perform ODR checks for decls not in the explicit
9794 // global module fragment.
9795 !shouldSkipCheckingODR(FD) &&
9796 FD->getODRHash() != NonConstDefn->getODRHash()) {
9797 if (!isa<CXXMethodDecl>(FD)) {
9798 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9799 } else if (FD->getLexicalParent()->isFileContext() &&
9800 NonConstDefn->getLexicalParent()->isFileContext()) {
9801 // Only diagnose out-of-line method definitions. If they are
9802 // in class definitions, then an error will be generated when
9803 // processing the class bodies.
9804 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9805 }
9806 }
9807 }
9808 continue;
9809 }
9810
9811 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9812 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9813 MD->setLazyBody(PB->second);
9814 }
9815 PendingBodies.clear();
9816
9817 // Inform any classes that had members added that they now have more members.
9818 for (auto [RD, MD] : PendingAddedClassMembers) {
9819 RD->addedMember(MD);
9820 }
9821 PendingAddedClassMembers.clear();
9822
9823 // Do some cleanup.
9824 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9826 PendingMergedDefinitionsToDeduplicate.clear();
9827}
9828
9829void ASTReader::diagnoseOdrViolations() {
9830 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9831 PendingRecordOdrMergeFailures.empty() &&
9832 PendingFunctionOdrMergeFailures.empty() &&
9833 PendingEnumOdrMergeFailures.empty() &&
9834 PendingObjCInterfaceOdrMergeFailures.empty() &&
9835 PendingObjCProtocolOdrMergeFailures.empty())
9836 return;
9837
9838 // Trigger the import of the full definition of each class that had any
9839 // odr-merging problems, so we can produce better diagnostics for them.
9840 // These updates may in turn find and diagnose some ODR failures, so take
9841 // ownership of the set first.
9842 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9843 PendingOdrMergeFailures.clear();
9844 for (auto &Merge : OdrMergeFailures) {
9845 Merge.first->buildLookup();
9846 Merge.first->decls_begin();
9847 Merge.first->bases_begin();
9848 Merge.first->vbases_begin();
9849 for (auto &RecordPair : Merge.second) {
9850 auto *RD = RecordPair.first;
9851 RD->decls_begin();
9852 RD->bases_begin();
9853 RD->vbases_begin();
9854 }
9855 }
9856
9857 // Trigger the import of the full definition of each record in C/ObjC.
9858 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
9859 PendingRecordOdrMergeFailures.clear();
9860 for (auto &Merge : RecordOdrMergeFailures) {
9861 Merge.first->decls_begin();
9862 for (auto &D : Merge.second)
9863 D->decls_begin();
9864 }
9865
9866 // Trigger the import of the full interface definition.
9867 auto ObjCInterfaceOdrMergeFailures =
9868 std::move(PendingObjCInterfaceOdrMergeFailures);
9869 PendingObjCInterfaceOdrMergeFailures.clear();
9870 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9871 Merge.first->decls_begin();
9872 for (auto &InterfacePair : Merge.second)
9873 InterfacePair.first->decls_begin();
9874 }
9875
9876 // Trigger the import of functions.
9877 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9878 PendingFunctionOdrMergeFailures.clear();
9879 for (auto &Merge : FunctionOdrMergeFailures) {
9880 Merge.first->buildLookup();
9881 Merge.first->decls_begin();
9882 Merge.first->getBody();
9883 for (auto &FD : Merge.second) {
9884 FD->buildLookup();
9885 FD->decls_begin();
9886 FD->getBody();
9887 }
9888 }
9889
9890 // Trigger the import of enums.
9891 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9892 PendingEnumOdrMergeFailures.clear();
9893 for (auto &Merge : EnumOdrMergeFailures) {
9894 Merge.first->decls_begin();
9895 for (auto &Enum : Merge.second) {
9896 Enum->decls_begin();
9897 }
9898 }
9899
9900 // Trigger the import of the full protocol definition.
9901 auto ObjCProtocolOdrMergeFailures =
9902 std::move(PendingObjCProtocolOdrMergeFailures);
9903 PendingObjCProtocolOdrMergeFailures.clear();
9904 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9905 Merge.first->decls_begin();
9906 for (auto &ProtocolPair : Merge.second)
9907 ProtocolPair.first->decls_begin();
9908 }
9909
9910 // For each declaration from a merged context, check that the canonical
9911 // definition of that context also contains a declaration of the same
9912 // entity.
9913 //
9914 // Caution: this loop does things that might invalidate iterators into
9915 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9916 while (!PendingOdrMergeChecks.empty()) {
9917 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9918
9919 // FIXME: Skip over implicit declarations for now. This matters for things
9920 // like implicitly-declared special member functions. This isn't entirely
9921 // correct; we can end up with multiple unmerged declarations of the same
9922 // implicit entity.
9923 if (D->isImplicit())
9924 continue;
9925
9926 DeclContext *CanonDef = D->getDeclContext();
9927
9928 bool Found = false;
9929 const Decl *DCanon = D->getCanonicalDecl();
9930
9931 for (auto *RI : D->redecls()) {
9932 if (RI->getLexicalDeclContext() == CanonDef) {
9933 Found = true;
9934 break;
9935 }
9936 }
9937 if (Found)
9938 continue;
9939
9940 // Quick check failed, time to do the slow thing. Note, we can't just
9941 // look up the name of D in CanonDef here, because the member that is
9942 // in CanonDef might not be found by name lookup (it might have been
9943 // replaced by a more recent declaration in the lookup table), and we
9944 // can't necessarily find it in the redeclaration chain because it might
9945 // be merely mergeable, not redeclarable.
9947 for (auto *CanonMember : CanonDef->decls()) {
9948 if (CanonMember->getCanonicalDecl() == DCanon) {
9949 // This can happen if the declaration is merely mergeable and not
9950 // actually redeclarable (we looked for redeclarations earlier).
9951 //
9952 // FIXME: We should be able to detect this more efficiently, without
9953 // pulling in all of the members of CanonDef.
9954 Found = true;
9955 break;
9956 }
9957 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9958 if (ND->getDeclName() == D->getDeclName())
9959 Candidates.push_back(ND);
9960 }
9961
9962 if (!Found) {
9963 // The AST doesn't like TagDecls becoming invalid after they've been
9964 // completed. We only really need to mark FieldDecls as invalid here.
9965 if (!isa<TagDecl>(D))
9966 D->setInvalidDecl();
9967
9968 // Ensure we don't accidentally recursively enter deserialization while
9969 // we're producing our diagnostic.
9970 Deserializing RecursionGuard(this);
9971
9972 std::string CanonDefModule =
9974 cast<Decl>(CanonDef));
9975 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9977 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9978
9979 if (Candidates.empty())
9980 Diag(cast<Decl>(CanonDef)->getLocation(),
9981 diag::note_module_odr_violation_no_possible_decls) << D;
9982 else {
9983 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9984 Diag(Candidates[I]->getLocation(),
9985 diag::note_module_odr_violation_possible_decl)
9986 << Candidates[I];
9987 }
9988
9989 DiagnosedOdrMergeFailures.insert(CanonDef);
9990 }
9991 }
9992
9993 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
9994 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
9995 ObjCInterfaceOdrMergeFailures.empty() &&
9996 ObjCProtocolOdrMergeFailures.empty())
9997 return;
9998
9999 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
10000 getPreprocessor().getLangOpts());
10001
10002 // Issue any pending ODR-failure diagnostics.
10003 for (auto &Merge : OdrMergeFailures) {
10004 // If we've already pointed out a specific problem with this class, don't
10005 // bother issuing a general "something's different" diagnostic.
10006 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10007 continue;
10008
10009 bool Diagnosed = false;
10010 CXXRecordDecl *FirstRecord = Merge.first;
10011 for (auto &RecordPair : Merge.second) {
10012 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
10013 RecordPair.second)) {
10014 Diagnosed = true;
10015 break;
10016 }
10017 }
10018
10019 if (!Diagnosed) {
10020 // All definitions are updates to the same declaration. This happens if a
10021 // module instantiates the declaration of a class template specialization
10022 // and two or more other modules instantiate its definition.
10023 //
10024 // FIXME: Indicate which modules had instantiations of this definition.
10025 // FIXME: How can this even happen?
10026 Diag(Merge.first->getLocation(),
10027 diag::err_module_odr_violation_different_instantiations)
10028 << Merge.first;
10029 }
10030 }
10031
10032 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
10033 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
10034 for (auto &Merge : RecordOdrMergeFailures) {
10035 // If we've already pointed out a specific problem with this class, don't
10036 // bother issuing a general "something's different" diagnostic.
10037 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10038 continue;
10039
10040 RecordDecl *FirstRecord = Merge.first;
10041 bool Diagnosed = false;
10042 for (auto *SecondRecord : Merge.second) {
10043 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
10044 Diagnosed = true;
10045 break;
10046 }
10047 }
10048 (void)Diagnosed;
10049 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10050 }
10051
10052 // Issue ODR failures diagnostics for functions.
10053 for (auto &Merge : FunctionOdrMergeFailures) {
10054 FunctionDecl *FirstFunction = Merge.first;
10055 bool Diagnosed = false;
10056 for (auto &SecondFunction : Merge.second) {
10057 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
10058 Diagnosed = true;
10059 break;
10060 }
10061 }
10062 (void)Diagnosed;
10063 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10064 }
10065
10066 // Issue ODR failures diagnostics for enums.
10067 for (auto &Merge : EnumOdrMergeFailures) {
10068 // If we've already pointed out a specific problem with this enum, don't
10069 // bother issuing a general "something's different" diagnostic.
10070 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10071 continue;
10072
10073 EnumDecl *FirstEnum = Merge.first;
10074 bool Diagnosed = false;
10075 for (auto &SecondEnum : Merge.second) {
10076 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
10077 Diagnosed = true;
10078 break;
10079 }
10080 }
10081 (void)Diagnosed;
10082 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10083 }
10084
10085 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10086 // If we've already pointed out a specific problem with this interface,
10087 // don't bother issuing a general "something's different" diagnostic.
10088 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10089 continue;
10090
10091 bool Diagnosed = false;
10092 ObjCInterfaceDecl *FirstID = Merge.first;
10093 for (auto &InterfacePair : Merge.second) {
10094 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
10095 InterfacePair.second)) {
10096 Diagnosed = true;
10097 break;
10098 }
10099 }
10100 (void)Diagnosed;
10101 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10102 }
10103
10104 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10105 // If we've already pointed out a specific problem with this protocol,
10106 // don't bother issuing a general "something's different" diagnostic.
10107 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10108 continue;
10109
10110 ObjCProtocolDecl *FirstProtocol = Merge.first;
10111 bool Diagnosed = false;
10112 for (auto &ProtocolPair : Merge.second) {
10113 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
10114 ProtocolPair.second)) {
10115 Diagnosed = true;
10116 break;
10117 }
10118 }
10119 (void)Diagnosed;
10120 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10121 }
10122}
10123
10125 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
10126 ReadTimer->startTimer();
10127}
10128
10130 assert(NumCurrentElementsDeserializing &&
10131 "FinishedDeserializing not paired with StartedDeserializing");
10132 if (NumCurrentElementsDeserializing == 1) {
10133 // We decrease NumCurrentElementsDeserializing only after pending actions
10134 // are finished, to avoid recursively re-calling finishPendingActions().
10135 finishPendingActions();
10136 }
10137 --NumCurrentElementsDeserializing;
10138
10139 if (NumCurrentElementsDeserializing == 0) {
10140 // Propagate exception specification and deduced type updates along
10141 // redeclaration chains.
10142 //
10143 // We do this now rather than in finishPendingActions because we want to
10144 // be able to walk the complete redeclaration chains of the updated decls.
10145 while (!PendingExceptionSpecUpdates.empty() ||
10146 !PendingDeducedTypeUpdates.empty()) {
10147 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
10148 PendingExceptionSpecUpdates.clear();
10149 for (auto Update : ESUpdates) {
10150 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10151 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
10152 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
10153 if (auto *Listener = getContext().getASTMutationListener())
10154 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
10155 for (auto *Redecl : Update.second->redecls())
10156 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
10157 }
10158
10159 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
10160 PendingDeducedTypeUpdates.clear();
10161 for (auto Update : DTUpdates) {
10162 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10163 // FIXME: If the return type is already deduced, check that it matches.
10165 Update.second);
10166 }
10167
10168 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
10169 PendingUndeducedFunctionDecls.clear();
10170 // We hope we can find the deduced type for the functions by iterating
10171 // redeclarations in other modules.
10172 for (FunctionDecl *UndeducedFD : UDTUpdates)
10173 (void)UndeducedFD->getMostRecentDecl();
10174 }
10175
10176 if (ReadTimer)
10177 ReadTimer->stopTimer();
10178
10179 diagnoseOdrViolations();
10180
10181 // We are not in recursive loading, so it's safe to pass the "interesting"
10182 // decls to the consumer.
10183 if (Consumer)
10184 PassInterestingDeclsToConsumer();
10185 }
10186}
10187
10188void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
10189 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10190 // Remove any fake results before adding any real ones.
10191 auto It = PendingFakeLookupResults.find(II);
10192 if (It != PendingFakeLookupResults.end()) {
10193 for (auto *ND : It->second)
10194 SemaObj->IdResolver.RemoveDecl(ND);
10195 // FIXME: this works around module+PCH performance issue.
10196 // Rather than erase the result from the map, which is O(n), just clear
10197 // the vector of NamedDecls.
10198 It->second.clear();
10199 }
10200 }
10201
10202 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10203 SemaObj->TUScope->AddDecl(D);
10204 } else if (SemaObj->TUScope) {
10205 // Adding the decl to IdResolver may have failed because it was already in
10206 // (even though it was not added in scope). If it is already in, make sure
10207 // it gets in the scope as well.
10208 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
10209 SemaObj->TUScope->AddDecl(D);
10210 }
10211}
10212
10214 ASTContext *Context,
10215 const PCHContainerReader &PCHContainerRdr,
10216 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10217 StringRef isysroot,
10218 DisableValidationForModuleKind DisableValidationKind,
10219 bool AllowASTWithCompilerErrors,
10220 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10221 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
10222 std::unique_ptr<llvm::Timer> ReadTimer)
10223 : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
10225 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
10226 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
10227 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
10228 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
10229 PCHContainerRdr, PP.getHeaderSearchInfo()),
10230 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
10231 DisableValidationKind(DisableValidationKind),
10232 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10233 AllowConfigurationMismatch(AllowConfigurationMismatch),
10234 ValidateSystemInputs(ValidateSystemInputs),
10235 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
10236 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
10237 SourceMgr.setExternalSLocEntrySource(this);
10238
10239 for (const auto &Ext : Extensions) {
10240 auto BlockName = Ext->getExtensionMetadata().BlockName;
10241 auto Known = ModuleFileExtensions.find(BlockName);
10242 if (Known != ModuleFileExtensions.end()) {
10243 Diags.Report(diag::warn_duplicate_module_file_extension)
10244 << BlockName;
10245 continue;
10246 }
10247
10248 ModuleFileExtensions.insert({BlockName, Ext});
10249 }
10250}
10251
10253 if (OwnsDeserializationListener)
10254 delete DeserializationListener;
10255}
10256
10258 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10259}
10260
10262 unsigned AbbrevID) {
10263 Idx = 0;
10264 Record.clear();
10265 return Cursor.readRecord(AbbrevID, Record);
10266}
10267//===----------------------------------------------------------------------===//
10268//// OMPClauseReader implementation
10269////===----------------------------------------------------------------------===//
10270
10271// This has to be in namespace clang because it's friended by all
10272// of the OMP clauses.
10273namespace clang {
10274
10275class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
10277 ASTContext &Context;
10278
10279public:
10281 : Record(Record), Context(Record.getContext()) {}
10282#define GEN_CLANG_CLAUSE_CLASS
10283#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
10284#include "llvm/Frontend/OpenMP/OMP.inc"
10288};
10289
10290} // end namespace clang
10291
10293 return OMPClauseReader(*this).readClause();
10294}
10295
10297 OMPClause *C = nullptr;
10298 switch (llvm::omp::Clause(Record.readInt())) {
10299 case llvm::omp::OMPC_if:
10300 C = new (Context) OMPIfClause();
10301 break;
10302 case llvm::omp::OMPC_final:
10303 C = new (Context) OMPFinalClause();
10304 break;
10305 case llvm::omp::OMPC_num_threads:
10306 C = new (Context) OMPNumThreadsClause();
10307 break;
10308 case llvm::omp::OMPC_safelen:
10309 C = new (Context) OMPSafelenClause();
10310 break;
10311 case llvm::omp::OMPC_simdlen:
10312 C = new (Context) OMPSimdlenClause();
10313 break;
10314 case llvm::omp::OMPC_sizes: {
10315 unsigned NumSizes = Record.readInt();
10316 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
10317 break;
10318 }
10319 case llvm::omp::OMPC_full:
10320 C = OMPFullClause::CreateEmpty(Context);
10321 break;
10322 case llvm::omp::OMPC_partial:
10324 break;
10325 case llvm::omp::OMPC_allocator:
10326 C = new (Context) OMPAllocatorClause();
10327 break;
10328 case llvm::omp::OMPC_collapse:
10329 C = new (Context) OMPCollapseClause();
10330 break;
10331 case llvm::omp::OMPC_default:
10332 C = new (Context) OMPDefaultClause();
10333 break;
10334 case llvm::omp::OMPC_proc_bind:
10335 C = new (Context) OMPProcBindClause();
10336 break;
10337 case llvm::omp::OMPC_schedule:
10338 C = new (Context) OMPScheduleClause();
10339 break;
10340 case llvm::omp::OMPC_ordered:
10341 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
10342 break;
10343 case llvm::omp::OMPC_nowait:
10344 C = new (Context) OMPNowaitClause();
10345 break;
10346 case llvm::omp::OMPC_untied:
10347 C = new (Context) OMPUntiedClause();
10348 break;
10349 case llvm::omp::OMPC_mergeable:
10350 C = new (Context) OMPMergeableClause();
10351 break;
10352 case llvm::omp::OMPC_read:
10353 C = new (Context) OMPReadClause();
10354 break;
10355 case llvm::omp::OMPC_write:
10356 C = new (Context) OMPWriteClause();
10357 break;
10358 case llvm::omp::OMPC_update:
10359 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
10360 break;
10361 case llvm::omp::OMPC_capture:
10362 C = new (Context) OMPCaptureClause();
10363 break;
10364 case llvm::omp::OMPC_compare:
10365 C = new (Context) OMPCompareClause();
10366 break;
10367 case llvm::omp::OMPC_fail:
10368 C = new (Context) OMPFailClause();
10369 break;
10370 case llvm::omp::OMPC_seq_cst:
10371 C = new (Context) OMPSeqCstClause();
10372 break;
10373 case llvm::omp::OMPC_acq_rel:
10374 C = new (Context) OMPAcqRelClause();
10375 break;
10376 case llvm::omp::OMPC_acquire:
10377 C = new (Context) OMPAcquireClause();
10378 break;
10379 case llvm::omp::OMPC_release:
10380 C = new (Context) OMPReleaseClause();
10381 break;
10382 case llvm::omp::OMPC_relaxed:
10383 C = new (Context) OMPRelaxedClause();
10384 break;
10385 case llvm::omp::OMPC_weak:
10386 C = new (Context) OMPWeakClause();
10387 break;
10388 case llvm::omp::OMPC_threads:
10389 C = new (Context) OMPThreadsClause();
10390 break;
10391 case llvm::omp::OMPC_simd:
10392 C = new (Context) OMPSIMDClause();
10393 break;
10394 case llvm::omp::OMPC_nogroup:
10395 C = new (Context) OMPNogroupClause();
10396 break;
10397 case llvm::omp::OMPC_unified_address:
10398 C = new (Context) OMPUnifiedAddressClause();
10399 break;
10400 case llvm::omp::OMPC_unified_shared_memory:
10401 C = new (Context) OMPUnifiedSharedMemoryClause();
10402 break;
10403 case llvm::omp::OMPC_reverse_offload:
10404 C = new (Context) OMPReverseOffloadClause();
10405 break;
10406 case llvm::omp::OMPC_dynamic_allocators:
10407 C = new (Context) OMPDynamicAllocatorsClause();
10408 break;
10409 case llvm::omp::OMPC_atomic_default_mem_order:
10410 C = new (Context) OMPAtomicDefaultMemOrderClause();
10411 break;
10412 case llvm::omp::OMPC_at:
10413 C = new (Context) OMPAtClause();
10414 break;
10415 case llvm::omp::OMPC_severity:
10416 C = new (Context) OMPSeverityClause();
10417 break;
10418 case llvm::omp::OMPC_message:
10419 C = new (Context) OMPMessageClause();
10420 break;
10421 case llvm::omp::OMPC_private:
10422 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
10423 break;
10424 case llvm::omp::OMPC_firstprivate:
10425 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
10426 break;
10427 case llvm::omp::OMPC_lastprivate:
10428 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
10429 break;
10430 case llvm::omp::OMPC_shared:
10431 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
10432 break;
10433 case llvm::omp::OMPC_reduction: {
10434 unsigned N = Record.readInt();
10435 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
10436 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
10437 break;
10438 }
10439 case llvm::omp::OMPC_task_reduction:
10440 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
10441 break;
10442 case llvm::omp::OMPC_in_reduction:
10443 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
10444 break;
10445 case llvm::omp::OMPC_linear:
10446 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
10447 break;
10448 case llvm::omp::OMPC_aligned:
10449 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
10450 break;
10451 case llvm::omp::OMPC_copyin:
10452 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
10453 break;
10454 case llvm::omp::OMPC_copyprivate:
10455 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
10456 break;
10457 case llvm::omp::OMPC_flush:
10458 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
10459 break;
10460 case llvm::omp::OMPC_depobj:
10462 break;
10463 case llvm::omp::OMPC_depend: {
10464 unsigned NumVars = Record.readInt();
10465 unsigned NumLoops = Record.readInt();
10466 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
10467 break;
10468 }
10469 case llvm::omp::OMPC_device:
10470 C = new (Context) OMPDeviceClause();
10471 break;
10472 case llvm::omp::OMPC_map: {
10474 Sizes.NumVars = Record.readInt();
10475 Sizes.NumUniqueDeclarations = Record.readInt();
10476 Sizes.NumComponentLists = Record.readInt();
10477 Sizes.NumComponents = Record.readInt();
10478 C = OMPMapClause::CreateEmpty(Context, Sizes);
10479 break;
10480 }
10481 case llvm::omp::OMPC_num_teams:
10482 C = new (Context) OMPNumTeamsClause();
10483 break;
10484 case llvm::omp::OMPC_thread_limit:
10485 C = new (Context) OMPThreadLimitClause();
10486 break;
10487 case llvm::omp::OMPC_priority:
10488 C = new (Context) OMPPriorityClause();
10489 break;
10490 case llvm::omp::OMPC_grainsize:
10491 C = new (Context) OMPGrainsizeClause();
10492 break;
10493 case llvm::omp::OMPC_num_tasks:
10494 C = new (Context) OMPNumTasksClause();
10495 break;
10496 case llvm::omp::OMPC_hint:
10497 C = new (Context) OMPHintClause();
10498 break;
10499 case llvm::omp::OMPC_dist_schedule:
10500 C = new (Context) OMPDistScheduleClause();
10501 break;
10502 case llvm::omp::OMPC_defaultmap:
10503 C = new (Context) OMPDefaultmapClause();
10504 break;
10505 case llvm::omp::OMPC_to: {
10507 Sizes.NumVars = Record.readInt();
10508 Sizes.NumUniqueDeclarations = Record.readInt();
10509 Sizes.NumComponentLists = Record.readInt();
10510 Sizes.NumComponents = Record.readInt();
10511 C = OMPToClause::CreateEmpty(Context, Sizes);
10512 break;
10513 }
10514 case llvm::omp::OMPC_from: {
10516 Sizes.NumVars = Record.readInt();
10517 Sizes.NumUniqueDeclarations = Record.readInt();
10518 Sizes.NumComponentLists = Record.readInt();
10519 Sizes.NumComponents = Record.readInt();
10520 C = OMPFromClause::CreateEmpty(Context, Sizes);
10521 break;
10522 }
10523 case llvm::omp::OMPC_use_device_ptr: {
10525 Sizes.NumVars = Record.readInt();
10526 Sizes.NumUniqueDeclarations = Record.readInt();
10527 Sizes.NumComponentLists = Record.readInt();
10528 Sizes.NumComponents = Record.readInt();
10529 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
10530 break;
10531 }
10532 case llvm::omp::OMPC_use_device_addr: {
10534 Sizes.NumVars = Record.readInt();
10535 Sizes.NumUniqueDeclarations = Record.readInt();
10536 Sizes.NumComponentLists = Record.readInt();
10537 Sizes.NumComponents = Record.readInt();
10538 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
10539 break;
10540 }
10541 case llvm::omp::OMPC_is_device_ptr: {
10543 Sizes.NumVars = Record.readInt();
10544 Sizes.NumUniqueDeclarations = Record.readInt();
10545 Sizes.NumComponentLists = Record.readInt();
10546 Sizes.NumComponents = Record.readInt();
10547 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
10548 break;
10549 }
10550 case llvm::omp::OMPC_has_device_addr: {
10552 Sizes.NumVars = Record.readInt();
10553 Sizes.NumUniqueDeclarations = Record.readInt();
10554 Sizes.NumComponentLists = Record.readInt();
10555 Sizes.NumComponents = Record.readInt();
10556 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
10557 break;
10558 }
10559 case llvm::omp::OMPC_allocate:
10560 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
10561 break;
10562 case llvm::omp::OMPC_nontemporal:
10563 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
10564 break;
10565 case llvm::omp::OMPC_inclusive:
10566 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
10567 break;
10568 case llvm::omp::OMPC_exclusive:
10569 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
10570 break;
10571 case llvm::omp::OMPC_order:
10572 C = new (Context) OMPOrderClause();
10573 break;
10574 case llvm::omp::OMPC_init:
10575 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
10576 break;
10577 case llvm::omp::OMPC_use:
10578 C = new (Context) OMPUseClause();
10579 break;
10580 case llvm::omp::OMPC_destroy:
10581 C = new (Context) OMPDestroyClause();
10582 break;
10583 case llvm::omp::OMPC_novariants:
10584 C = new (Context) OMPNovariantsClause();
10585 break;
10586 case llvm::omp::OMPC_nocontext:
10587 C = new (Context) OMPNocontextClause();
10588 break;
10589 case llvm::omp::OMPC_detach:
10590 C = new (Context) OMPDetachClause();
10591 break;
10592 case llvm::omp::OMPC_uses_allocators:
10593 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
10594 break;
10595 case llvm::omp::OMPC_affinity:
10596 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
10597 break;
10598 case llvm::omp::OMPC_filter:
10599 C = new (Context) OMPFilterClause();
10600 break;
10601 case llvm::omp::OMPC_bind:
10602 C = OMPBindClause::CreateEmpty(Context);
10603 break;
10604 case llvm::omp::OMPC_align:
10605 C = new (Context) OMPAlignClause();
10606 break;
10607 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
10608 C = new (Context) OMPXDynCGroupMemClause();
10609 break;
10610 case llvm::omp::OMPC_doacross: {
10611 unsigned NumVars = Record.readInt();
10612 unsigned NumLoops = Record.readInt();
10613 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
10614 break;
10615 }
10616 case llvm::omp::OMPC_ompx_attribute:
10617 C = new (Context) OMPXAttributeClause();
10618 break;
10619 case llvm::omp::OMPC_ompx_bare:
10620 C = new (Context) OMPXBareClause();
10621 break;
10622#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
10623 case llvm::omp::Enum: \
10624 break;
10625#include "llvm/Frontend/OpenMP/OMPKinds.def"
10626 default:
10627 break;
10628 }
10629 assert(C && "Unknown OMPClause type");
10630
10631 Visit(C);
10632 C->setLocStart(Record.readSourceLocation());
10633 C->setLocEnd(Record.readSourceLocation());
10634
10635 return C;
10636}
10637
10639 C->setPreInitStmt(Record.readSubStmt(),
10640 static_cast<OpenMPDirectiveKind>(Record.readInt()));
10641}
10642
10645 C->setPostUpdateExpr(Record.readSubExpr());
10646}
10647
10648void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
10650 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
10651 C->setNameModifierLoc(Record.readSourceLocation());
10652 C->setColonLoc(Record.readSourceLocation());
10653 C->setCondition(Record.readSubExpr());
10654 C->setLParenLoc(Record.readSourceLocation());
10655}
10656
10657void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
10659 C->setCondition(Record.readSubExpr());
10660 C->setLParenLoc(Record.readSourceLocation());
10661}
10662
10663void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
10665 C->setNumThreads(Record.readSubExpr());
10666 C->setLParenLoc(Record.readSourceLocation());
10667}
10668
10669void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
10670 C->setSafelen(Record.readSubExpr());
10671 C->setLParenLoc(Record.readSourceLocation());
10672}
10673
10674void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
10675 C->setSimdlen(Record.readSubExpr());
10676 C->setLParenLoc(Record.readSourceLocation());
10677}
10678
10679void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
10680 for (Expr *&E : C->getSizesRefs())
10681 E = Record.readSubExpr();
10682 C->setLParenLoc(Record.readSourceLocation());
10683}
10684
10685void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
10686
10687void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
10688 C->setFactor(Record.readSubExpr());
10689 C->setLParenLoc(Record.readSourceLocation());
10690}
10691
10692void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
10693 C->setAllocator(Record.readExpr());
10694 C->setLParenLoc(Record.readSourceLocation());
10695}
10696
10697void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
10698 C->setNumForLoops(Record.readSubExpr());
10699 C->setLParenLoc(Record.readSourceLocation());
10700}
10701
10702void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
10703 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
10704 C->setLParenLoc(Record.readSourceLocation());
10705 C->setDefaultKindKwLoc(Record.readSourceLocation());
10706}
10707
10708void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
10709 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
10710 C->setLParenLoc(Record.readSourceLocation());
10711 C->setProcBindKindKwLoc(Record.readSourceLocation());
10712}
10713
10714void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
10716 C->setScheduleKind(
10717 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
10718 C->setFirstScheduleModifier(
10719 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10720 C->setSecondScheduleModifier(
10721 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10722 C->setChunkSize(Record.readSubExpr());
10723 C->setLParenLoc(Record.readSourceLocation());
10724 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
10725 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
10726 C->setScheduleKindLoc(Record.readSourceLocation());
10727 C->setCommaLoc(Record.readSourceLocation());
10728}
10729
10730void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
10731 C->setNumForLoops(Record.readSubExpr());
10732 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10733 C->setLoopNumIterations(I, Record.readSubExpr());
10734 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10735 C->setLoopCounter(I, Record.readSubExpr());
10736 C->setLParenLoc(Record.readSourceLocation());
10737}
10738
10739void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
10740 C->setEventHandler(Record.readSubExpr());
10741 C->setLParenLoc(Record.readSourceLocation());
10742}
10743
10744void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
10745
10746void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
10747
10748void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
10749
10750void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
10751
10752void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
10753
10754void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
10755 if (C->isExtended()) {
10756 C->setLParenLoc(Record.readSourceLocation());
10757 C->setArgumentLoc(Record.readSourceLocation());
10758 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
10759 }
10760}
10761
10762void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
10763
10764void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
10765
10766// Read the parameter of fail clause. This will have been saved when
10767// OMPClauseWriter is called.
10768void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
10769 C->setLParenLoc(Record.readSourceLocation());
10770 SourceLocation FailParameterLoc = Record.readSourceLocation();
10771 C->setFailParameterLoc(FailParameterLoc);
10772 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
10773 C->setFailParameter(CKind);
10774}
10775
10776void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
10777
10778void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
10779
10780void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
10781
10782void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
10783
10784void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
10785
10786void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
10787
10788void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
10789
10790void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
10791
10792void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
10793
10794void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
10795 unsigned NumVars = C->varlist_size();
10797 Vars.reserve(NumVars);
10798 for (unsigned I = 0; I != NumVars; ++I)
10799 Vars.push_back(Record.readSubExpr());
10800 C->setVarRefs(Vars);
10801 C->setIsTarget(Record.readBool());
10802 C->setIsTargetSync(Record.readBool());
10803 C->setLParenLoc(Record.readSourceLocation());
10804 C->setVarLoc(Record.readSourceLocation());
10805}
10806
10807void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
10808 C->setInteropVar(Record.readSubExpr());
10809 C->setLParenLoc(Record.readSourceLocation());
10810 C->setVarLoc(Record.readSourceLocation());
10811}
10812
10813void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
10814 C->setInteropVar(Record.readSubExpr());
10815 C->setLParenLoc(Record.readSourceLocation());
10816 C->setVarLoc(Record.readSourceLocation());
10817}
10818
10819void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
10821 C->setCondition(Record.readSubExpr());
10822 C->setLParenLoc(Record.readSourceLocation());
10823}
10824
10825void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
10827 C->setCondition(Record.readSubExpr());
10828 C->setLParenLoc(Record.readSourceLocation());
10829}
10830
10831void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
10832
10833void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
10835
10836void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
10837
10838void
10839OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
10840}
10841
10842void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
10844 C->setAtomicDefaultMemOrderKind(
10845 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
10846 C->setLParenLoc(Record.readSourceLocation());
10847 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
10848}
10849
10850void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
10851 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
10852 C->setLParenLoc(Record.readSourceLocation());
10853 C->setAtKindKwLoc(Record.readSourceLocation());
10854}
10855
10856void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
10857 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
10858 C->setLParenLoc(Record.readSourceLocation());
10859 C->setSeverityKindKwLoc(Record.readSourceLocation());
10860}
10861
10862void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
10863 C->setMessageString(Record.readSubExpr());
10864 C->setLParenLoc(Record.readSourceLocation());
10865}
10866
10867void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
10868 C->setLParenLoc(Record.readSourceLocation());
10869 unsigned NumVars = C->varlist_size();
10871 Vars.reserve(NumVars);
10872 for (unsigned i = 0; i != NumVars; ++i)
10873 Vars.push_back(Record.readSubExpr());
10874 C->setVarRefs(Vars);
10875 Vars.clear();
10876 for (unsigned i = 0; i != NumVars; ++i)
10877 Vars.push_back(Record.readSubExpr());
10878 C->setPrivateCopies(Vars);
10879}
10880
10881void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
10883 C->setLParenLoc(Record.readSourceLocation());
10884 unsigned NumVars = C->varlist_size();
10886 Vars.reserve(NumVars);
10887 for (unsigned i = 0; i != NumVars; ++i)
10888 Vars.push_back(Record.readSubExpr());
10889 C->setVarRefs(Vars);
10890 Vars.clear();
10891 for (unsigned i = 0; i != NumVars; ++i)
10892 Vars.push_back(Record.readSubExpr());
10893 C->setPrivateCopies(Vars);
10894 Vars.clear();
10895 for (unsigned i = 0; i != NumVars; ++i)
10896 Vars.push_back(Record.readSubExpr());
10897 C->setInits(Vars);
10898}
10899
10900void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
10902 C->setLParenLoc(Record.readSourceLocation());
10903 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
10904 C->setKindLoc(Record.readSourceLocation());
10905 C->setColonLoc(Record.readSourceLocation());
10906 unsigned NumVars = C->varlist_size();
10908 Vars.reserve(NumVars);
10909 for (unsigned i = 0; i != NumVars; ++i)
10910 Vars.push_back(Record.readSubExpr());
10911 C->setVarRefs(Vars);
10912 Vars.clear();
10913 for (unsigned i = 0; i != NumVars; ++i)
10914 Vars.push_back(Record.readSubExpr());
10915 C->setPrivateCopies(Vars);
10916 Vars.clear();
10917 for (unsigned i = 0; i != NumVars; ++i)
10918 Vars.push_back(Record.readSubExpr());
10919 C->setSourceExprs(Vars);
10920 Vars.clear();
10921 for (unsigned i = 0; i != NumVars; ++i)
10922 Vars.push_back(Record.readSubExpr());
10923 C->setDestinationExprs(Vars);
10924 Vars.clear();
10925 for (unsigned i = 0; i != NumVars; ++i)
10926 Vars.push_back(Record.readSubExpr());
10927 C->setAssignmentOps(Vars);
10928}
10929
10930void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
10931 C->setLParenLoc(Record.readSourceLocation());
10932 unsigned NumVars = C->varlist_size();
10934 Vars.reserve(NumVars);
10935 for (unsigned i = 0; i != NumVars; ++i)
10936 Vars.push_back(Record.readSubExpr());
10937 C->setVarRefs(Vars);
10938}
10939
10940void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
10942 C->setLParenLoc(Record.readSourceLocation());
10943 C->setModifierLoc(Record.readSourceLocation());
10944 C->setColonLoc(Record.readSourceLocation());
10945 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10946 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10947 C->setQualifierLoc(NNSL);
10948 C->setNameInfo(DNI);
10949
10950 unsigned NumVars = C->varlist_size();
10952 Vars.reserve(NumVars);
10953 for (unsigned i = 0; i != NumVars; ++i)
10954 Vars.push_back(Record.readSubExpr());
10955 C->setVarRefs(Vars);
10956 Vars.clear();
10957 for (unsigned i = 0; i != NumVars; ++i)
10958 Vars.push_back(Record.readSubExpr());
10959 C->setPrivates(Vars);
10960 Vars.clear();
10961 for (unsigned i = 0; i != NumVars; ++i)
10962 Vars.push_back(Record.readSubExpr());
10963 C->setLHSExprs(Vars);
10964 Vars.clear();
10965 for (unsigned i = 0; i != NumVars; ++i)
10966 Vars.push_back(Record.readSubExpr());
10967 C->setRHSExprs(Vars);
10968 Vars.clear();
10969 for (unsigned i = 0; i != NumVars; ++i)
10970 Vars.push_back(Record.readSubExpr());
10971 C->setReductionOps(Vars);
10972 if (C->getModifier() == OMPC_REDUCTION_inscan) {
10973 Vars.clear();
10974 for (unsigned i = 0; i != NumVars; ++i)
10975 Vars.push_back(Record.readSubExpr());
10976 C->setInscanCopyOps(Vars);
10977 Vars.clear();
10978 for (unsigned i = 0; i != NumVars; ++i)
10979 Vars.push_back(Record.readSubExpr());
10980 C->setInscanCopyArrayTemps(Vars);
10981 Vars.clear();
10982 for (unsigned i = 0; i != NumVars; ++i)
10983 Vars.push_back(Record.readSubExpr());
10984 C->setInscanCopyArrayElems(Vars);
10985 }
10986}
10987
10988void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
10990 C->setLParenLoc(Record.readSourceLocation());
10991 C->setColonLoc(Record.readSourceLocation());
10992 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10993 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10994 C->setQualifierLoc(NNSL);
10995 C->setNameInfo(DNI);
10996
10997 unsigned NumVars = C->varlist_size();
10999 Vars.reserve(NumVars);
11000 for (unsigned I = 0; I != NumVars; ++I)
11001 Vars.push_back(Record.readSubExpr());
11002 C->setVarRefs(Vars);
11003 Vars.clear();
11004 for (unsigned I = 0; I != NumVars; ++I)
11005 Vars.push_back(Record.readSubExpr());
11006 C->setPrivates(Vars);
11007 Vars.clear();
11008 for (unsigned I = 0; I != NumVars; ++I)
11009 Vars.push_back(Record.readSubExpr());
11010 C->setLHSExprs(Vars);
11011 Vars.clear();
11012 for (unsigned I = 0; I != NumVars; ++I)
11013 Vars.push_back(Record.readSubExpr());
11014 C->setRHSExprs(Vars);
11015 Vars.clear();
11016 for (unsigned I = 0; I != NumVars; ++I)
11017 Vars.push_back(Record.readSubExpr());
11018 C->setReductionOps(Vars);
11019}
11020
11021void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
11023 C->setLParenLoc(Record.readSourceLocation());
11024 C->setColonLoc(Record.readSourceLocation());
11025 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11026 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11027 C->setQualifierLoc(NNSL);
11028 C->setNameInfo(DNI);
11029
11030 unsigned NumVars = C->varlist_size();
11032 Vars.reserve(NumVars);
11033 for (unsigned I = 0; I != NumVars; ++I)
11034 Vars.push_back(Record.readSubExpr());
11035 C->setVarRefs(Vars);
11036 Vars.clear();
11037 for (unsigned I = 0; I != NumVars; ++I)
11038 Vars.push_back(Record.readSubExpr());
11039 C->setPrivates(Vars);
11040 Vars.clear();
11041 for (unsigned I = 0; I != NumVars; ++I)
11042 Vars.push_back(Record.readSubExpr());
11043 C->setLHSExprs(Vars);
11044 Vars.clear();
11045 for (unsigned I = 0; I != NumVars; ++I)
11046 Vars.push_back(Record.readSubExpr());
11047 C->setRHSExprs(Vars);
11048 Vars.clear();
11049 for (unsigned I = 0; I != NumVars; ++I)
11050 Vars.push_back(Record.readSubExpr());
11051 C->setReductionOps(Vars);
11052 Vars.clear();
11053 for (unsigned I = 0; I != NumVars; ++I)
11054 Vars.push_back(Record.readSubExpr());
11055 C->setTaskgroupDescriptors(Vars);
11056}
11057
11058void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
11060 C->setLParenLoc(Record.readSourceLocation());
11061 C->setColonLoc(Record.readSourceLocation());
11062 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
11063 C->setModifierLoc(Record.readSourceLocation());
11064 unsigned NumVars = C->varlist_size();
11066 Vars.reserve(NumVars);
11067 for (unsigned i = 0; i != NumVars; ++i)
11068 Vars.push_back(Record.readSubExpr());
11069 C->setVarRefs(Vars);
11070 Vars.clear();
11071 for (unsigned i = 0; i != NumVars; ++i)
11072 Vars.push_back(Record.readSubExpr());
11073 C->setPrivates(Vars);
11074 Vars.clear();
11075 for (unsigned i = 0; i != NumVars; ++i)
11076 Vars.push_back(Record.readSubExpr());
11077 C->setInits(Vars);
11078 Vars.clear();
11079 for (unsigned i = 0; i != NumVars; ++i)
11080 Vars.push_back(Record.readSubExpr());
11081 C->setUpdates(Vars);
11082 Vars.clear();
11083 for (unsigned i = 0; i != NumVars; ++i)
11084 Vars.push_back(Record.readSubExpr());
11085 C->setFinals(Vars);
11086 C->setStep(Record.readSubExpr());
11087 C->setCalcStep(Record.readSubExpr());
11088 Vars.clear();
11089 for (unsigned I = 0; I != NumVars + 1; ++I)
11090 Vars.push_back(Record.readSubExpr());
11091 C->setUsedExprs(Vars);
11092}
11093
11094void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
11095 C->setLParenLoc(Record.readSourceLocation());
11096 C->setColonLoc(Record.readSourceLocation());
11097 unsigned NumVars = C->varlist_size();
11099 Vars.reserve(NumVars);
11100 for (unsigned i = 0; i != NumVars; ++i)
11101 Vars.push_back(Record.readSubExpr());
11102 C->setVarRefs(Vars);
11103 C->setAlignment(Record.readSubExpr());
11104}
11105
11106void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
11107 C->setLParenLoc(Record.readSourceLocation());
11108 unsigned NumVars = C->varlist_size();
11110 Exprs.reserve(NumVars);
11111 for (unsigned i = 0; i != NumVars; ++i)
11112 Exprs.push_back(Record.readSubExpr());
11113 C->setVarRefs(Exprs);
11114 Exprs.clear();
11115 for (unsigned i = 0; i != NumVars; ++i)
11116 Exprs.push_back(Record.readSubExpr());
11117 C->setSourceExprs(Exprs);
11118 Exprs.clear();
11119 for (unsigned i = 0; i != NumVars; ++i)
11120 Exprs.push_back(Record.readSubExpr());
11121 C->setDestinationExprs(Exprs);
11122 Exprs.clear();
11123 for (unsigned i = 0; i != NumVars; ++i)
11124 Exprs.push_back(Record.readSubExpr());
11125 C->setAssignmentOps(Exprs);
11126}
11127
11128void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
11129 C->setLParenLoc(Record.readSourceLocation());
11130 unsigned NumVars = C->varlist_size();
11132 Exprs.reserve(NumVars);
11133 for (unsigned i = 0; i != NumVars; ++i)
11134 Exprs.push_back(Record.readSubExpr());
11135 C->setVarRefs(Exprs);
11136 Exprs.clear();
11137 for (unsigned i = 0; i != NumVars; ++i)
11138 Exprs.push_back(Record.readSubExpr());
11139 C->setSourceExprs(Exprs);
11140 Exprs.clear();
11141 for (unsigned i = 0; i != NumVars; ++i)
11142 Exprs.push_back(Record.readSubExpr());
11143 C->setDestinationExprs(Exprs);
11144 Exprs.clear();
11145 for (unsigned i = 0; i != NumVars; ++i)
11146 Exprs.push_back(Record.readSubExpr());
11147 C->setAssignmentOps(Exprs);
11148}
11149
11150void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
11151 C->setLParenLoc(Record.readSourceLocation());
11152 unsigned NumVars = C->varlist_size();
11154 Vars.reserve(NumVars);
11155 for (unsigned i = 0; i != NumVars; ++i)
11156 Vars.push_back(Record.readSubExpr());
11157 C->setVarRefs(Vars);
11158}
11159
11160void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
11161 C->setDepobj(Record.readSubExpr());
11162 C->setLParenLoc(Record.readSourceLocation());
11163}
11164
11165void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
11166 C->setLParenLoc(Record.readSourceLocation());
11167 C->setModifier(Record.readSubExpr());
11168 C->setDependencyKind(
11169 static_cast<OpenMPDependClauseKind>(Record.readInt()));
11170 C->setDependencyLoc(Record.readSourceLocation());
11171 C->setColonLoc(Record.readSourceLocation());
11172 C->setOmpAllMemoryLoc(Record.readSourceLocation());
11173 unsigned NumVars = C->varlist_size();
11175 Vars.reserve(NumVars);
11176 for (unsigned I = 0; I != NumVars; ++I)
11177 Vars.push_back(Record.readSubExpr());
11178 C->setVarRefs(Vars);
11179 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11180 C->setLoopData(I, Record.readSubExpr());
11181}
11182
11183void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
11185 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
11186 C->setDevice(Record.readSubExpr());
11187 C->setModifierLoc(Record.readSourceLocation());
11188 C->setLParenLoc(Record.readSourceLocation());
11189}
11190
11191void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
11192 C->setLParenLoc(Record.readSourceLocation());
11193 bool HasIteratorModifier = false;
11194 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
11195 C->setMapTypeModifier(
11196 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
11197 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
11198 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
11199 HasIteratorModifier = true;
11200 }
11201 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11202 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11203 C->setMapType(
11204 static_cast<OpenMPMapClauseKind>(Record.readInt()));
11205 C->setMapLoc(Record.readSourceLocation());
11206 C->setColonLoc(Record.readSourceLocation());
11207 auto NumVars = C->varlist_size();
11208 auto UniqueDecls = C->getUniqueDeclarationsNum();
11209 auto TotalLists = C->getTotalComponentListNum();
11210 auto TotalComponents = C->getTotalComponentsNum();
11211
11213 Vars.reserve(NumVars);
11214 for (unsigned i = 0; i != NumVars; ++i)
11215 Vars.push_back(Record.readExpr());
11216 C->setVarRefs(Vars);
11217
11218 SmallVector<Expr *, 16> UDMappers;
11219 UDMappers.reserve(NumVars);
11220 for (unsigned I = 0; I < NumVars; ++I)
11221 UDMappers.push_back(Record.readExpr());
11222 C->setUDMapperRefs(UDMappers);
11223
11224 if (HasIteratorModifier)
11225 C->setIteratorModifier(Record.readExpr());
11226
11228 Decls.reserve(UniqueDecls);
11229 for (unsigned i = 0; i < UniqueDecls; ++i)
11230 Decls.push_back(Record.readDeclAs<ValueDecl>());
11231 C->setUniqueDecls(Decls);
11232
11233 SmallVector<unsigned, 16> ListsPerDecl;
11234 ListsPerDecl.reserve(UniqueDecls);
11235 for (unsigned i = 0; i < UniqueDecls; ++i)
11236 ListsPerDecl.push_back(Record.readInt());
11237 C->setDeclNumLists(ListsPerDecl);
11238
11239 SmallVector<unsigned, 32> ListSizes;
11240 ListSizes.reserve(TotalLists);
11241 for (unsigned i = 0; i < TotalLists; ++i)
11242 ListSizes.push_back(Record.readInt());
11243 C->setComponentListSizes(ListSizes);
11244
11246 Components.reserve(TotalComponents);
11247 for (unsigned i = 0; i < TotalComponents; ++i) {
11248 Expr *AssociatedExprPr = Record.readExpr();
11249 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11250 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11251 /*IsNonContiguous=*/false);
11252 }
11253 C->setComponents(Components, ListSizes);
11254}
11255
11256void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
11257 C->setLParenLoc(Record.readSourceLocation());
11258 C->setColonLoc(Record.readSourceLocation());
11259 C->setAllocator(Record.readSubExpr());
11260 unsigned NumVars = C->varlist_size();
11262 Vars.reserve(NumVars);
11263 for (unsigned i = 0; i != NumVars; ++i)
11264 Vars.push_back(Record.readSubExpr());
11265 C->setVarRefs(Vars);
11266}
11267
11268void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
11270 C->setNumTeams(Record.readSubExpr());
11271 C->setLParenLoc(Record.readSourceLocation());
11272}
11273
11274void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
11276 C->setThreadLimit(Record.readSubExpr());
11277 C->setLParenLoc(Record.readSourceLocation());
11278}
11279
11280void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
11282 C->setPriority(Record.readSubExpr());
11283 C->setLParenLoc(Record.readSourceLocation());
11284}
11285
11286void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
11288 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
11289 C->setGrainsize(Record.readSubExpr());
11290 C->setModifierLoc(Record.readSourceLocation());
11291 C->setLParenLoc(Record.readSourceLocation());
11292}
11293
11294void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
11296 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
11297 C->setNumTasks(Record.readSubExpr());
11298 C->setModifierLoc(Record.readSourceLocation());
11299 C->setLParenLoc(Record.readSourceLocation());
11300}
11301
11302void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
11303 C->setHint(Record.readSubExpr());
11304 C->setLParenLoc(Record.readSourceLocation());
11305}
11306
11307void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
11309 C->setDistScheduleKind(
11310 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
11311 C->setChunkSize(Record.readSubExpr());
11312 C->setLParenLoc(Record.readSourceLocation());
11313 C->setDistScheduleKindLoc(Record.readSourceLocation());
11314 C->setCommaLoc(Record.readSourceLocation());
11315}
11316
11317void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
11318 C->setDefaultmapKind(
11319 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
11320 C->setDefaultmapModifier(
11321 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
11322 C->setLParenLoc(Record.readSourceLocation());
11323 C->setDefaultmapModifierLoc(Record.readSourceLocation());
11324 C->setDefaultmapKindLoc(Record.readSourceLocation());
11325}
11326
11327void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
11328 C->setLParenLoc(Record.readSourceLocation());
11329 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11330 C->setMotionModifier(
11331 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11332 C->setMotionModifierLoc(I, Record.readSourceLocation());
11333 }
11334 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11335 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11336 C->setColonLoc(Record.readSourceLocation());
11337 auto NumVars = C->varlist_size();
11338 auto UniqueDecls = C->getUniqueDeclarationsNum();
11339 auto TotalLists = C->getTotalComponentListNum();
11340 auto TotalComponents = C->getTotalComponentsNum();
11341
11343 Vars.reserve(NumVars);
11344 for (unsigned i = 0; i != NumVars; ++i)
11345 Vars.push_back(Record.readSubExpr());
11346 C->setVarRefs(Vars);
11347
11348 SmallVector<Expr *, 16> UDMappers;
11349 UDMappers.reserve(NumVars);
11350 for (unsigned I = 0; I < NumVars; ++I)
11351 UDMappers.push_back(Record.readSubExpr());
11352 C->setUDMapperRefs(UDMappers);
11353
11355 Decls.reserve(UniqueDecls);
11356 for (unsigned i = 0; i < UniqueDecls; ++i)
11357 Decls.push_back(Record.readDeclAs<ValueDecl>());
11358 C->setUniqueDecls(Decls);
11359
11360 SmallVector<unsigned, 16> ListsPerDecl;
11361 ListsPerDecl.reserve(UniqueDecls);
11362 for (unsigned i = 0; i < UniqueDecls; ++i)
11363 ListsPerDecl.push_back(Record.readInt());
11364 C->setDeclNumLists(ListsPerDecl);
11365
11366 SmallVector<unsigned, 32> ListSizes;
11367 ListSizes.reserve(TotalLists);
11368 for (unsigned i = 0; i < TotalLists; ++i)
11369 ListSizes.push_back(Record.readInt());
11370 C->setComponentListSizes(ListSizes);
11371
11373 Components.reserve(TotalComponents);
11374 for (unsigned i = 0; i < TotalComponents; ++i) {
11375 Expr *AssociatedExprPr = Record.readSubExpr();
11376 bool IsNonContiguous = Record.readBool();
11377 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11378 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11379 }
11380 C->setComponents(Components, ListSizes);
11381}
11382
11383void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
11384 C->setLParenLoc(Record.readSourceLocation());
11385 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11386 C->setMotionModifier(
11387 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11388 C->setMotionModifierLoc(I, Record.readSourceLocation());
11389 }
11390 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11391 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11392 C->setColonLoc(Record.readSourceLocation());
11393 auto NumVars = C->varlist_size();
11394 auto UniqueDecls = C->getUniqueDeclarationsNum();
11395 auto TotalLists = C->getTotalComponentListNum();
11396 auto TotalComponents = C->getTotalComponentsNum();
11397
11399 Vars.reserve(NumVars);
11400 for (unsigned i = 0; i != NumVars; ++i)
11401 Vars.push_back(Record.readSubExpr());
11402 C->setVarRefs(Vars);
11403
11404 SmallVector<Expr *, 16> UDMappers;
11405 UDMappers.reserve(NumVars);
11406 for (unsigned I = 0; I < NumVars; ++I)
11407 UDMappers.push_back(Record.readSubExpr());
11408 C->setUDMapperRefs(UDMappers);
11409
11411 Decls.reserve(UniqueDecls);
11412 for (unsigned i = 0; i < UniqueDecls; ++i)
11413 Decls.push_back(Record.readDeclAs<ValueDecl>());
11414 C->setUniqueDecls(Decls);
11415
11416 SmallVector<unsigned, 16> ListsPerDecl;
11417 ListsPerDecl.reserve(UniqueDecls);
11418 for (unsigned i = 0; i < UniqueDecls; ++i)
11419 ListsPerDecl.push_back(Record.readInt());
11420 C->setDeclNumLists(ListsPerDecl);
11421
11422 SmallVector<unsigned, 32> ListSizes;
11423 ListSizes.reserve(TotalLists);
11424 for (unsigned i = 0; i < TotalLists; ++i)
11425 ListSizes.push_back(Record.readInt());
11426 C->setComponentListSizes(ListSizes);
11427
11429 Components.reserve(TotalComponents);
11430 for (unsigned i = 0; i < TotalComponents; ++i) {
11431 Expr *AssociatedExprPr = Record.readSubExpr();
11432 bool IsNonContiguous = Record.readBool();
11433 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11434 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11435 }
11436 C->setComponents(Components, ListSizes);
11437}
11438
11439void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
11440 C->setLParenLoc(Record.readSourceLocation());
11441 auto NumVars = C->varlist_size();
11442 auto UniqueDecls = C->getUniqueDeclarationsNum();
11443 auto TotalLists = C->getTotalComponentListNum();
11444 auto TotalComponents = C->getTotalComponentsNum();
11445
11447 Vars.reserve(NumVars);
11448 for (unsigned i = 0; i != NumVars; ++i)
11449 Vars.push_back(Record.readSubExpr());
11450 C->setVarRefs(Vars);
11451 Vars.clear();
11452 for (unsigned i = 0; i != NumVars; ++i)
11453 Vars.push_back(Record.readSubExpr());
11454 C->setPrivateCopies(Vars);
11455 Vars.clear();
11456 for (unsigned i = 0; i != NumVars; ++i)
11457 Vars.push_back(Record.readSubExpr());
11458 C->setInits(Vars);
11459
11461 Decls.reserve(UniqueDecls);
11462 for (unsigned i = 0; i < UniqueDecls; ++i)
11463 Decls.push_back(Record.readDeclAs<ValueDecl>());
11464 C->setUniqueDecls(Decls);
11465
11466 SmallVector<unsigned, 16> ListsPerDecl;
11467 ListsPerDecl.reserve(UniqueDecls);
11468 for (unsigned i = 0; i < UniqueDecls; ++i)
11469 ListsPerDecl.push_back(Record.readInt());
11470 C->setDeclNumLists(ListsPerDecl);
11471
11472 SmallVector<unsigned, 32> ListSizes;
11473 ListSizes.reserve(TotalLists);
11474 for (unsigned i = 0; i < TotalLists; ++i)
11475 ListSizes.push_back(Record.readInt());
11476 C->setComponentListSizes(ListSizes);
11477
11479 Components.reserve(TotalComponents);
11480 for (unsigned i = 0; i < TotalComponents; ++i) {
11481 auto *AssociatedExprPr = Record.readSubExpr();
11482 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11483 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11484 /*IsNonContiguous=*/false);
11485 }
11486 C->setComponents(Components, ListSizes);
11487}
11488
11489void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
11490 C->setLParenLoc(Record.readSourceLocation());
11491 auto NumVars = C->varlist_size();
11492 auto UniqueDecls = C->getUniqueDeclarationsNum();
11493 auto TotalLists = C->getTotalComponentListNum();
11494 auto TotalComponents = C->getTotalComponentsNum();
11495
11497 Vars.reserve(NumVars);
11498 for (unsigned i = 0; i != NumVars; ++i)
11499 Vars.push_back(Record.readSubExpr());
11500 C->setVarRefs(Vars);
11501
11503 Decls.reserve(UniqueDecls);
11504 for (unsigned i = 0; i < UniqueDecls; ++i)
11505 Decls.push_back(Record.readDeclAs<ValueDecl>());
11506 C->setUniqueDecls(Decls);
11507
11508 SmallVector<unsigned, 16> ListsPerDecl;
11509 ListsPerDecl.reserve(UniqueDecls);
11510 for (unsigned i = 0; i < UniqueDecls; ++i)
11511 ListsPerDecl.push_back(Record.readInt());
11512 C->setDeclNumLists(ListsPerDecl);
11513
11514 SmallVector<unsigned, 32> ListSizes;
11515 ListSizes.reserve(TotalLists);
11516 for (unsigned i = 0; i < TotalLists; ++i)
11517 ListSizes.push_back(Record.readInt());
11518 C->setComponentListSizes(ListSizes);
11519
11521 Components.reserve(TotalComponents);
11522 for (unsigned i = 0; i < TotalComponents; ++i) {
11523 Expr *AssociatedExpr = Record.readSubExpr();
11524 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11525 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11526 /*IsNonContiguous*/ false);
11527 }
11528 C->setComponents(Components, ListSizes);
11529}
11530
11531void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
11532 C->setLParenLoc(Record.readSourceLocation());
11533 auto NumVars = C->varlist_size();
11534 auto UniqueDecls = C->getUniqueDeclarationsNum();
11535 auto TotalLists = C->getTotalComponentListNum();
11536 auto TotalComponents = C->getTotalComponentsNum();
11537
11539 Vars.reserve(NumVars);
11540 for (unsigned i = 0; i != NumVars; ++i)
11541 Vars.push_back(Record.readSubExpr());
11542 C->setVarRefs(Vars);
11543 Vars.clear();
11544
11546 Decls.reserve(UniqueDecls);
11547 for (unsigned i = 0; i < UniqueDecls; ++i)
11548 Decls.push_back(Record.readDeclAs<ValueDecl>());
11549 C->setUniqueDecls(Decls);
11550
11551 SmallVector<unsigned, 16> ListsPerDecl;
11552 ListsPerDecl.reserve(UniqueDecls);
11553 for (unsigned i = 0; i < UniqueDecls; ++i)
11554 ListsPerDecl.push_back(Record.readInt());
11555 C->setDeclNumLists(ListsPerDecl);
11556
11557 SmallVector<unsigned, 32> ListSizes;
11558 ListSizes.reserve(TotalLists);
11559 for (unsigned i = 0; i < TotalLists; ++i)
11560 ListSizes.push_back(Record.readInt());
11561 C->setComponentListSizes(ListSizes);
11562
11564 Components.reserve(TotalComponents);
11565 for (unsigned i = 0; i < TotalComponents; ++i) {
11566 Expr *AssociatedExpr = Record.readSubExpr();
11567 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11568 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11569 /*IsNonContiguous=*/false);
11570 }
11571 C->setComponents(Components, ListSizes);
11572}
11573
11574void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
11575 C->setLParenLoc(Record.readSourceLocation());
11576 auto NumVars = C->varlist_size();
11577 auto UniqueDecls = C->getUniqueDeclarationsNum();
11578 auto TotalLists = C->getTotalComponentListNum();
11579 auto TotalComponents = C->getTotalComponentsNum();
11580
11582 Vars.reserve(NumVars);
11583 for (unsigned I = 0; I != NumVars; ++I)
11584 Vars.push_back(Record.readSubExpr());
11585 C->setVarRefs(Vars);
11586 Vars.clear();
11587
11589 Decls.reserve(UniqueDecls);
11590 for (unsigned I = 0; I < UniqueDecls; ++I)
11591 Decls.push_back(Record.readDeclAs<ValueDecl>());
11592 C->setUniqueDecls(Decls);
11593
11594 SmallVector<unsigned, 16> ListsPerDecl;
11595 ListsPerDecl.reserve(UniqueDecls);
11596 for (unsigned I = 0; I < UniqueDecls; ++I)
11597 ListsPerDecl.push_back(Record.readInt());
11598 C->setDeclNumLists(ListsPerDecl);
11599
11600 SmallVector<unsigned, 32> ListSizes;
11601 ListSizes.reserve(TotalLists);
11602 for (unsigned i = 0; i < TotalLists; ++i)
11603 ListSizes.push_back(Record.readInt());
11604 C->setComponentListSizes(ListSizes);
11605
11607 Components.reserve(TotalComponents);
11608 for (unsigned I = 0; I < TotalComponents; ++I) {
11609 Expr *AssociatedExpr = Record.readSubExpr();
11610 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11611 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11612 /*IsNonContiguous=*/false);
11613 }
11614 C->setComponents(Components, ListSizes);
11615}
11616
11617void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
11618 C->setLParenLoc(Record.readSourceLocation());
11619 unsigned NumVars = C->varlist_size();
11621 Vars.reserve(NumVars);
11622 for (unsigned i = 0; i != NumVars; ++i)
11623 Vars.push_back(Record.readSubExpr());
11624 C->setVarRefs(Vars);
11625 Vars.clear();
11626 Vars.reserve(NumVars);
11627 for (unsigned i = 0; i != NumVars; ++i)
11628 Vars.push_back(Record.readSubExpr());
11629 C->setPrivateRefs(Vars);
11630}
11631
11632void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
11633 C->setLParenLoc(Record.readSourceLocation());
11634 unsigned NumVars = C->varlist_size();
11636 Vars.reserve(NumVars);
11637 for (unsigned i = 0; i != NumVars; ++i)
11638 Vars.push_back(Record.readSubExpr());
11639 C->setVarRefs(Vars);
11640}
11641
11642void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
11643 C->setLParenLoc(Record.readSourceLocation());
11644 unsigned NumVars = C->varlist_size();
11646 Vars.reserve(NumVars);
11647 for (unsigned i = 0; i != NumVars; ++i)
11648 Vars.push_back(Record.readSubExpr());
11649 C->setVarRefs(Vars);
11650}
11651
11652void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
11653 C->setLParenLoc(Record.readSourceLocation());
11654 unsigned NumOfAllocators = C->getNumberOfAllocators();
11656 Data.reserve(NumOfAllocators);
11657 for (unsigned I = 0; I != NumOfAllocators; ++I) {
11658 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
11659 D.Allocator = Record.readSubExpr();
11660 D.AllocatorTraits = Record.readSubExpr();
11661 D.LParenLoc = Record.readSourceLocation();
11662 D.RParenLoc = Record.readSourceLocation();
11663 }
11664 C->setAllocatorsData(Data);
11665}
11666
11667void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
11668 C->setLParenLoc(Record.readSourceLocation());
11669 C->setModifier(Record.readSubExpr());
11670 C->setColonLoc(Record.readSourceLocation());
11671 unsigned NumOfLocators = C->varlist_size();
11672 SmallVector<Expr *, 4> Locators;
11673 Locators.reserve(NumOfLocators);
11674 for (unsigned I = 0; I != NumOfLocators; ++I)
11675 Locators.push_back(Record.readSubExpr());
11676 C->setVarRefs(Locators);
11677}
11678
11679void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
11680 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
11681 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
11682 C->setLParenLoc(Record.readSourceLocation());
11683 C->setKindKwLoc(Record.readSourceLocation());
11684 C->setModifierKwLoc(Record.readSourceLocation());
11685}
11686
11687void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
11689 C->setThreadID(Record.readSubExpr());
11690 C->setLParenLoc(Record.readSourceLocation());
11691}
11692
11693void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
11694 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
11695 C->setLParenLoc(Record.readSourceLocation());
11696 C->setBindKindLoc(Record.readSourceLocation());
11697}
11698
11699void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
11700 C->setAlignment(Record.readExpr());
11701 C->setLParenLoc(Record.readSourceLocation());
11702}
11703
11704void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
11706 C->setSize(Record.readSubExpr());
11707 C->setLParenLoc(Record.readSourceLocation());
11708}
11709
11710void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
11711 C->setLParenLoc(Record.readSourceLocation());
11712 C->setDependenceType(
11713 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
11714 C->setDependenceLoc(Record.readSourceLocation());
11715 C->setColonLoc(Record.readSourceLocation());
11716 unsigned NumVars = C->varlist_size();
11718 Vars.reserve(NumVars);
11719 for (unsigned I = 0; I != NumVars; ++I)
11720 Vars.push_back(Record.readSubExpr());
11721 C->setVarRefs(Vars);
11722 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11723 C->setLoopData(I, Record.readSubExpr());
11724}
11725
11726void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
11727 AttrVec Attrs;
11728 Record.readAttributes(Attrs);
11729 C->setAttrs(Attrs);
11730 C->setLocStart(Record.readSourceLocation());
11731 C->setLParenLoc(Record.readSourceLocation());
11732 C->setLocEnd(Record.readSourceLocation());
11733}
11734
11735void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
11736
11739 TI.Sets.resize(readUInt32());
11740 for (auto &Set : TI.Sets) {
11741 Set.Kind = readEnum<llvm::omp::TraitSet>();
11742 Set.Selectors.resize(readUInt32());
11743 for (auto &Selector : Set.Selectors) {
11744 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
11745 Selector.ScoreOrCondition = nullptr;
11746 if (readBool())
11747 Selector.ScoreOrCondition = readExprRef();
11748 Selector.Properties.resize(readUInt32());
11749 for (auto &Property : Selector.Properties)
11750 Property.Kind = readEnum<llvm::omp::TraitProperty>();
11751 }
11752 }
11753 return &TI;
11754}
11755
11757 if (!Data)
11758 return;
11759 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
11760 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
11761 skipInts(3);
11762 }
11763 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
11764 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
11765 Clauses[I] = readOMPClause();
11766 Data->setClauses(Clauses);
11767 if (Data->hasAssociatedStmt())
11768 Data->setAssociatedStmt(readStmt());
11769 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
11770 Data->getChildren()[I] = readStmt();
11771}
11772
11774 OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>();
11777
11778 switch (ClauseKind) {
11780 SourceLocation LParenLoc = readSourceLocation();
11781 OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>();
11782 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
11783 EndLoc);
11784 }
11785 case OpenACCClauseKind::If: {
11786 SourceLocation LParenLoc = readSourceLocation();
11787 Expr *CondExpr = readSubExpr();
11788 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
11789 EndLoc);
11790 }
11792 SourceLocation LParenLoc = readSourceLocation();
11793 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
11794 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
11795 CondExpr, EndLoc);
11796 }
11798 SourceLocation LParenLoc = readSourceLocation();
11799 unsigned NumClauses = readInt();
11801 for (unsigned I = 0; I < NumClauses; ++I)
11802 IntExprs.push_back(readSubExpr());
11803 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
11804 IntExprs, EndLoc);
11805 }
11807 SourceLocation LParenLoc = readSourceLocation();
11808 Expr *IntExpr = readSubExpr();
11809 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
11810 IntExpr, EndLoc);
11811 }
11813 SourceLocation LParenLoc = readSourceLocation();
11814 Expr *IntExpr = readSubExpr();
11815 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
11816 IntExpr, EndLoc);
11817 }
11855 llvm_unreachable("Clause serialization not yet implemented");
11856 }
11857 llvm_unreachable("Invalid Clause Kind");
11858}
11859
11862 for (unsigned I = 0; I < Clauses.size(); ++I)
11863 Clauses[I] = readOpenACCClause();
11864}
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:8041
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:7709
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:8563
static bool readBit(unsigned &Bits)
Definition: ASTReader.cpp:1001
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
Definition: ASTReader.cpp:6689
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:8158
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:5247
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:2376
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:2972
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:1202
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:1974
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
CanQualType Char16Ty
Definition: ASTContext.h:1098
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1952
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1108
CanQualType DependentTy
Definition: ASTContext.h:1119
CanQualType NullPtrTy
Definition: ASTContext.h:1118
CanQualType OMPIteratorTy
Definition: ASTContext.h:1130
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 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:1986
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:2155
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:2136
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:1419
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:1962
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
CanQualType OMPArraySectionTy
Definition: ASTContext.h:1130
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:8384
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
Definition: ASTReader.cpp:8412
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Definition: ASTReader.cpp:8417
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:6483
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
Definition: ASTReader.cpp:6264
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:9544
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:9050
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
Definition: ASTReader.cpp:9419
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1785
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:9425
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
Definition: ASTReader.cpp:9409
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition: ASTReader.h:2379
static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx)
Definition: ASTReader.cpp:9368
void ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector< Decl *, 4 > &Decls) override
Read the set of decls to be checked for deferred diags.
Definition: ASTReader.cpp:8704
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
Definition: ASTReader.cpp:8214
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition: ASTReader.h:1627
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1640
@ 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:1631
@ 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:1635
serialization::DeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, serialization::GlobalDeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
Definition: ASTReader.cpp:7814
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &Exprs) override
Definition: ASTReader.cpp:8634
Decl * GetDecl(serialization::GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7793
serialization::GlobalDeclID getGlobalDeclID(ModuleFile &F, serialization::LocalDeclID LocalID) const
Map from a local declaration ID within a given module to a global declaration ID.
Definition: ASTReader.cpp:7655
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:7939
SourceRange ReadSkippedRange(unsigned Index) override
Read a preallocated skipped range from the external source.
Definition: ASTReader.cpp:6250
void dump()
Dump information about the AST reader to standard error.
Definition: ASTReader.cpp:8178
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:8912
void AssignedLambdaNumbering(const CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
Definition: ASTReader.cpp:8805
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:2413
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
Definition: ASTReader.cpp:9057
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:7863
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
Definition: ASTReader.cpp:9032
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
Definition: ASTReader.cpp:8032
void ClearSwitchCaseIDs()
Definition: ASTReader.cpp:9437
void SetIdentifierInfo(unsigned ID, IdentifierInfo *II)
Definition: ASTReader.cpp:8821
bool loadGlobalIndex()
Attempts to load the global index.
Definition: ASTReader.cpp:4352
void ReadComments() override
Loads comments ranges.
Definition: ASTReader.cpp:9441
SourceManager & getSourceManager() const
Definition: ASTReader.h:1612
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
bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
Definition: ASTReader.cpp:7671
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:5241
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition: ASTReader.h:2391
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
Definition: ASTReader.cpp:7581
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:9513
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:8058
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:7981
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Definition: ASTReader.cpp:8650
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:7524
SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile, SourceLocation Loc) const
Translate a source location from another module file's source location space into ours.
Definition: ASTReader.h:2263
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
Decl * GetLocalDecl(ModuleFile &F, serialization::LocalDeclID LocalID)
Reads a declaration with the given local ID in the given module.
Definition: ASTReader.h:1942
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:6470
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
Definition: ASTReader.cpp:8345
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:9529
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
Definition: ASTReader.cpp:8998
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Definition: ASTReader.cpp:6243
serialization::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:7832
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Definition: ASTReader.cpp:7847
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
Definition: ASTReader.cpp:9086
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:1885
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
Definition: ASTReader.cpp:8927
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:8623
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
Definition: ASTReader.cpp:8671
SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, SourceLocation::UIntTy Raw, LocSeq *Seq=nullptr) const
Read a source location from raw form.
Definition: ASTReader.h:2254
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
Definition: ASTReader.cpp:7149
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:9343
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:8732
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< serialization::GlobalDeclID > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
Definition: ASTReader.cpp:8845
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
Definition: ASTReader.cpp:8008
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
Definition: ASTReader.cpp:8692
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:5409
SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID)
Returns the source location for the decl ID.
Definition: ASTReader.cpp:7690
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
Definition: ASTReader.cpp:8682
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:7681
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:8660
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Definition: ASTReader.cpp:8714
Selector DecodeSelector(serialization::SelectorID Idx)
Definition: ASTReader.cpp:9061
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:1792
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9375
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Definition: ASTReader.cpp:9015
Decl * GetExistingDecl(serialization::GlobalDeclID ID)
Resolve a declaration ID into a declaration.
Definition: ASTReader.cpp:7768
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
Definition: ASTReader.cpp:8877
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:9390
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:9432
ModuleFile * getLocalModuleFile(ModuleFile &M, unsigned ID)
Retrieve the module file with a given local ID within the specified ModuleFile.
Definition: ASTReader.cpp:9002
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:8775
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
Definition: ASTReader.cpp:8470
SmallVector< serialization::GlobalDeclID, 16 > PreloadedDeclIDs
Definition: ASTReader.h:2386
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
Definition: ASTReader.cpp:8750
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:9090
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Definition: ASTReader.cpp:8607
static llvm::BitVector ReadBitVector(const RecordData &Record, const StringRef Blob)
Definition: ASTReader.cpp:9350
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
Definition: ASTReader.cpp:8816
IdentifierInfo * getLocalIdentifier(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:8908
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
Definition: ASTReader.cpp:6542
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:8240
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:8763
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID)
Retrieve the global submodule ID given a module and its local ID number.
Definition: ASTReader.cpp:8969
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition: ASTReader.h:1788
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9402
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:8612
QualType getLocalType(ModuleFile &F, unsigned LocalID)
Resolve a local type ID within a given AST file into a type.
Definition: ASTReader.cpp:7438
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
Definition: ASTReader.cpp:8984
void PrintStats() override
Print some statistics about AST usage.
Definition: ASTReader.cpp:8068
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:9096
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:8569
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:7613
Decl * GetExternalDecl(Decl::DeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7520
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:7443
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:5703
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:6533
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:8954
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:9363
TemplateArgumentLoc readTemplateArgumentLoc()
Reads a TemplateArgumentLoc, advancing Idx.
Definition: ASTReader.cpp:7494
void readTypeLoc(TypeLoc TL, LocSeq *Seq=nullptr)
Reads the location information for a type.
Definition: ASTReader.cpp:7132
void readUnresolvedSet(LazyASTUnresolvedSet &Set)
Read a UnresolvedSet structure, advancing Idx.
Definition: ASTReader.cpp:9191
void readTemplateArgumentList(SmallVectorImpl< TemplateArgument > &TemplArgs, bool Canonicalize=false)
Read a template argument array, advancing Idx.
Definition: ASTReader.cpp:9181
void readQualifierInfo(QualifierInfo &Info)
Definition: ASTReader.cpp:9149
DeclarationNameLoc readDeclarationNameLoc(DeclarationName Name)
Read a declaration name, advancing Idx.
Definition: ASTReader.cpp:9112
CXXBaseSpecifier readCXXBaseSpecifier()
Read a C++ base specifier, advancing Idx.
Definition: ASTReader.cpp:9202
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:9137
IdentifierInfo * readIdentifier()
TemplateArgumentLocInfo readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind, advancing Idx.
Definition: ASTReader.cpp:7462
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:7139
void readTemplateArgumentListInfo(TemplateArgumentListInfo &Result)
Definition: ASTReader.cpp:7504
TypeCoupledDeclRefInfo readTypeCoupledDeclRefInfo()
Definition: ASTReader.cpp:9145
void skipInts(unsigned N)
Skips the specified number of values.
SourceRange readSourceRange(LocSeq *Seq=nullptr)
Read a source range, advancing Idx.
NestedNameSpecifierLoc readNestedNameSpecifierLoc()
Return a nested name specifier, advancing Idx.
Definition: ASTReader.cpp:9282
ConceptReference * readConceptReference()
Definition: ASTReader.cpp:6975
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:9162
OpenACCClause * readOpenACCClause()
Read an OpenACC clause, advancing Idx.
serialization::GlobalDeclID readDeclID()
Reads a declaration ID from the given position in this record.
CXXCtorInitializer ** readCXXCtorInitializers()
Read a CXXCtorInitializer array, advancing Idx.
Definition: ASTReader.cpp:9217
Stmt * readStmt()
Reads a statement.
const ASTTemplateArgumentListInfo * readASTTemplateArgumentListInfo()
Definition: ASTReader.cpp:7514
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:2532
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2297
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition: DeclCXX.h:2484
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2796
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:1684
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition: DeclCXX.h:1791
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:1438
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:2651
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:2624
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2639
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:2324
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition: DeclBase.h:2645
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:2665
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:601
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:851
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:88
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:805
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:778
SourceLocation getLocation() const
Definition: DeclBase.h:447
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1041
DeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition: DeclBase.h:782
DeclContext * getDeclContext()
Definition: DeclBase.h:456
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:910
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:970
Kind getKind() const
Definition: DeclBase.h:450
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:862
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:6313
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:908
static FPOptionsOverride getFromOpaqueInt(storage_type I)
Definition: LangOptions.h:974
FPOptions applyOverrides(FPOptions Base)
Definition: LangOptions.h:981
static FPOptions getFromOpaqueInt(storage_type Value)
Definition: LangOptions.h:872
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:234
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:4446
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4690
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:454
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:489
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:460
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:518
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
Definition: LangOptions.h:532
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:528
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:509
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:515
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:3117
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:1014
Represents an ObjC class declaration.
Definition: DeclObjC.h:1152
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:6742
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1948
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:2079
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:738
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:805
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:148
@ FastWidth
The width of the "fast" qualifier mask.
Definition: Type.h:191
@ FastMask
The fast qualifier mask.
Definition: Type.h:194
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:5339
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:5947
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:2957
void VisitArrayTypeLoc(ArrayTypeLoc)
Definition: ASTReader.cpp:6848
void VisitFunctionTypeLoc(FunctionTypeLoc)
Definition: ASTReader.cpp:6915
TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
Definition: ASTReader.cpp:6776
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:7120
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:1607
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7913
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:2166
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
Definition: ASTReader.cpp:1134
Wrapper class for DeclID.
Definition: ASTBitCodes.h:84
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
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 serialization::LocalDeclID * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition: ModuleFile.h:477
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:8498
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8540
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8545
static TypeIdx fromTypeID(TypeID ID)
Definition: ASTBitCodes.h:177
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:930
PredefinedDeclIDs
Predefined declaration IDs.
Definition: ASTBitCodes.h:1247
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
Definition: ASTBitCodes.h:2122
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:1184
const unsigned int NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition: ASTBitCodes.h:1307
const unsigned NumSpecialTypeIDs
The number of special type IDs.
Definition: ASTBitCodes.h:1239
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:1198
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
Definition: ASTBitCodes.h:1076
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
Definition: ASTBitCodes.h:1049
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
Definition: ASTBitCodes.h:998
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
Definition: ASTBitCodes.h:1007
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
Definition: ASTBitCodes.h:1106
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
Definition: ASTBitCodes.h:1154
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
Definition: ASTBitCodes.h:1088
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
Definition: ASTBitCodes.h:1028
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
Definition: ASTBitCodes.h:1022
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
Definition: ASTBitCodes.h:977
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
Definition: ASTBitCodes.h:1091
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
Definition: ASTBitCodes.h:1034
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
Definition: ASTBitCodes.h:1097
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
Definition: ASTBitCodes.h:1139
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
Definition: ASTBitCodes.h:938
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
Definition: ASTBitCodes.h:1112
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
Definition: ASTBitCodes.h:1130
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
Definition: ASTBitCodes.h:1124
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
Definition: ASTBitCodes.h:941
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
Definition: ASTBitCodes.h:1055
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
Definition: ASTBitCodes.h:1109
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
Definition: ASTBitCodes.h:1040
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
Definition: ASTBitCodes.h:1070
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
Definition: ASTBitCodes.h:980
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
Definition: ASTBitCodes.h:1052
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
Definition: ASTBitCodes.h:971
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
Definition: ASTBitCodes.h:1016
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
Definition: ASTBitCodes.h:1151
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
Definition: ASTBitCodes.h:965
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
Definition: ASTBitCodes.h:944
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
Definition: ASTBitCodes.h:1082
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
Definition: ASTBitCodes.h:962
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
Definition: ASTBitCodes.h:959
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
Definition: ASTBitCodes.h:1001
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
Definition: ASTBitCodes.h:1103
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
Definition: ASTBitCodes.h:1064
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
Definition: ASTBitCodes.h:950
@ PREDEF_TYPE_OMP_ARRAY_SECTION
The placeholder type for OpenMP array section.
Definition: ASTBitCodes.h:1058
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
Definition: ASTBitCodes.h:1061
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
Definition: ASTBitCodes.h:1010
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
Definition: ASTBitCodes.h:1004
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
Definition: ASTBitCodes.h:956
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
Definition: ASTBitCodes.h:1136
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
Definition: ASTBitCodes.h:947
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
Definition: ASTBitCodes.h:968
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
Definition: ASTBitCodes.h:1142
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
Definition: ASTBitCodes.h:992
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
Definition: ASTBitCodes.h:986
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
Definition: ASTBitCodes.h:983
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
Definition: ASTBitCodes.h:995
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
Definition: ASTBitCodes.h:1031
@ PREDEF_TYPE_VOID_ID
The void type.
Definition: ASTBitCodes.h:935
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
Definition: ASTBitCodes.h:1133
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
Definition: ASTBitCodes.h:1073
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
Definition: ASTBitCodes.h:1127
@ PREDEF_TYPE_NULL_ID
The NULL type.
Definition: ASTBitCodes.h:932
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
Definition: ASTBitCodes.h:1079
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
Definition: ASTBitCodes.h:1067
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
Definition: ASTBitCodes.h:1100
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
Definition: ASTBitCodes.h:989
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
Definition: ASTBitCodes.h:1148
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
Definition: ASTBitCodes.h:1115
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
Definition: ASTBitCodes.h:974
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
Definition: ASTBitCodes.h:1121
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
Definition: ASTBitCodes.h:1094
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
Definition: ASTBitCodes.h:1019
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
Definition: ASTBitCodes.h:1145
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
Definition: ASTBitCodes.h:1037
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
Definition: ASTBitCodes.h:1013
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
Definition: ASTBitCodes.h:953
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
Definition: ASTBitCodes.h:1118
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
Definition: ASTBitCodes.h:1046
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
Definition: ASTBitCodes.h:1043
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
Definition: ASTBitCodes.h:1085
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
Definition: ASTBitCodes.h:1025
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition: ASTBitCodes.h:1258
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition: ASTBitCodes.h:1270
@ PREDEF_DECL_OBJC_CLASS_ID
The Objective-C 'Class' type.
Definition: ASTBitCodes.h:1261
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition: ASTBitCodes.h:1255
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition: ASTBitCodes.h:1267
@ PREDEF_DECL_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition: ASTBitCodes.h:1273
@ PREDEF_DECL_BUILTIN_MS_GUID_ID
The predeclared '_GUID' struct.
Definition: ASTBitCodes.h:1285
@ PREDEF_DECL_MAKE_INTEGER_SEQ_ID
The internal '__make_integer_seq' template.
Definition: ASTBitCodes.h:1291
@ PREDEF_DECL_NULL_ID
The NULL declaration.
Definition: ASTBitCodes.h:1249
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition: ASTBitCodes.h:1288
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition: ASTBitCodes.h:1264
@ PREDEF_DECL_TYPE_PACK_ELEMENT_ID
The internal '__type_pack_element' template.
Definition: ASTBitCodes.h:1300
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition: ASTBitCodes.h:1282
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition: ASTBitCodes.h:1276
@ PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID
The internal '__NSConstantString' tag type.
Definition: ASTBitCodes.h:1297
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition: ASTBitCodes.h:1252
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition: ASTBitCodes.h:1279
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition: ASTBitCodes.h:1294
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1542
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
Definition: ASTBitCodes.h:1422
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1545
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1431
@ TYPE_EXT_QUAL
An ExtQualType record.
Definition: ASTBitCodes.h:1204
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
Definition: ASTBitCodes.h:1232
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
Definition: ASTBitCodes.h:1235
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
Definition: ASTBitCodes.h:1220
@ SPECIAL_TYPE_FILE
C FILE typedef type.
Definition: ASTBitCodes.h:1217
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
Definition: ASTBitCodes.h:1223
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
Definition: ASTBitCodes.h:1229
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
Definition: ASTBitCodes.h:1214
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Definition: ASTBitCodes.h:1226
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:489
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:158
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
Definition: ASTBitCodes.h:879
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:861
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:899
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:858
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
Definition: ASTBitCodes.h:907
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
Definition: ASTBitCodes.h:864
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:855
@ SUBMODULE_METADATA
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:847
@ SUBMODULE_REQUIRES
Specifies a required feature.
Definition: ASTBitCodes.h:875
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:891
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:868
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
Definition: ASTBitCodes.h:888
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
Definition: ASTBitCodes.h:903
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:851
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:882
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:885
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:872
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:895
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
Definition: ASTBitCodes.h:910
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition: ASTBitCodes.h:210
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:244
OptionsRecordTypes
Record types that occur within the options block inside the control block.
Definition: ASTBitCodes.h:440
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
Definition: ASTBitCodes.h:453
@ TARGET_OPTIONS
Record code for the target options table.
Definition: ASTBitCodes.h:450
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
Definition: ASTBitCodes.h:459
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
Definition: ASTBitCodes.h:456
@ LANGUAGE_OPTIONS
Record code for the language options table.
Definition: ASTBitCodes.h:447
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:226
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
Definition: ASTBitCodes.h:346
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:241
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
Definition: ASTBitCodes.h:247
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
Definition: ASTBitCodes.h:371
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
Definition: ASTBitCodes.h:368
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
Definition: ASTBitCodes.h:353
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
Definition: ASTBitCodes.h:357
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
Definition: ASTBitCodes.h:379
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
Definition: ASTBitCodes.h:365
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
Definition: ASTBitCodes.h:361
@ COMMENTS_BLOCK_ID
The block containing comments.
Definition: ASTBitCodes.h:374
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
Definition: ASTBitCodes.h:401
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
Definition: ASTBitCodes.h:395
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
Definition: ASTBitCodes.h:392
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
Definition: ASTBitCodes.h:385
uint32_t IdentID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:207
CommentRecordTypes
Record types used within a comments block.
Definition: ASTBitCodes.h:914
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:784
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:798
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:788
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:794
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:802
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
Definition: ASTBitCodes.h:229
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:44
PreprocessorRecordTypes
Record types used within a preprocessor block.
Definition: ASTBitCodes.h:806
@ PP_TOKEN
Describes one token.
Definition: ASTBitCodes.h:821
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
Definition: ASTBitCodes.h:817
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
Definition: ASTBitCodes.h:812
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:824
@ PP_MODULE_MACRO
A macro directive exported by a module.
Definition: ASTBitCodes.h:828
ControlRecordTypes
Record types that occur within the control block.
Definition: ASTBitCodes.h:405
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
Definition: ASTBitCodes.h:432
@ MODULE_DIRECTORY
Record code for the module build directory.
Definition: ASTBitCodes.h:435
@ IMPORTS
Record code for the list of other AST files imported by this AST file.
Definition: ASTBitCodes.h:412
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
Definition: ASTBitCodes.h:421
@ MODULE_NAME
Record code for the module name.
Definition: ASTBitCodes.h:428
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
Definition: ASTBitCodes.h:417
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
Definition: ASTBitCodes.h:425
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
Definition: ASTBitCodes.h:408
UnhashedControlBlockRecordTypes
Record codes for the unhashed control block.
Definition: ASTBitCodes.h:463
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:471
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
Definition: ASTBitCodes.h:480
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
Definition: ASTBitCodes.h:468
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:477
@ SIGNATURE
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:465
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
Definition: ASTBitCodes.h:474
@ VFS_USAGE
Record code for the indices of used VFSs.
Definition: ASTBitCodes.h:483
uint32_t DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:70
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
Definition: ASTBitCodes.h:497
@ INPUT_FILE_HASH
The input file content hash.
Definition: ASTBitCodes.h:502
@ INPUT_FILE
An input file.
Definition: ASTBitCodes.h:499
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
Definition: ASTBitCodes.h:832
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:841
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:834
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:837
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:223
ASTRecordTypes
Record types that occur within the AST block itself.
Definition: ASTBitCodes.h:506
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:647
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:581
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
Definition: ASTBitCodes.h:767
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:673
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:577
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:636
@ TYPE_OFFSET
Record code for the offsets of each type.
Definition: ASTBitCodes.h:519
@ DELEGATING_CTORS
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:669
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
Definition: ASTBitCodes.h:773
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:606
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:666
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:663
@ VTABLE_USES
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:616
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
Definition: ASTBitCodes.h:723
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
Definition: ASTBitCodes.h:764
@ DECL_OFFSET
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:531
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:683
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
Definition: ASTBitCodes.h:597
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:734
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:643
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched #pragma clang cuda_force_host_device begin directives we've seen.
Definition: ASTBitCodes.h:744
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:711
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:613
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:539
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:704
@ METHOD_POOL
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:593
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
Definition: ASTBitCodes.h:777
@ PP_CONDITIONAL_STACK
The stack of open #ifs/#ifdefs recorded in a preamble.
Definition: ASTBitCodes.h:758
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
Definition: ASTBitCodes.h:621
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:601
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:633
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
Definition: ASTBitCodes.h:720
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:690
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:737
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:584
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:609
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
Definition: ASTBitCodes.h:755
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
Definition: ASTBitCodes.h:694
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:590
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:729
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:568
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
Definition: ASTBitCodes.h:716
@ HEADER_SEARCH_TABLE
Record code for header search information.
Definition: ASTBitCodes.h:660
@ 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:687
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:657
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:625
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
Definition: ASTBitCodes.h:761
@ IDENTIFIER_TABLE
Record code for the identifier table.
Definition: ASTBitCodes.h:558
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:630
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:726
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:679
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:740
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:213
uint32_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:60
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
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
@ 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:2483
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:4532
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:314
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:2133
Source range/offset of a preprocessed entity.
Definition: ASTBitCodes.h:250
uint32_t BitOffset
Offset in the AST file relative to ModuleFile::MacroOffsetsBase.
Definition: ASTBitCodes.h:258
SourceLocation getBegin() const
Definition: ASTBitCodes.h:264
SourceLocation getEnd() const
Definition: ASTBitCodes.h:268
Source range of a skipped preprocessor region.
Definition: ASTBitCodes.h:274
SourceLocation getBegin() const
Definition: ASTBitCodes.h:284
SourceLocation getEnd() const
Definition: ASTBitCodes.h:287