clang 20.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"
54#include "clang/Basic/LLVM.h"
56#include "clang/Basic/Module.h"
70#include "clang/Basic/Version.h"
73#include "clang/Lex/MacroInfo.h"
74#include "clang/Lex/ModuleMap.h"
78#include "clang/Lex/Token.h"
80#include "clang/Sema/Scope.h"
81#include "clang/Sema/Sema.h"
82#include "clang/Sema/SemaCUDA.h"
83#include "clang/Sema/SemaObjC.h"
84#include "clang/Sema/Weak.h"
96#include "llvm/ADT/APFloat.h"
97#include "llvm/ADT/APInt.h"
98#include "llvm/ADT/APSInt.h"
99#include "llvm/ADT/ArrayRef.h"
100#include "llvm/ADT/DenseMap.h"
101#include "llvm/ADT/FloatingPointMode.h"
102#include "llvm/ADT/FoldingSet.h"
103#include "llvm/ADT/Hashing.h"
104#include "llvm/ADT/IntrusiveRefCntPtr.h"
105#include "llvm/ADT/STLExtras.h"
106#include "llvm/ADT/ScopeExit.h"
107#include "llvm/ADT/Sequence.h"
108#include "llvm/ADT/SmallPtrSet.h"
109#include "llvm/ADT/SmallString.h"
110#include "llvm/ADT/SmallVector.h"
111#include "llvm/ADT/StringExtras.h"
112#include "llvm/ADT/StringMap.h"
113#include "llvm/ADT/StringRef.h"
114#include "llvm/ADT/iterator_range.h"
115#include "llvm/Bitstream/BitstreamReader.h"
116#include "llvm/Support/Casting.h"
117#include "llvm/Support/Compiler.h"
118#include "llvm/Support/Compression.h"
119#include "llvm/Support/DJB.h"
120#include "llvm/Support/Endian.h"
121#include "llvm/Support/Error.h"
122#include "llvm/Support/ErrorHandling.h"
123#include "llvm/Support/FileSystem.h"
124#include "llvm/Support/LEB128.h"
125#include "llvm/Support/MemoryBuffer.h"
126#include "llvm/Support/Path.h"
127#include "llvm/Support/SaveAndRestore.h"
128#include "llvm/Support/TimeProfiler.h"
129#include "llvm/Support/Timer.h"
130#include "llvm/Support/VersionTuple.h"
131#include "llvm/Support/raw_ostream.h"
132#include "llvm/TargetParser/Triple.h"
133#include <algorithm>
134#include <cassert>
135#include <cstddef>
136#include <cstdint>
137#include <cstdio>
138#include <ctime>
139#include <iterator>
140#include <limits>
141#include <map>
142#include <memory>
143#include <optional>
144#include <string>
145#include <system_error>
146#include <tuple>
147#include <utility>
148#include <vector>
149
150using namespace clang;
151using namespace clang::serialization;
152using namespace clang::serialization::reader;
153using llvm::BitstreamCursor;
154
155//===----------------------------------------------------------------------===//
156// ChainedASTReaderListener implementation
157//===----------------------------------------------------------------------===//
158
159bool
161 return First->ReadFullVersionInformation(FullVersion) ||
162 Second->ReadFullVersionInformation(FullVersion);
163}
164
166 First->ReadModuleName(ModuleName);
167 Second->ReadModuleName(ModuleName);
168}
169
170void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
171 First->ReadModuleMapFile(ModuleMapPath);
172 Second->ReadModuleMapFile(ModuleMapPath);
173}
174
176 const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain,
177 bool AllowCompatibleDifferences) {
178 return First->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
179 AllowCompatibleDifferences) ||
180 Second->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
181 AllowCompatibleDifferences);
182}
183
185 const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain,
186 bool AllowCompatibleDifferences) {
187 return First->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
188 AllowCompatibleDifferences) ||
189 Second->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
190 AllowCompatibleDifferences);
191}
192
194 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, StringRef ModuleFilename,
195 bool Complain) {
196 return First->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain) ||
197 Second->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
198}
199
200bool
202 bool Complain) {
203 return First->ReadFileSystemOptions(FSOpts, Complain) ||
204 Second->ReadFileSystemOptions(FSOpts, Complain);
205}
206
208 const HeaderSearchOptions &HSOpts, StringRef ModuleFilename,
209 StringRef SpecificModuleCachePath, bool Complain) {
210 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
211 SpecificModuleCachePath, Complain) ||
212 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
213 SpecificModuleCachePath, Complain);
214}
215
217 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
218 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
219 return First->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
220 Complain, SuggestedPredefines) ||
221 Second->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
222 Complain, SuggestedPredefines);
223}
224
226 unsigned Value) {
227 First->ReadCounter(M, Value);
228 Second->ReadCounter(M, Value);
229}
230
232 return First->needsInputFileVisitation() ||
233 Second->needsInputFileVisitation();
234}
235
237 return First->needsSystemInputFileVisitation() ||
238 Second->needsSystemInputFileVisitation();
239}
240
242 ModuleKind Kind) {
243 First->visitModuleFile(Filename, Kind);
244 Second->visitModuleFile(Filename, Kind);
245}
246
248 bool isSystem,
249 bool isOverridden,
250 bool isExplicitModule) {
251 bool Continue = false;
252 if (First->needsInputFileVisitation() &&
253 (!isSystem || First->needsSystemInputFileVisitation()))
254 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
255 isExplicitModule);
256 if (Second->needsInputFileVisitation() &&
257 (!isSystem || Second->needsSystemInputFileVisitation()))
258 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
259 isExplicitModule);
260 return Continue;
261}
262
264 const ModuleFileExtensionMetadata &Metadata) {
265 First->readModuleFileExtension(Metadata);
266 Second->readModuleFileExtension(Metadata);
267}
268
269//===----------------------------------------------------------------------===//
270// PCH validator implementation
271//===----------------------------------------------------------------------===//
272
274
275/// Compare the given set of language options against an existing set of
276/// language options.
277///
278/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
279/// \param AllowCompatibleDifferences If true, differences between compatible
280/// language options will be permitted.
281///
282/// \returns true if the languagae options mis-match, false otherwise.
283static bool checkLanguageOptions(const LangOptions &LangOpts,
284 const LangOptions &ExistingLangOpts,
285 StringRef ModuleFilename,
286 DiagnosticsEngine *Diags,
287 bool AllowCompatibleDifferences = true) {
288#define LANGOPT(Name, Bits, Default, Description) \
289 if (ExistingLangOpts.Name != LangOpts.Name) { \
290 if (Diags) { \
291 if (Bits == 1) \
292 Diags->Report(diag::err_ast_file_langopt_mismatch) \
293 << Description << LangOpts.Name << ExistingLangOpts.Name \
294 << ModuleFilename; \
295 else \
296 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
297 << Description << ModuleFilename; \
298 } \
299 return true; \
300 }
301
302#define VALUE_LANGOPT(Name, Bits, Default, Description) \
303 if (ExistingLangOpts.Name != LangOpts.Name) { \
304 if (Diags) \
305 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
306 << Description << ModuleFilename; \
307 return true; \
308 }
309
310#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
311 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
312 if (Diags) \
313 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
314 << Description << ModuleFilename; \
315 return true; \
316 }
317
318#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
319 if (!AllowCompatibleDifferences) \
320 LANGOPT(Name, Bits, Default, Description)
321
322#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
323 if (!AllowCompatibleDifferences) \
324 ENUM_LANGOPT(Name, Bits, Default, Description)
325
326#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
327 if (!AllowCompatibleDifferences) \
328 VALUE_LANGOPT(Name, Bits, Default, Description)
329
330#define BENIGN_LANGOPT(Name, Bits, Default, Description)
331#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
332#define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
333#include "clang/Basic/LangOptions.def"
334
335 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
336 if (Diags)
337 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
338 << "module features" << ModuleFilename;
339 return true;
340 }
341
342 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
343 if (Diags)
344 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
345 << "target Objective-C runtime" << ModuleFilename;
346 return true;
347 }
348
349 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
351 if (Diags)
352 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
353 << "block command names" << ModuleFilename;
354 return true;
355 }
356
357 // Sanitizer feature mismatches are treated as compatible differences. If
358 // compatible differences aren't allowed, we still only want to check for
359 // mismatches of non-modular sanitizers (the only ones which can affect AST
360 // generation).
361 if (!AllowCompatibleDifferences) {
362 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
363 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
364 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
365 ExistingSanitizers.clear(ModularSanitizers);
366 ImportedSanitizers.clear(ModularSanitizers);
367 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
368 const std::string Flag = "-fsanitize=";
369 if (Diags) {
370#define SANITIZER(NAME, ID) \
371 { \
372 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
373 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
374 if (InExistingModule != InImportedModule) \
375 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \
376 << InExistingModule << ModuleFilename << (Flag + NAME); \
377 }
378#include "clang/Basic/Sanitizers.def"
379 }
380 return true;
381 }
382 }
383
384 return false;
385}
386
387/// Compare the given set of target options against an existing set of
388/// target options.
389///
390/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
391///
392/// \returns true if the target options mis-match, false otherwise.
393static bool checkTargetOptions(const TargetOptions &TargetOpts,
394 const TargetOptions &ExistingTargetOpts,
395 StringRef ModuleFilename,
396 DiagnosticsEngine *Diags,
397 bool AllowCompatibleDifferences = true) {
398#define CHECK_TARGET_OPT(Field, Name) \
399 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
400 if (Diags) \
401 Diags->Report(diag::err_ast_file_targetopt_mismatch) \
402 << ModuleFilename << Name << TargetOpts.Field \
403 << ExistingTargetOpts.Field; \
404 return true; \
405 }
406
407 // The triple and ABI must match exactly.
408 CHECK_TARGET_OPT(Triple, "target");
409 CHECK_TARGET_OPT(ABI, "target ABI");
410
411 // We can tolerate different CPUs in many cases, notably when one CPU
412 // supports a strict superset of another. When allowing compatible
413 // differences skip this check.
414 if (!AllowCompatibleDifferences) {
415 CHECK_TARGET_OPT(CPU, "target CPU");
416 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
417 }
418
419#undef CHECK_TARGET_OPT
420
421 // Compare feature sets.
422 SmallVector<StringRef, 4> ExistingFeatures(
423 ExistingTargetOpts.FeaturesAsWritten.begin(),
424 ExistingTargetOpts.FeaturesAsWritten.end());
425 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
426 TargetOpts.FeaturesAsWritten.end());
427 llvm::sort(ExistingFeatures);
428 llvm::sort(ReadFeatures);
429
430 // We compute the set difference in both directions explicitly so that we can
431 // diagnose the differences differently.
432 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
433 std::set_difference(
434 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
435 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
436 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
437 ExistingFeatures.begin(), ExistingFeatures.end(),
438 std::back_inserter(UnmatchedReadFeatures));
439
440 // If we are allowing compatible differences and the read feature set is
441 // a strict subset of the existing feature set, there is nothing to diagnose.
442 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
443 return false;
444
445 if (Diags) {
446 for (StringRef Feature : UnmatchedReadFeatures)
447 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
448 << /* is-existing-feature */ false << ModuleFilename << Feature;
449 for (StringRef Feature : UnmatchedExistingFeatures)
450 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
451 << /* is-existing-feature */ true << ModuleFilename << Feature;
452 }
453
454 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
455}
456
458 StringRef ModuleFilename, bool Complain,
459 bool AllowCompatibleDifferences) {
460 const LangOptions &ExistingLangOpts = PP.getLangOpts();
461 return checkLanguageOptions(LangOpts, ExistingLangOpts, ModuleFilename,
462 Complain ? &Reader.Diags : nullptr,
463 AllowCompatibleDifferences);
464}
465
467 StringRef ModuleFilename, bool Complain,
468 bool AllowCompatibleDifferences) {
469 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
470 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
471 Complain ? &Reader.Diags : nullptr,
472 AllowCompatibleDifferences);
473}
474
475namespace {
476
477using MacroDefinitionsMap =
478 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
479using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
480
481} // namespace
482
484 DiagnosticsEngine &Diags,
485 StringRef ModuleFilename,
486 bool Complain) {
487 using Level = DiagnosticsEngine::Level;
488
489 // Check current mappings for new -Werror mappings, and the stored mappings
490 // for cases that were explicitly mapped to *not* be errors that are now
491 // errors because of options like -Werror.
492 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
493
494 for (DiagnosticsEngine *MappingSource : MappingSources) {
495 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
496 diag::kind DiagID = DiagIDMappingPair.first;
497 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
498 if (CurLevel < DiagnosticsEngine::Error)
499 continue; // not significant
500 Level StoredLevel =
501 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
502 if (StoredLevel < DiagnosticsEngine::Error) {
503 if (Complain)
504 Diags.Report(diag::err_ast_file_diagopt_mismatch)
505 << "-Werror=" + Diags.getDiagnosticIDs()
506 ->getWarningOptionForDiag(DiagID)
507 .str()
508 << ModuleFilename;
509 return true;
510 }
511 }
512 }
513
514 return false;
515}
516
519 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
520 return true;
521 return Ext >= diag::Severity::Error;
522}
523
525 DiagnosticsEngine &Diags,
526 StringRef ModuleFilename, bool IsSystem,
527 bool SystemHeaderWarningsInModule,
528 bool Complain) {
529 // Top-level options
530 if (IsSystem) {
531 if (Diags.getSuppressSystemWarnings())
532 return false;
533 // If -Wsystem-headers was not enabled before, and it was not explicit,
534 // be conservative
535 if (StoredDiags.getSuppressSystemWarnings() &&
536 !SystemHeaderWarningsInModule) {
537 if (Complain)
538 Diags.Report(diag::err_ast_file_diagopt_mismatch)
539 << "-Wsystem-headers" << ModuleFilename;
540 return true;
541 }
542 }
543
544 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
545 if (Complain)
546 Diags.Report(diag::err_ast_file_diagopt_mismatch)
547 << "-Werror" << ModuleFilename;
548 return true;
549 }
550
551 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
552 !StoredDiags.getEnableAllWarnings()) {
553 if (Complain)
554 Diags.Report(diag::err_ast_file_diagopt_mismatch)
555 << "-Weverything -Werror" << ModuleFilename;
556 return true;
557 }
558
559 if (isExtHandlingFromDiagsError(Diags) &&
560 !isExtHandlingFromDiagsError(StoredDiags)) {
561 if (Complain)
562 Diags.Report(diag::err_ast_file_diagopt_mismatch)
563 << "-pedantic-errors" << ModuleFilename;
564 return true;
565 }
566
567 return checkDiagnosticGroupMappings(StoredDiags, Diags, ModuleFilename,
568 Complain);
569}
570
571/// Return the top import module if it is implicit, nullptr otherwise.
573 Preprocessor &PP) {
574 // If the original import came from a file explicitly generated by the user,
575 // don't check the diagnostic mappings.
576 // FIXME: currently this is approximated by checking whether this is not a
577 // module import of an implicitly-loaded module file.
578 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
579 // the transitive closure of its imports, since unrelated modules cannot be
580 // imported until after this module finishes validation.
581 ModuleFile *TopImport = &*ModuleMgr.rbegin();
582 while (!TopImport->ImportedBy.empty())
583 TopImport = TopImport->ImportedBy[0];
584 if (TopImport->Kind != MK_ImplicitModule)
585 return nullptr;
586
587 StringRef ModuleName = TopImport->ModuleName;
588 assert(!ModuleName.empty() && "diagnostic options read before module name");
589
590 Module *M =
591 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
592 assert(M && "missing module");
593 return M;
594}
595
597 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, StringRef ModuleFilename,
598 bool Complain) {
599 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
602 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
603 // This should never fail, because we would have processed these options
604 // before writing them to an ASTFile.
605 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
606
607 ModuleManager &ModuleMgr = Reader.getModuleManager();
608 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
609
610 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
611 if (!TopM)
612 return false;
613
614 Module *Importer = PP.getCurrentModule();
615
616 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
617 bool SystemHeaderWarningsInModule =
618 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
619 Importer->Name);
620
621 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
622 // contains the union of their flags.
623 return checkDiagnosticMappings(*Diags, ExistingDiags, ModuleFilename,
624 TopM->IsSystem, SystemHeaderWarningsInModule,
625 Complain);
626}
627
628/// Collect the macro definitions provided by the given preprocessor
629/// options.
630static void
632 MacroDefinitionsMap &Macros,
633 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
634 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
635 StringRef Macro = PPOpts.Macros[I].first;
636 bool IsUndef = PPOpts.Macros[I].second;
637
638 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
639 StringRef MacroName = MacroPair.first;
640 StringRef MacroBody = MacroPair.second;
641
642 // For an #undef'd macro, we only care about the name.
643 if (IsUndef) {
644 if (MacroNames && !Macros.count(MacroName))
645 MacroNames->push_back(MacroName);
646
647 Macros[MacroName] = std::make_pair("", true);
648 continue;
649 }
650
651 // For a #define'd macro, figure out the actual definition.
652 if (MacroName.size() == Macro.size())
653 MacroBody = "1";
654 else {
655 // Note: GCC drops anything following an end-of-line character.
656 StringRef::size_type End = MacroBody.find_first_of("\n\r");
657 MacroBody = MacroBody.substr(0, End);
658 }
659
660 if (MacroNames && !Macros.count(MacroName))
661 MacroNames->push_back(MacroName);
662 Macros[MacroName] = std::make_pair(MacroBody, false);
663 }
664}
665
670};
671
672/// Check the preprocessor options deserialized from the control block
673/// against the preprocessor options in an existing preprocessor.
674///
675/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
676/// \param Validation If set to OptionValidateNone, ignore differences in
677/// preprocessor options. If set to OptionValidateContradictions,
678/// require that options passed both in the AST file and on the command
679/// line (-D or -U) match, but tolerate options missing in one or the
680/// other. If set to OptionValidateContradictions, require that there
681/// are no differences in the options between the two.
683 const PreprocessorOptions &PPOpts,
684 const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename,
685 bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr,
686 std::string &SuggestedPredefines, const LangOptions &LangOpts,
688 if (ReadMacros) {
689 // Check macro definitions.
690 MacroDefinitionsMap ASTFileMacros;
691 collectMacroDefinitions(PPOpts, ASTFileMacros);
692 MacroDefinitionsMap ExistingMacros;
693 SmallVector<StringRef, 4> ExistingMacroNames;
694 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
695 &ExistingMacroNames);
696
697 // Use a line marker to enter the <command line> file, as the defines and
698 // undefines here will have come from the command line.
699 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
700
701 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
702 // Dig out the macro definition in the existing preprocessor options.
703 StringRef MacroName = ExistingMacroNames[I];
704 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
705
706 // Check whether we know anything about this macro name or not.
707 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
708 ASTFileMacros.find(MacroName);
709 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
710 if (Validation == OptionValidateStrictMatches) {
711 // If strict matches are requested, don't tolerate any extra defines
712 // on the command line that are missing in the AST file.
713 if (Diags) {
714 Diags->Report(diag::err_ast_file_macro_def_undef)
715 << MacroName << true << ModuleFilename;
716 }
717 return true;
718 }
719 // FIXME: Check whether this identifier was referenced anywhere in the
720 // AST file. If so, we should reject the AST file. Unfortunately, this
721 // information isn't in the control block. What shall we do about it?
722
723 if (Existing.second) {
724 SuggestedPredefines += "#undef ";
725 SuggestedPredefines += MacroName.str();
726 SuggestedPredefines += '\n';
727 } else {
728 SuggestedPredefines += "#define ";
729 SuggestedPredefines += MacroName.str();
730 SuggestedPredefines += ' ';
731 SuggestedPredefines += Existing.first.str();
732 SuggestedPredefines += '\n';
733 }
734 continue;
735 }
736
737 // If the macro was defined in one but undef'd in the other, we have a
738 // conflict.
739 if (Existing.second != Known->second.second) {
740 if (Diags) {
741 Diags->Report(diag::err_ast_file_macro_def_undef)
742 << MacroName << Known->second.second << ModuleFilename;
743 }
744 return true;
745 }
746
747 // If the macro was #undef'd in both, or if the macro bodies are
748 // identical, it's fine.
749 if (Existing.second || Existing.first == Known->second.first) {
750 ASTFileMacros.erase(Known);
751 continue;
752 }
753
754 // The macro bodies differ; complain.
755 if (Diags) {
756 Diags->Report(diag::err_ast_file_macro_def_conflict)
757 << MacroName << Known->second.first << Existing.first
758 << ModuleFilename;
759 }
760 return true;
761 }
762
763 // Leave the <command line> file and return to <built-in>.
764 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
765
766 if (Validation == OptionValidateStrictMatches) {
767 // If strict matches are requested, don't tolerate any extra defines in
768 // the AST file that are missing on the command line.
769 for (const auto &MacroName : ASTFileMacros.keys()) {
770 if (Diags) {
771 Diags->Report(diag::err_ast_file_macro_def_undef)
772 << MacroName << false << ModuleFilename;
773 }
774 return true;
775 }
776 }
777 }
778
779 // Check whether we're using predefines.
780 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
781 Validation != OptionValidateNone) {
782 if (Diags) {
783 Diags->Report(diag::err_ast_file_undef)
784 << ExistingPPOpts.UsePredefines << ModuleFilename;
785 }
786 return true;
787 }
788
789 // Detailed record is important since it is used for the module cache hash.
790 if (LangOpts.Modules &&
791 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
792 Validation != OptionValidateNone) {
793 if (Diags) {
794 Diags->Report(diag::err_ast_file_pp_detailed_record)
795 << PPOpts.DetailedRecord << ModuleFilename;
796 }
797 return true;
798 }
799
800 // Compute the #include and #include_macros lines we need.
801 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
802 StringRef File = ExistingPPOpts.Includes[I];
803
804 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
805 !ExistingPPOpts.PCHThroughHeader.empty()) {
806 // In case the through header is an include, we must add all the includes
807 // to the predefines so the start point can be determined.
808 SuggestedPredefines += "#include \"";
809 SuggestedPredefines += File;
810 SuggestedPredefines += "\"\n";
811 continue;
812 }
813
814 if (File == ExistingPPOpts.ImplicitPCHInclude)
815 continue;
816
817 if (llvm::is_contained(PPOpts.Includes, File))
818 continue;
819
820 SuggestedPredefines += "#include \"";
821 SuggestedPredefines += File;
822 SuggestedPredefines += "\"\n";
823 }
824
825 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
826 StringRef File = ExistingPPOpts.MacroIncludes[I];
827 if (llvm::is_contained(PPOpts.MacroIncludes, File))
828 continue;
829
830 SuggestedPredefines += "#__include_macros \"";
831 SuggestedPredefines += File;
832 SuggestedPredefines += "\"\n##\n";
833 }
834
835 return false;
836}
837
839 StringRef ModuleFilename,
840 bool ReadMacros, bool Complain,
841 std::string &SuggestedPredefines) {
842 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
843
845 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros,
846 Complain ? &Reader.Diags : nullptr, PP.getFileManager(),
847 SuggestedPredefines, PP.getLangOpts());
848}
849
851 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
852 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
854 ModuleFilename, ReadMacros, nullptr,
855 PP.getFileManager(), SuggestedPredefines,
857}
858
859/// Check that the specified and the existing module cache paths are equivalent.
860///
861/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
862/// \returns true when the module cache paths differ.
863static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS,
864 StringRef SpecificModuleCachePath,
865 StringRef ExistingModuleCachePath,
866 StringRef ModuleFilename,
867 DiagnosticsEngine *Diags,
868 const LangOptions &LangOpts,
869 const PreprocessorOptions &PPOpts) {
870 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
871 SpecificModuleCachePath == ExistingModuleCachePath)
872 return false;
873 auto EqualOrErr =
874 VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath);
875 if (EqualOrErr && *EqualOrErr)
876 return false;
877 if (Diags)
878 Diags->Report(diag::err_ast_file_modulecache_mismatch)
879 << SpecificModuleCachePath << ExistingModuleCachePath << ModuleFilename;
880 return true;
881}
882
884 StringRef ModuleFilename,
885 StringRef SpecificModuleCachePath,
886 bool Complain) {
888 Reader.getFileManager().getVirtualFileSystem(), SpecificModuleCachePath,
889 PP.getHeaderSearchInfo().getModuleCachePath(), ModuleFilename,
890 Complain ? &Reader.Diags : nullptr, PP.getLangOpts(),
892}
893
896}
897
898//===----------------------------------------------------------------------===//
899// AST reader implementation
900//===----------------------------------------------------------------------===//
901
902static uint64_t readULEB(const unsigned char *&P) {
903 unsigned Length = 0;
904 const char *Error = nullptr;
905
906 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
907 if (Error)
908 llvm::report_fatal_error(Error);
909 P += Length;
910 return Val;
911}
912
913/// Read ULEB-encoded key length and data length.
914static std::pair<unsigned, unsigned>
915readULEBKeyDataLength(const unsigned char *&P) {
916 unsigned KeyLen = readULEB(P);
917 if ((unsigned)KeyLen != KeyLen)
918 llvm::report_fatal_error("key too large");
919
920 unsigned DataLen = readULEB(P);
921 if ((unsigned)DataLen != DataLen)
922 llvm::report_fatal_error("data too large");
923
924 return std::make_pair(KeyLen, DataLen);
925}
926
928 bool TakeOwnership) {
929 DeserializationListener = Listener;
930 OwnsDeserializationListener = TakeOwnership;
931}
932
934 return serialization::ComputeHash(Sel);
935}
936
939#ifndef NDEBUG
940 if (!MF.ModuleOffsetMap.empty())
941 Reader.ReadModuleOffsetMap(MF);
942
943 unsigned ModuleFileIndex = ID.getModuleFileIndex();
944 unsigned LocalDeclID = ID.getLocalDeclIndex();
945
946 assert(ModuleFileIndex <= MF.TransitiveImports.size());
947
948 ModuleFile *OwningModuleFile =
949 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
950 assert(OwningModuleFile);
951
952 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
953
954 if (!ModuleFileIndex)
955 LocalNumDecls += NUM_PREDEF_DECL_IDS;
956
957 assert(LocalDeclID < LocalNumDecls);
958#endif
959 (void)Reader;
960 (void)MF;
961 return ID;
962}
963
965 unsigned ModuleFileIndex, unsigned LocalDeclID) {
966 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
967 return LocalDeclID::get(Reader, MF, Value);
968}
969
970std::pair<unsigned, unsigned>
972 return readULEBKeyDataLength(d);
973}
974
976ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
977 using namespace llvm::support;
978
979 SelectorTable &SelTable = Reader.getContext().Selectors;
980 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
981 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
982 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
983 if (N == 0)
984 return SelTable.getNullarySelector(FirstII);
985 else if (N == 1)
986 return SelTable.getUnarySelector(FirstII);
987
989 Args.push_back(FirstII);
990 for (unsigned I = 1; I != N; ++I)
991 Args.push_back(Reader.getLocalIdentifier(
992 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
993
994 return SelTable.getSelector(N, Args.data());
995}
996
999 unsigned DataLen) {
1000 using namespace llvm::support;
1001
1003
1004 Result.ID = Reader.getGlobalSelectorID(
1005 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1006 unsigned FullInstanceBits =
1007 endian::readNext<uint16_t, llvm::endianness::little>(d);
1008 unsigned FullFactoryBits =
1009 endian::readNext<uint16_t, llvm::endianness::little>(d);
1010 Result.InstanceBits = FullInstanceBits & 0x3;
1011 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1012 Result.FactoryBits = FullFactoryBits & 0x3;
1013 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1014 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1015 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1016
1017 // Load instance methods
1018 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
1019 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1021 Reader, F,
1022 endian::readNext<DeclID, llvm::endianness::little>(d))))
1023 Result.Instance.push_back(Method);
1024 }
1025
1026 // Load factory methods
1027 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1028 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1030 Reader, F,
1031 endian::readNext<DeclID, llvm::endianness::little>(d))))
1032 Result.Factory.push_back(Method);
1033 }
1034
1035 return Result;
1036}
1037
1039 return llvm::djbHash(a);
1040}
1041
1042std::pair<unsigned, unsigned>
1044 return readULEBKeyDataLength(d);
1045}
1046
1048ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1049 assert(n >= 2 && d[n-1] == '\0');
1050 return StringRef((const char*) d, n-1);
1051}
1052
1053/// Whether the given identifier is "interesting".
1054static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1055 bool IsModule) {
1056 bool IsInteresting =
1057 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1059 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1060 return II.hadMacroDefinition() || II.isPoisoned() ||
1061 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1062 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1063 II.getFETokenInfo());
1064}
1065
1066static bool readBit(unsigned &Bits) {
1067 bool Value = Bits & 0x1;
1068 Bits >>= 1;
1069 return Value;
1070}
1071
1073 using namespace llvm::support;
1074
1075 IdentifierID RawID =
1076 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1077 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1078}
1079
1081 bool IsModule) {
1082 if (!II.isFromAST()) {
1083 II.setIsFromAST();
1084 if (isInterestingIdentifier(Reader, II, IsModule))
1086 }
1087}
1088
1090 const unsigned char* d,
1091 unsigned DataLen) {
1092 using namespace llvm::support;
1093
1094 IdentifierID RawID =
1095 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1096 bool IsInteresting = RawID & 0x01;
1097
1098 DataLen -= sizeof(IdentifierID);
1099
1100 // Wipe out the "is interesting" bit.
1101 RawID = RawID >> 1;
1102
1103 // Build the IdentifierInfo and link the identifier ID with it.
1104 IdentifierInfo *II = KnownII;
1105 if (!II) {
1106 II = &Reader.getIdentifierTable().getOwn(k);
1107 KnownII = II;
1108 }
1109 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1110 markIdentifierFromAST(Reader, *II, IsModule);
1111 Reader.markIdentifierUpToDate(II);
1112
1113 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1114 if (!IsInteresting) {
1115 // For uninteresting identifiers, there's nothing else to do. Just notify
1116 // the reader that we've finished loading this identifier.
1117 Reader.SetIdentifierInfo(ID, II);
1118 return II;
1119 }
1120
1121 unsigned ObjCOrBuiltinID =
1122 endian::readNext<uint16_t, llvm::endianness::little>(d);
1123 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1124 bool CPlusPlusOperatorKeyword = readBit(Bits);
1125 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1126 bool Poisoned = readBit(Bits);
1127 bool ExtensionToken = readBit(Bits);
1128 bool HadMacroDefinition = readBit(Bits);
1129
1130 assert(Bits == 0 && "Extra bits in the identifier?");
1131 DataLen -= sizeof(uint16_t) * 2;
1132
1133 // Set or check the various bits in the IdentifierInfo structure.
1134 // Token IDs are read-only.
1135 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1137 if (!F.isModule())
1138 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1139 assert(II->isExtensionToken() == ExtensionToken &&
1140 "Incorrect extension token flag");
1141 (void)ExtensionToken;
1142 if (Poisoned)
1143 II->setIsPoisoned(true);
1144 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1145 "Incorrect C++ operator keyword flag");
1146 (void)CPlusPlusOperatorKeyword;
1147
1148 // If this identifier is a macro, deserialize the macro
1149 // definition.
1150 if (HadMacroDefinition) {
1151 uint32_t MacroDirectivesOffset =
1152 endian::readNext<uint32_t, llvm::endianness::little>(d);
1153 DataLen -= 4;
1154
1155 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1156 }
1157
1158 Reader.SetIdentifierInfo(ID, II);
1159
1160 // Read all of the declarations visible at global scope with this
1161 // name.
1162 if (DataLen > 0) {
1164 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1165 DeclIDs.push_back(Reader.getGlobalDeclID(
1167 Reader, F,
1168 endian::readNext<DeclID, llvm::endianness::little>(d))));
1169 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1170 }
1171
1172 return II;
1173}
1174
1176 : Kind(Name.getNameKind()) {
1177 switch (Kind) {
1179 Data = (uint64_t)Name.getAsIdentifierInfo();
1180 break;
1184 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1185 break;
1187 Data = Name.getCXXOverloadedOperator();
1188 break;
1190 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1191 break;
1193 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1194 ->getDeclName().getAsIdentifierInfo();
1195 break;
1200 Data = 0;
1201 break;
1202 }
1203}
1204
1206 llvm::FoldingSetNodeID ID;
1207 ID.AddInteger(Kind);
1208
1209 switch (Kind) {
1213 ID.AddString(((IdentifierInfo*)Data)->getName());
1214 break;
1218 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1219 break;
1221 ID.AddInteger((OverloadedOperatorKind)Data);
1222 break;
1227 break;
1228 }
1229
1230 return ID.computeStableHash();
1231}
1232
1233ModuleFile *
1234ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1235 using namespace llvm::support;
1236
1237 uint32_t ModuleFileID =
1238 endian::readNext<uint32_t, llvm::endianness::little>(d);
1239 return Reader.getLocalModuleFile(F, ModuleFileID);
1240}
1241
1242std::pair<unsigned, unsigned>
1243ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1244 return readULEBKeyDataLength(d);
1245}
1246
1248ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1249 using namespace llvm::support;
1250
1251 auto Kind = (DeclarationName::NameKind)*d++;
1252 uint64_t Data;
1253 switch (Kind) {
1257 Data = (uint64_t)Reader.getLocalIdentifier(
1258 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1259 break;
1263 Data = (uint64_t)Reader
1264 .getLocalSelector(
1265 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1266 .getAsOpaquePtr();
1267 break;
1269 Data = *d++; // OverloadedOperatorKind
1270 break;
1275 Data = 0;
1276 break;
1277 }
1278
1279 return DeclarationNameKey(Kind, Data);
1280}
1281
1282void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1283 const unsigned char *d,
1284 unsigned DataLen,
1285 data_type_builder &Val) {
1286 using namespace llvm::support;
1287
1288 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1290 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1291 Val.insert(Reader.getGlobalDeclID(F, ID));
1292 }
1293}
1294
1295bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1296 BitstreamCursor &Cursor,
1297 uint64_t Offset,
1298 DeclContext *DC) {
1299 assert(Offset != 0);
1300
1301 SavedStreamPosition SavedPosition(Cursor);
1302 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1303 Error(std::move(Err));
1304 return true;
1305 }
1306
1307 RecordData Record;
1308 StringRef Blob;
1309 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1310 if (!MaybeCode) {
1311 Error(MaybeCode.takeError());
1312 return true;
1313 }
1314 unsigned Code = MaybeCode.get();
1315
1316 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1317 if (!MaybeRecCode) {
1318 Error(MaybeRecCode.takeError());
1319 return true;
1320 }
1321 unsigned RecCode = MaybeRecCode.get();
1322 if (RecCode != DECL_CONTEXT_LEXICAL) {
1323 Error("Expected lexical block");
1324 return true;
1325 }
1326
1327 assert(!isa<TranslationUnitDecl>(DC) &&
1328 "expected a TU_UPDATE_LEXICAL record for TU");
1329 // If we are handling a C++ class template instantiation, we can see multiple
1330 // lexical updates for the same record. It's important that we select only one
1331 // of them, so that field numbering works properly. Just pick the first one we
1332 // see.
1333 auto &Lex = LexicalDecls[DC];
1334 if (!Lex.first) {
1335 Lex = std::make_pair(
1336 &M, llvm::ArrayRef(
1337 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1338 Blob.size() / sizeof(DeclID)));
1339 }
1341 return false;
1342}
1343
1344bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1345 BitstreamCursor &Cursor,
1346 uint64_t Offset,
1347 GlobalDeclID ID) {
1348 assert(Offset != 0);
1349
1350 SavedStreamPosition SavedPosition(Cursor);
1351 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1352 Error(std::move(Err));
1353 return true;
1354 }
1355
1356 RecordData Record;
1357 StringRef Blob;
1358 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1359 if (!MaybeCode) {
1360 Error(MaybeCode.takeError());
1361 return true;
1362 }
1363 unsigned Code = MaybeCode.get();
1364
1365 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1366 if (!MaybeRecCode) {
1367 Error(MaybeRecCode.takeError());
1368 return true;
1369 }
1370 unsigned RecCode = MaybeRecCode.get();
1371 if (RecCode != DECL_CONTEXT_VISIBLE) {
1372 Error("Expected visible lookup table block");
1373 return true;
1374 }
1375
1376 // We can't safely determine the primary context yet, so delay attaching the
1377 // lookup table until we're done with recursive deserialization.
1378 auto *Data = (const unsigned char*)Blob.data();
1379 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1380 return false;
1381}
1382
1383void ASTReader::Error(StringRef Msg) const {
1384 Error(diag::err_fe_pch_malformed, Msg);
1385 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1386 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1387 Diag(diag::note_module_cache_path)
1388 << PP.getHeaderSearchInfo().getModuleCachePath();
1389 }
1390}
1391
1392void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1393 StringRef Arg3) const {
1394 if (Diags.isDiagnosticInFlight())
1395 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1396 else
1397 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1398}
1399
1400void ASTReader::Error(llvm::Error &&Err) const {
1401 llvm::Error RemainingErr =
1402 handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1403 auto Diag = E.getDiagnostic().second;
1404
1405 // Ideally we'd just emit it, but have to handle a possible in-flight
1406 // diagnostic. Note that the location is currently ignored as well.
1407 auto NumArgs = Diag.getStorage()->NumDiagArgs;
1408 assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1409 StringRef Arg1, Arg2, Arg3;
1410 switch (NumArgs) {
1411 case 3:
1412 Arg3 = Diag.getStringArg(2);
1413 [[fallthrough]];
1414 case 2:
1415 Arg2 = Diag.getStringArg(1);
1416 [[fallthrough]];
1417 case 1:
1418 Arg1 = Diag.getStringArg(0);
1419 }
1420 Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1421 });
1422 if (RemainingErr)
1423 Error(toString(std::move(RemainingErr)));
1424}
1425
1426//===----------------------------------------------------------------------===//
1427// Source Manager Deserialization
1428//===----------------------------------------------------------------------===//
1429
1430/// Read the line table in the source manager block.
1431void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1432 unsigned Idx = 0;
1433 LineTableInfo &LineTable = SourceMgr.getLineTable();
1434
1435 // Parse the file names
1436 std::map<int, int> FileIDs;
1437 FileIDs[-1] = -1; // For unspecified filenames.
1438 for (unsigned I = 0; Record[Idx]; ++I) {
1439 // Extract the file name
1440 auto Filename = ReadPath(F, Record, Idx);
1441 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1442 }
1443 ++Idx;
1444
1445 // Parse the line entries
1446 std::vector<LineEntry> Entries;
1447 while (Idx < Record.size()) {
1448 FileID FID = ReadFileID(F, Record, Idx);
1449
1450 // Extract the line entries
1451 unsigned NumEntries = Record[Idx++];
1452 assert(NumEntries && "no line entries for file ID");
1453 Entries.clear();
1454 Entries.reserve(NumEntries);
1455 for (unsigned I = 0; I != NumEntries; ++I) {
1456 unsigned FileOffset = Record[Idx++];
1457 unsigned LineNo = Record[Idx++];
1458 int FilenameID = FileIDs[Record[Idx++]];
1461 unsigned IncludeOffset = Record[Idx++];
1462 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1463 FileKind, IncludeOffset));
1464 }
1465 LineTable.AddEntry(FID, Entries);
1466 }
1467}
1468
1469/// Read a source manager block
1470llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1471 using namespace SrcMgr;
1472
1473 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1474
1475 // Set the source-location entry cursor to the current position in
1476 // the stream. This cursor will be used to read the contents of the
1477 // source manager block initially, and then lazily read
1478 // source-location entries as needed.
1479 SLocEntryCursor = F.Stream;
1480
1481 // The stream itself is going to skip over the source manager block.
1482 if (llvm::Error Err = F.Stream.SkipBlock())
1483 return Err;
1484
1485 // Enter the source manager block.
1486 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1487 return Err;
1488 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1489
1490 RecordData Record;
1491 while (true) {
1493 SLocEntryCursor.advanceSkippingSubblocks();
1494 if (!MaybeE)
1495 return MaybeE.takeError();
1496 llvm::BitstreamEntry E = MaybeE.get();
1497
1498 switch (E.Kind) {
1499 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1500 case llvm::BitstreamEntry::Error:
1501 return llvm::createStringError(std::errc::illegal_byte_sequence,
1502 "malformed block record in AST file");
1503 case llvm::BitstreamEntry::EndBlock:
1504 return llvm::Error::success();
1505 case llvm::BitstreamEntry::Record:
1506 // The interesting case.
1507 break;
1508 }
1509
1510 // Read a record.
1511 Record.clear();
1512 StringRef Blob;
1513 Expected<unsigned> MaybeRecord =
1514 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1515 if (!MaybeRecord)
1516 return MaybeRecord.takeError();
1517 switch (MaybeRecord.get()) {
1518 default: // Default behavior: ignore.
1519 break;
1520
1521 case SM_SLOC_FILE_ENTRY:
1524 // Once we hit one of the source location entries, we're done.
1525 return llvm::Error::success();
1526 }
1527 }
1528}
1529
1532 BitstreamCursor &Cursor = F->SLocEntryCursor;
1533 SavedStreamPosition SavedPosition(Cursor);
1534 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1535 F->SLocEntryOffsets[Index]))
1536 return std::move(Err);
1537
1538 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1539 if (!MaybeEntry)
1540 return MaybeEntry.takeError();
1541
1542 llvm::BitstreamEntry Entry = MaybeEntry.get();
1543 if (Entry.Kind != llvm::BitstreamEntry::Record)
1544 return llvm::createStringError(
1545 std::errc::illegal_byte_sequence,
1546 "incorrectly-formatted source location entry in AST file");
1547
1549 StringRef Blob;
1550 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1551 if (!MaybeSLOC)
1552 return MaybeSLOC.takeError();
1553
1554 switch (MaybeSLOC.get()) {
1555 default:
1556 return llvm::createStringError(
1557 std::errc::illegal_byte_sequence,
1558 "incorrectly-formatted source location entry in AST file");
1559 case SM_SLOC_FILE_ENTRY:
1562 return F->SLocEntryBaseOffset + Record[0];
1563 }
1564}
1565
1567 auto SLocMapI =
1568 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1569 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1570 "Corrupted global sloc offset map");
1571 ModuleFile *F = SLocMapI->second;
1572
1573 bool Invalid = false;
1574
1575 auto It = llvm::upper_bound(
1576 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1577 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1578 int ID = F->SLocEntryBaseID + LocalIndex;
1579 std::size_t Index = -ID - 2;
1580 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1581 assert(!SourceMgr.SLocEntryLoaded[Index]);
1582 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1583 if (!MaybeEntryOffset) {
1584 Error(MaybeEntryOffset.takeError());
1585 Invalid = true;
1586 return true;
1587 }
1588 SourceMgr.LoadedSLocEntryTable[Index] =
1589 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1590 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1591 }
1592 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1593 });
1594
1595 if (Invalid)
1596 return 0;
1597
1598 // The iterator points to the first entry with start offset greater than the
1599 // offset of interest. The previous entry must contain the offset of interest.
1600 return F->SLocEntryBaseID + *std::prev(It);
1601}
1602
1604 if (ID == 0)
1605 return false;
1606
1607 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1608 Error("source location entry ID out-of-range for AST file");
1609 return true;
1610 }
1611
1612 // Local helper to read the (possibly-compressed) buffer data following the
1613 // entry record.
1614 auto ReadBuffer = [this](
1615 BitstreamCursor &SLocEntryCursor,
1616 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1618 StringRef Blob;
1619 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1620 if (!MaybeCode) {
1621 Error(MaybeCode.takeError());
1622 return nullptr;
1623 }
1624 unsigned Code = MaybeCode.get();
1625
1626 Expected<unsigned> MaybeRecCode =
1627 SLocEntryCursor.readRecord(Code, Record, &Blob);
1628 if (!MaybeRecCode) {
1629 Error(MaybeRecCode.takeError());
1630 return nullptr;
1631 }
1632 unsigned RecCode = MaybeRecCode.get();
1633
1634 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1635 // Inspect the first byte to differentiate zlib (\x78) and zstd
1636 // (little-endian 0xFD2FB528).
1637 const llvm::compression::Format F =
1638 Blob.size() > 0 && Blob.data()[0] == 0x78
1639 ? llvm::compression::Format::Zlib
1640 : llvm::compression::Format::Zstd;
1641 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1642 Error(Reason);
1643 return nullptr;
1644 }
1645 SmallVector<uint8_t, 0> Decompressed;
1646 if (llvm::Error E = llvm::compression::decompress(
1647 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1648 Error("could not decompress embedded file contents: " +
1649 llvm::toString(std::move(E)));
1650 return nullptr;
1651 }
1652 return llvm::MemoryBuffer::getMemBufferCopy(
1653 llvm::toStringRef(Decompressed), Name);
1654 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1655 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1656 } else {
1657 Error("AST record has invalid code");
1658 return nullptr;
1659 }
1660 };
1661
1662 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1663 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1665 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1666 Error(std::move(Err));
1667 return true;
1668 }
1669
1670 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1672
1673 ++NumSLocEntriesRead;
1674 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1675 if (!MaybeEntry) {
1676 Error(MaybeEntry.takeError());
1677 return true;
1678 }
1679 llvm::BitstreamEntry Entry = MaybeEntry.get();
1680
1681 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1682 Error("incorrectly-formatted source location entry in AST file");
1683 return true;
1684 }
1685
1687 StringRef Blob;
1688 Expected<unsigned> MaybeSLOC =
1689 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1690 if (!MaybeSLOC) {
1691 Error(MaybeSLOC.takeError());
1692 return true;
1693 }
1694 switch (MaybeSLOC.get()) {
1695 default:
1696 Error("incorrectly-formatted source location entry in AST file");
1697 return true;
1698
1699 case SM_SLOC_FILE_ENTRY: {
1700 // We will detect whether a file changed and return 'Failure' for it, but
1701 // we will also try to fail gracefully by setting up the SLocEntry.
1702 unsigned InputID = Record[4];
1703 InputFile IF = getInputFile(*F, InputID);
1705 bool OverriddenBuffer = IF.isOverridden();
1706
1707 // Note that we only check if a File was returned. If it was out-of-date
1708 // we have complained but we will continue creating a FileID to recover
1709 // gracefully.
1710 if (!File)
1711 return true;
1712
1713 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1714 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1715 // This is the module's main file.
1716 IncludeLoc = getImportLocation(F);
1717 }
1719 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1720 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1721 BaseOffset + Record[0]);
1722 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1723 FileInfo.NumCreatedFIDs = Record[5];
1724 if (Record[3])
1725 FileInfo.setHasLineDirectives();
1726
1727 unsigned NumFileDecls = Record[7];
1728 if (NumFileDecls && ContextObj) {
1729 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
1730 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1731 FileDeclIDs[FID] =
1732 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1733 }
1734
1735 const SrcMgr::ContentCache &ContentCache =
1736 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1737 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1738 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1739 !ContentCache.getBufferIfLoaded()) {
1740 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1741 if (!Buffer)
1742 return true;
1743 SourceMgr.overrideFileContents(*File, std::move(Buffer));
1744 }
1745
1746 break;
1747 }
1748
1749 case SM_SLOC_BUFFER_ENTRY: {
1750 const char *Name = Blob.data();
1751 unsigned Offset = Record[0];
1753 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1754 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1755 if (IncludeLoc.isInvalid() && F->isModule()) {
1756 IncludeLoc = getImportLocation(F);
1757 }
1758
1759 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1760 if (!Buffer)
1761 return true;
1762 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1763 BaseOffset + Offset, IncludeLoc);
1764 if (Record[3]) {
1765 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1766 FileInfo.setHasLineDirectives();
1767 }
1768 break;
1769 }
1770
1773 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
1774 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
1775 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
1776 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
1777 Record[5], Record[4], ID,
1778 BaseOffset + Record[0]);
1779 break;
1780 }
1781 }
1782
1783 return false;
1784}
1785
1786std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1787 if (ID == 0)
1788 return std::make_pair(SourceLocation(), "");
1789
1790 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1791 Error("source location entry ID out-of-range for AST file");
1792 return std::make_pair(SourceLocation(), "");
1793 }
1794
1795 // Find which module file this entry lands in.
1796 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1797 if (!M->isModule())
1798 return std::make_pair(SourceLocation(), "");
1799
1800 // FIXME: Can we map this down to a particular submodule? That would be
1801 // ideal.
1802 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1803}
1804
1805/// Find the location where the module F is imported.
1806SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1807 if (F->ImportLoc.isValid())
1808 return F->ImportLoc;
1809
1810 // Otherwise we have a PCH. It's considered to be "imported" at the first
1811 // location of its includer.
1812 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1813 // Main file is the importer.
1814 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1815 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1816 }
1817 return F->ImportedBy[0]->FirstLoc;
1818}
1819
1820/// Enter a subblock of the specified BlockID with the specified cursor. Read
1821/// the abbreviations that are at the top of the block and then leave the cursor
1822/// pointing into the block.
1823llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1824 unsigned BlockID,
1825 uint64_t *StartOfBlockOffset) {
1826 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1827 return Err;
1828
1829 if (StartOfBlockOffset)
1830 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1831
1832 while (true) {
1833 uint64_t Offset = Cursor.GetCurrentBitNo();
1834 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1835 if (!MaybeCode)
1836 return MaybeCode.takeError();
1837 unsigned Code = MaybeCode.get();
1838
1839 // We expect all abbrevs to be at the start of the block.
1840 if (Code != llvm::bitc::DEFINE_ABBREV) {
1841 if (llvm::Error Err = Cursor.JumpToBit(Offset))
1842 return Err;
1843 return llvm::Error::success();
1844 }
1845 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1846 return Err;
1847 }
1848}
1849
1851 unsigned &Idx) {
1852 Token Tok;
1853 Tok.startToken();
1854 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
1855 Tok.setKind((tok::TokenKind)Record[Idx++]);
1856 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1857
1858 if (Tok.isAnnotation()) {
1859 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
1860 switch (Tok.getKind()) {
1861 case tok::annot_pragma_loop_hint: {
1862 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
1863 Info->PragmaName = ReadToken(M, Record, Idx);
1864 Info->Option = ReadToken(M, Record, Idx);
1865 unsigned NumTokens = Record[Idx++];
1867 Toks.reserve(NumTokens);
1868 for (unsigned I = 0; I < NumTokens; ++I)
1869 Toks.push_back(ReadToken(M, Record, Idx));
1870 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
1871 Tok.setAnnotationValue(static_cast<void *>(Info));
1872 break;
1873 }
1874 case tok::annot_pragma_pack: {
1875 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
1876 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
1877 auto SlotLabel = ReadString(Record, Idx);
1878 Info->SlotLabel =
1879 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
1880 Info->Alignment = ReadToken(M, Record, Idx);
1881 Tok.setAnnotationValue(static_cast<void *>(Info));
1882 break;
1883 }
1884 // Some annotation tokens do not use the PtrData field.
1885 case tok::annot_pragma_openmp:
1886 case tok::annot_pragma_openmp_end:
1887 case tok::annot_pragma_unused:
1888 case tok::annot_pragma_openacc:
1889 case tok::annot_pragma_openacc_end:
1890 case tok::annot_repl_input_end:
1891 break;
1892 default:
1893 llvm_unreachable("missing deserialization code for annotation token");
1894 }
1895 } else {
1896 Tok.setLength(Record[Idx++]);
1897 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
1898 Tok.setIdentifierInfo(II);
1899 }
1900 return Tok;
1901}
1902
1904 BitstreamCursor &Stream = F.MacroCursor;
1905
1906 // Keep track of where we are in the stream, then jump back there
1907 // after reading this macro.
1908 SavedStreamPosition SavedPosition(Stream);
1909
1910 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1911 // FIXME this drops errors on the floor.
1912 consumeError(std::move(Err));
1913 return nullptr;
1914 }
1917 MacroInfo *Macro = nullptr;
1918 llvm::MutableArrayRef<Token> MacroTokens;
1919
1920 while (true) {
1921 // Advance to the next record, but if we get to the end of the block, don't
1922 // pop it (removing all the abbreviations from the cursor) since we want to
1923 // be able to reseek within the block and read entries.
1924 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1926 Stream.advanceSkippingSubblocks(Flags);
1927 if (!MaybeEntry) {
1928 Error(MaybeEntry.takeError());
1929 return Macro;
1930 }
1931 llvm::BitstreamEntry Entry = MaybeEntry.get();
1932
1933 switch (Entry.Kind) {
1934 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1935 case llvm::BitstreamEntry::Error:
1936 Error("malformed block record in AST file");
1937 return Macro;
1938 case llvm::BitstreamEntry::EndBlock:
1939 return Macro;
1940 case llvm::BitstreamEntry::Record:
1941 // The interesting case.
1942 break;
1943 }
1944
1945 // Read a record.
1946 Record.clear();
1948 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1949 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1950 else {
1951 Error(MaybeRecType.takeError());
1952 return Macro;
1953 }
1954 switch (RecType) {
1955 case PP_MODULE_MACRO:
1957 return Macro;
1958
1961 // If we already have a macro, that means that we've hit the end
1962 // of the definition of the macro we were looking for. We're
1963 // done.
1964 if (Macro)
1965 return Macro;
1966
1967 unsigned NextIndex = 1; // Skip identifier ID.
1968 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1969 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1970 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1971 MI->setIsUsed(Record[NextIndex++]);
1972 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1973 MacroTokens = MI->allocateTokens(Record[NextIndex++],
1974 PP.getPreprocessorAllocator());
1975 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1976 // Decode function-like macro info.
1977 bool isC99VarArgs = Record[NextIndex++];
1978 bool isGNUVarArgs = Record[NextIndex++];
1979 bool hasCommaPasting = Record[NextIndex++];
1980 MacroParams.clear();
1981 unsigned NumArgs = Record[NextIndex++];
1982 for (unsigned i = 0; i != NumArgs; ++i)
1983 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1984
1985 // Install function-like macro info.
1986 MI->setIsFunctionLike();
1987 if (isC99VarArgs) MI->setIsC99Varargs();
1988 if (isGNUVarArgs) MI->setIsGNUVarargs();
1989 if (hasCommaPasting) MI->setHasCommaPasting();
1990 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1991 }
1992
1993 // Remember that we saw this macro last so that we add the tokens that
1994 // form its body to it.
1995 Macro = MI;
1996
1997 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1998 Record[NextIndex]) {
1999 // We have a macro definition. Register the association
2001 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
2002 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2003 PreprocessingRecord::PPEntityID PPID =
2004 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
2005 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2006 PPRec.getPreprocessedEntity(PPID));
2007 if (PPDef)
2008 PPRec.RegisterMacroDefinition(Macro, PPDef);
2009 }
2010
2011 ++NumMacrosRead;
2012 break;
2013 }
2014
2015 case PP_TOKEN: {
2016 // If we see a TOKEN before a PP_MACRO_*, then the file is
2017 // erroneous, just pretend we didn't see this.
2018 if (!Macro) break;
2019 if (MacroTokens.empty()) {
2020 Error("unexpected number of macro tokens for a macro in AST file");
2021 return Macro;
2022 }
2023
2024 unsigned Idx = 0;
2025 MacroTokens[0] = ReadToken(F, Record, Idx);
2026 MacroTokens = MacroTokens.drop_front();
2027 break;
2028 }
2029 }
2030 }
2031}
2032
2035 unsigned LocalID) const {
2036 if (!M.ModuleOffsetMap.empty())
2037 ReadModuleOffsetMap(M);
2038
2041 assert(I != M.PreprocessedEntityRemap.end()
2042 && "Invalid index into preprocessed entity index remap");
2043
2044 return LocalID + I->second;
2045}
2046
2047const FileEntry *HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2048 FileManager &FileMgr = Reader.getFileManager();
2049 if (!Key.Imported) {
2050 if (auto File = FileMgr.getFile(Key.Filename))
2051 return *File;
2052 return nullptr;
2053 }
2054
2055 std::string Resolved = std::string(Key.Filename);
2056 Reader.ResolveImportedPath(M, Resolved);
2057 if (auto File = FileMgr.getFile(Resolved))
2058 return *File;
2059 return nullptr;
2060}
2061
2062unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
2063 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2064 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2065 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2066 return llvm::xxh3_64bits(buf);
2067}
2068
2070HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) {
2071 internal_key_type ikey = {ekey.getSize(),
2072 M.HasTimestamps ? ekey.getModificationTime() : 0,
2073 ekey.getName(), /*Imported*/ false};
2074 return ikey;
2075}
2076
2077bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
2078 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2079 return false;
2080
2081 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2082 return true;
2083
2084 // Determine whether the actual files are equivalent.
2085 const FileEntry *FEA = getFile(a);
2086 const FileEntry *FEB = getFile(b);
2087 return FEA && FEA == FEB;
2088}
2089
2090std::pair<unsigned, unsigned>
2091HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
2092 return readULEBKeyDataLength(d);
2093}
2094
2096HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2097 using namespace llvm::support;
2098
2099 internal_key_type ikey;
2100 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2101 ikey.ModTime =
2102 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2103 ikey.Filename = (const char *)d;
2104 ikey.Imported = true;
2105 return ikey;
2106}
2107
2109HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
2110 unsigned DataLen) {
2111 using namespace llvm::support;
2112
2113 const unsigned char *End = d + DataLen;
2114 HeaderFileInfo HFI;
2115 unsigned Flags = *d++;
2116
2117 bool Included = (Flags >> 6) & 0x01;
2118 if (Included)
2119 if (const FileEntry *FE = getFile(key))
2120 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2121 // deserialize this header file info again.
2122 Reader.getPreprocessor().getIncludedFiles().insert(FE);
2123
2124 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2125 HFI.isImport |= (Flags >> 5) & 0x01;
2126 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2127 HFI.DirInfo = (Flags >> 1) & 0x07;
2128 HFI.IndexHeaderMapHeader = Flags & 0x01;
2129 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2130 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2131 if (unsigned FrameworkOffset =
2132 endian::readNext<uint32_t, llvm::endianness::little>(d)) {
2133 // The framework offset is 1 greater than the actual offset,
2134 // since 0 is used as an indicator for "no framework name".
2135 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
2136 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
2137 }
2138
2139 assert((End - d) % 4 == 0 &&
2140 "Wrong data length in HeaderFileInfo deserialization");
2141 while (d != End) {
2142 uint32_t LocalSMID =
2143 endian::readNext<uint32_t, llvm::endianness::little>(d);
2144 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2145 LocalSMID >>= 3;
2146
2147 // This header is part of a module. Associate it with the module to enable
2148 // implicit module import.
2149 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2150 Module *Mod = Reader.getSubmodule(GlobalSMID);
2151 FileManager &FileMgr = Reader.getFileManager();
2152 ModuleMap &ModMap =
2153 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2154
2155 std::string Filename = std::string(key.Filename);
2156 if (key.Imported)
2157 Reader.ResolveImportedPath(M, Filename);
2158 if (auto FE = FileMgr.getOptionalFileRef(Filename)) {
2159 // FIXME: NameAsWritten
2160 Module::Header H = {std::string(key.Filename), "", *FE};
2161 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2162 }
2163 HFI.mergeModuleMembership(HeaderRole);
2164 }
2165
2166 // This HeaderFileInfo was externally loaded.
2167 HFI.External = true;
2168 HFI.IsValid = true;
2169 return HFI;
2170}
2171
2173 uint32_t MacroDirectivesOffset) {
2174 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2175 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2176}
2177
2179 // Note that we are loading defined macros.
2180 Deserializing Macros(this);
2181
2182 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2183 BitstreamCursor &MacroCursor = I.MacroCursor;
2184
2185 // If there was no preprocessor block, skip this file.
2186 if (MacroCursor.getBitcodeBytes().empty())
2187 continue;
2188
2189 BitstreamCursor Cursor = MacroCursor;
2190 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2191 Error(std::move(Err));
2192 return;
2193 }
2194
2196 while (true) {
2197 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2198 if (!MaybeE) {
2199 Error(MaybeE.takeError());
2200 return;
2201 }
2202 llvm::BitstreamEntry E = MaybeE.get();
2203
2204 switch (E.Kind) {
2205 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2206 case llvm::BitstreamEntry::Error:
2207 Error("malformed block record in AST file");
2208 return;
2209 case llvm::BitstreamEntry::EndBlock:
2210 goto NextCursor;
2211
2212 case llvm::BitstreamEntry::Record: {
2213 Record.clear();
2214 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2215 if (!MaybeRecord) {
2216 Error(MaybeRecord.takeError());
2217 return;
2218 }
2219 switch (MaybeRecord.get()) {
2220 default: // Default behavior: ignore.
2221 break;
2222
2225 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
2226 if (II->isOutOfDate())
2227 updateOutOfDateIdentifier(*II);
2228 break;
2229 }
2230
2231 case PP_TOKEN:
2232 // Ignore tokens.
2233 break;
2234 }
2235 break;
2236 }
2237 }
2238 }
2239 NextCursor: ;
2240 }
2241}
2242
2243namespace {
2244
2245 /// Visitor class used to look up identifirs in an AST file.
2246 class IdentifierLookupVisitor {
2247 StringRef Name;
2248 unsigned NameHash;
2249 unsigned PriorGeneration;
2250 unsigned &NumIdentifierLookups;
2251 unsigned &NumIdentifierLookupHits;
2252 IdentifierInfo *Found = nullptr;
2253
2254 public:
2255 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2256 unsigned &NumIdentifierLookups,
2257 unsigned &NumIdentifierLookupHits)
2258 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2259 PriorGeneration(PriorGeneration),
2260 NumIdentifierLookups(NumIdentifierLookups),
2261 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2262
2263 bool operator()(ModuleFile &M) {
2264 // If we've already searched this module file, skip it now.
2265 if (M.Generation <= PriorGeneration)
2266 return true;
2267
2270 if (!IdTable)
2271 return false;
2272
2273 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2274 Found);
2275 ++NumIdentifierLookups;
2276 ASTIdentifierLookupTable::iterator Pos =
2277 IdTable->find_hashed(Name, NameHash, &Trait);
2278 if (Pos == IdTable->end())
2279 return false;
2280
2281 // Dereferencing the iterator has the effect of building the
2282 // IdentifierInfo node and populating it with the various
2283 // declarations it needs.
2284 ++NumIdentifierLookupHits;
2285 Found = *Pos;
2286 return true;
2287 }
2288
2289 // Retrieve the identifier info found within the module
2290 // files.
2291 IdentifierInfo *getIdentifierInfo() const { return Found; }
2292 };
2293
2294} // namespace
2295
2297 // Note that we are loading an identifier.
2298 Deserializing AnIdentifier(this);
2299
2300 unsigned PriorGeneration = 0;
2301 if (getContext().getLangOpts().Modules)
2302 PriorGeneration = IdentifierGeneration[&II];
2303
2304 // If there is a global index, look there first to determine which modules
2305 // provably do not have any results for this identifier.
2307 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2308 if (!loadGlobalIndex()) {
2309 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2310 HitsPtr = &Hits;
2311 }
2312 }
2313
2314 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2315 NumIdentifierLookups,
2316 NumIdentifierLookupHits);
2317 ModuleMgr.visit(Visitor, HitsPtr);
2318 markIdentifierUpToDate(&II);
2319}
2320
2322 if (!II)
2323 return;
2324
2325 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2326
2327 // Update the generation for this identifier.
2328 if (getContext().getLangOpts().Modules)
2329 IdentifierGeneration[II] = getGeneration();
2330}
2331
2333 const PendingMacroInfo &PMInfo) {
2334 ModuleFile &M = *PMInfo.M;
2335
2336 BitstreamCursor &Cursor = M.MacroCursor;
2337 SavedStreamPosition SavedPosition(Cursor);
2338 if (llvm::Error Err =
2339 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2340 Error(std::move(Err));
2341 return;
2342 }
2343
2344 struct ModuleMacroRecord {
2345 SubmoduleID SubModID;
2346 MacroInfo *MI;
2348 };
2350
2351 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2352 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2353 // macro histroy.
2355 while (true) {
2357 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2358 if (!MaybeEntry) {
2359 Error(MaybeEntry.takeError());
2360 return;
2361 }
2362 llvm::BitstreamEntry Entry = MaybeEntry.get();
2363
2364 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2365 Error("malformed block record in AST file");
2366 return;
2367 }
2368
2369 Record.clear();
2370 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2371 if (!MaybePP) {
2372 Error(MaybePP.takeError());
2373 return;
2374 }
2375 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2377 break;
2378
2379 case PP_MODULE_MACRO: {
2380 ModuleMacros.push_back(ModuleMacroRecord());
2381 auto &Info = ModuleMacros.back();
2382 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2383 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2384 for (int I = 2, N = Record.size(); I != N; ++I)
2385 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2386 continue;
2387 }
2388
2389 default:
2390 Error("malformed block record in AST file");
2391 return;
2392 }
2393
2394 // We found the macro directive history; that's the last record
2395 // for this macro.
2396 break;
2397 }
2398
2399 // Module macros are listed in reverse dependency order.
2400 {
2401 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2403 for (auto &MMR : ModuleMacros) {
2404 Overrides.clear();
2405 for (unsigned ModID : MMR.Overrides) {
2406 Module *Mod = getSubmodule(ModID);
2407 auto *Macro = PP.getModuleMacro(Mod, II);
2408 assert(Macro && "missing definition for overridden macro");
2409 Overrides.push_back(Macro);
2410 }
2411
2412 bool Inserted = false;
2413 Module *Owner = getSubmodule(MMR.SubModID);
2414 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2415 }
2416 }
2417
2418 // Don't read the directive history for a module; we don't have anywhere
2419 // to put it.
2420 if (M.isModule())
2421 return;
2422
2423 // Deserialize the macro directives history in reverse source-order.
2424 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2425 unsigned Idx = 0, N = Record.size();
2426 while (Idx < N) {
2427 MacroDirective *MD = nullptr;
2428 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2430 switch (K) {
2432 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2433 MD = PP.AllocateDefMacroDirective(MI, Loc);
2434 break;
2435 }
2437 MD = PP.AllocateUndefMacroDirective(Loc);
2438 break;
2440 bool isPublic = Record[Idx++];
2441 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2442 break;
2443 }
2444
2445 if (!Latest)
2446 Latest = MD;
2447 if (Earliest)
2448 Earliest->setPrevious(MD);
2449 Earliest = MD;
2450 }
2451
2452 if (Latest)
2453 PP.setLoadedMacroDirective(II, Earliest, Latest);
2454}
2455
2456bool ASTReader::shouldDisableValidationForFile(
2457 const serialization::ModuleFile &M) const {
2458 if (DisableValidationKind == DisableValidationForModuleKind::None)
2459 return false;
2460
2461 // If a PCH is loaded and validation is disabled for PCH then disable
2462 // validation for the PCH and the modules it loads.
2463 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2464
2465 switch (K) {
2466 case MK_MainFile:
2467 case MK_Preamble:
2468 case MK_PCH:
2469 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2470 case MK_ImplicitModule:
2471 case MK_ExplicitModule:
2472 case MK_PrebuiltModule:
2473 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2474 }
2475
2476 return false;
2477}
2478
2479InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2480 // If this ID is bogus, just return an empty input file.
2481 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2482 return InputFileInfo();
2483
2484 // If we've already loaded this input file, return it.
2485 if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
2486 return F.InputFileInfosLoaded[ID - 1];
2487
2488 // Go find this input file.
2489 BitstreamCursor &Cursor = F.InputFilesCursor;
2490 SavedStreamPosition SavedPosition(Cursor);
2491 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2492 F.InputFileOffsets[ID - 1])) {
2493 // FIXME this drops errors on the floor.
2494 consumeError(std::move(Err));
2495 }
2496
2497 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2498 if (!MaybeCode) {
2499 // FIXME this drops errors on the floor.
2500 consumeError(MaybeCode.takeError());
2501 }
2502 unsigned Code = MaybeCode.get();
2503 RecordData Record;
2504 StringRef Blob;
2505
2506 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2507 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2508 "invalid record type for input file");
2509 else {
2510 // FIXME this drops errors on the floor.
2511 consumeError(Maybe.takeError());
2512 }
2513
2514 assert(Record[0] == ID && "Bogus stored ID or offset");
2515 InputFileInfo R;
2516 R.StoredSize = static_cast<off_t>(Record[1]);
2517 R.StoredTime = static_cast<time_t>(Record[2]);
2518 R.Overridden = static_cast<bool>(Record[3]);
2519 R.Transient = static_cast<bool>(Record[4]);
2520 R.TopLevel = static_cast<bool>(Record[5]);
2521 R.ModuleMap = static_cast<bool>(Record[6]);
2522 std::tie(R.FilenameAsRequested, R.Filename) = [&]() {
2523 uint16_t AsRequestedLength = Record[7];
2524
2525 std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();
2526 std::string Name = Blob.substr(AsRequestedLength).str();
2527
2528 ResolveImportedPath(F, NameAsRequested);
2529 ResolveImportedPath(F, Name);
2530
2531 if (Name.empty())
2532 Name = NameAsRequested;
2533
2534 return std::make_pair(std::move(NameAsRequested), std::move(Name));
2535 }();
2536
2537 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2538 if (!MaybeEntry) // FIXME this drops errors on the floor.
2539 consumeError(MaybeEntry.takeError());
2540 llvm::BitstreamEntry Entry = MaybeEntry.get();
2541 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2542 "expected record type for input file hash");
2543
2544 Record.clear();
2545 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2546 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2547 "invalid record type for input file hash");
2548 else {
2549 // FIXME this drops errors on the floor.
2550 consumeError(Maybe.takeError());
2551 }
2552 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2553 static_cast<uint64_t>(Record[0]);
2554
2555 // Note that we've loaded this input file info.
2556 F.InputFileInfosLoaded[ID - 1] = R;
2557 return R;
2558}
2559
2560static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2561InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2562 // If this ID is bogus, just return an empty input file.
2563 if (ID == 0 || ID > F.InputFilesLoaded.size())
2564 return InputFile();
2565
2566 // If we've already loaded this input file, return it.
2567 if (F.InputFilesLoaded[ID-1].getFile())
2568 return F.InputFilesLoaded[ID-1];
2569
2570 if (F.InputFilesLoaded[ID-1].isNotFound())
2571 return InputFile();
2572
2573 // Go find this input file.
2574 BitstreamCursor &Cursor = F.InputFilesCursor;
2575 SavedStreamPosition SavedPosition(Cursor);
2576 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2577 F.InputFileOffsets[ID - 1])) {
2578 // FIXME this drops errors on the floor.
2579 consumeError(std::move(Err));
2580 }
2581
2582 InputFileInfo FI = getInputFileInfo(F, ID);
2583 off_t StoredSize = FI.StoredSize;
2584 time_t StoredTime = FI.StoredTime;
2585 bool Overridden = FI.Overridden;
2586 bool Transient = FI.Transient;
2587 StringRef Filename = FI.FilenameAsRequested;
2588 uint64_t StoredContentHash = FI.ContentHash;
2589
2590 // For standard C++ modules, we don't need to check the inputs.
2591 bool SkipChecks = F.StandardCXXModule;
2592
2593 const HeaderSearchOptions &HSOpts =
2594 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2595
2596 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2597 // modules.
2599 SkipChecks = false;
2600 Overridden = false;
2601 }
2602
2603 auto File = FileMgr.getOptionalFileRef(Filename, /*OpenFile=*/false);
2604
2605 // For an overridden file, create a virtual file with the stored
2606 // size/timestamp.
2607 if ((Overridden || Transient || SkipChecks) && !File)
2608 File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
2609
2610 if (!File) {
2611 if (Complain) {
2612 std::string ErrorStr = "could not find file '";
2613 ErrorStr += Filename;
2614 ErrorStr += "' referenced by AST file '";
2615 ErrorStr += F.FileName;
2616 ErrorStr += "'";
2617 Error(ErrorStr);
2618 }
2619 // Record that we didn't find the file.
2621 return InputFile();
2622 }
2623
2624 // Check if there was a request to override the contents of the file
2625 // that was part of the precompiled header. Overriding such a file
2626 // can lead to problems when lexing using the source locations from the
2627 // PCH.
2628 SourceManager &SM = getSourceManager();
2629 // FIXME: Reject if the overrides are different.
2630 if ((!Overridden && !Transient) && !SkipChecks &&
2631 SM.isFileOverridden(*File)) {
2632 if (Complain)
2633 Error(diag::err_fe_pch_file_overridden, Filename);
2634
2635 // After emitting the diagnostic, bypass the overriding file to recover
2636 // (this creates a separate FileEntry).
2637 File = SM.bypassFileContentsOverride(*File);
2638 if (!File) {
2640 return InputFile();
2641 }
2642 }
2643
2644 struct Change {
2645 enum ModificationKind {
2646 Size,
2647 ModTime,
2648 Content,
2649 None,
2650 } Kind;
2651 std::optional<int64_t> Old = std::nullopt;
2652 std::optional<int64_t> New = std::nullopt;
2653 };
2654 auto HasInputContentChanged = [&](Change OriginalChange) {
2655 assert(ValidateASTInputFilesContent &&
2656 "We should only check the content of the inputs with "
2657 "ValidateASTInputFilesContent enabled.");
2658
2659 if (StoredContentHash == 0)
2660 return OriginalChange;
2661
2662 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2663 if (!MemBuffOrError) {
2664 if (!Complain)
2665 return OriginalChange;
2666 std::string ErrorStr = "could not get buffer for file '";
2667 ErrorStr += File->getName();
2668 ErrorStr += "'";
2669 Error(ErrorStr);
2670 return OriginalChange;
2671 }
2672
2673 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2674 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2675 return Change{Change::None};
2676
2677 return Change{Change::Content};
2678 };
2679 auto HasInputFileChanged = [&]() {
2680 if (StoredSize != File->getSize())
2681 return Change{Change::Size, StoredSize, File->getSize()};
2682 if (!shouldDisableValidationForFile(F) && StoredTime &&
2683 StoredTime != File->getModificationTime()) {
2684 Change MTimeChange = {Change::ModTime, StoredTime,
2685 File->getModificationTime()};
2686
2687 // In case the modification time changes but not the content,
2688 // accept the cached file as legit.
2689 if (ValidateASTInputFilesContent)
2690 return HasInputContentChanged(MTimeChange);
2691
2692 return MTimeChange;
2693 }
2694 return Change{Change::None};
2695 };
2696
2697 bool IsOutOfDate = false;
2698 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2699 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2700 // enabled, it is better to check the contents of the inputs. Since we can't
2701 // get correct modified time information for inputs from overriden inputs.
2702 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2703 F.StandardCXXModule && FileChange.Kind == Change::None)
2704 FileChange = HasInputContentChanged(FileChange);
2705
2706 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2707 // it is better to check the content of the input files because we cannot rely
2708 // on the file modification time, which will be the same (zero) for these
2709 // files.
2710 if (!StoredTime && ValidateASTInputFilesContent &&
2711 FileChange.Kind == Change::None)
2712 FileChange = HasInputContentChanged(FileChange);
2713
2714 // For an overridden file, there is nothing to validate.
2715 if (!Overridden && FileChange.Kind != Change::None) {
2716 if (Complain && !Diags.isDiagnosticInFlight()) {
2717 // Build a list of the PCH imports that got us here (in reverse).
2718 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2719 while (!ImportStack.back()->ImportedBy.empty())
2720 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2721
2722 // The top-level PCH is stale.
2723 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2724 Diag(diag::err_fe_ast_file_modified)
2725 << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2726 << TopLevelPCHName << FileChange.Kind
2727 << (FileChange.Old && FileChange.New)
2728 << llvm::itostr(FileChange.Old.value_or(0))
2729 << llvm::itostr(FileChange.New.value_or(0));
2730
2731 // Print the import stack.
2732 if (ImportStack.size() > 1) {
2733 Diag(diag::note_pch_required_by)
2734 << Filename << ImportStack[0]->FileName;
2735 for (unsigned I = 1; I < ImportStack.size(); ++I)
2736 Diag(diag::note_pch_required_by)
2737 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2738 }
2739
2740 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2741 }
2742
2743 IsOutOfDate = true;
2744 }
2745 // FIXME: If the file is overridden and we've already opened it,
2746 // issue an error (or split it into a separate FileEntry).
2747
2748 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2749
2750 // Note that we've loaded this input file.
2751 F.InputFilesLoaded[ID-1] = IF;
2752 return IF;
2753}
2754
2755/// If we are loading a relocatable PCH or module file, and the filename
2756/// is not an absolute path, add the system or module root to the beginning of
2757/// the file name.
2759 // Resolve relative to the base directory, if we have one.
2760 if (!M.BaseDirectory.empty())
2761 return ResolveImportedPath(Filename, M.BaseDirectory);
2762}
2763
2764void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2765 if (Filename.empty() || llvm::sys::path::is_absolute(Filename) ||
2766 Filename == "<built-in>" || Filename == "<command line>")
2767 return;
2768
2769 SmallString<128> Buffer;
2770 llvm::sys::path::append(Buffer, Prefix, Filename);
2771 Filename.assign(Buffer.begin(), Buffer.end());
2772}
2773
2774static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2775 switch (ARR) {
2776 case ASTReader::Failure: return true;
2777 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2778 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2781 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2782 case ASTReader::HadErrors: return true;
2783 case ASTReader::Success: return false;
2784 }
2785
2786 llvm_unreachable("unknown ASTReadResult");
2787}
2788
2789ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2790 BitstreamCursor &Stream, StringRef Filename,
2791 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
2792 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
2793 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2794 // FIXME this drops errors on the floor.
2795 consumeError(std::move(Err));
2796 return Failure;
2797 }
2798
2799 // Read all of the records in the options block.
2800 RecordData Record;
2801 ASTReadResult Result = Success;
2802 while (true) {
2803 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2804 if (!MaybeEntry) {
2805 // FIXME this drops errors on the floor.
2806 consumeError(MaybeEntry.takeError());
2807 return Failure;
2808 }
2809 llvm::BitstreamEntry Entry = MaybeEntry.get();
2810
2811 switch (Entry.Kind) {
2812 case llvm::BitstreamEntry::Error:
2813 case llvm::BitstreamEntry::SubBlock:
2814 return Failure;
2815
2816 case llvm::BitstreamEntry::EndBlock:
2817 return Result;
2818
2819 case llvm::BitstreamEntry::Record:
2820 // The interesting case.
2821 break;
2822 }
2823
2824 // Read and process a record.
2825 Record.clear();
2826 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2827 if (!MaybeRecordType) {
2828 // FIXME this drops errors on the floor.
2829 consumeError(MaybeRecordType.takeError());
2830 return Failure;
2831 }
2832 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2833 case LANGUAGE_OPTIONS: {
2834 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2835 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
2836 AllowCompatibleConfigurationMismatch))
2837 Result = ConfigurationMismatch;
2838 break;
2839 }
2840
2841 case TARGET_OPTIONS: {
2842 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2843 if (ParseTargetOptions(Record, Filename, Complain, Listener,
2844 AllowCompatibleConfigurationMismatch))
2845 Result = ConfigurationMismatch;
2846 break;
2847 }
2848
2849 case FILE_SYSTEM_OPTIONS: {
2850 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2851 if (!AllowCompatibleConfigurationMismatch &&
2852 ParseFileSystemOptions(Record, Complain, Listener))
2853 Result = ConfigurationMismatch;
2854 break;
2855 }
2856
2857 case HEADER_SEARCH_OPTIONS: {
2858 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2859 if (!AllowCompatibleConfigurationMismatch &&
2860 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
2861 Result = ConfigurationMismatch;
2862 break;
2863 }
2864
2866 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2867 if (!AllowCompatibleConfigurationMismatch &&
2868 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
2869 SuggestedPredefines))
2870 Result = ConfigurationMismatch;
2871 break;
2872 }
2873 }
2874}
2875
2877ASTReader::ReadControlBlock(ModuleFile &F,
2879 const ModuleFile *ImportedBy,
2880 unsigned ClientLoadCapabilities) {
2881 BitstreamCursor &Stream = F.Stream;
2882
2883 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2884 Error(std::move(Err));
2885 return Failure;
2886 }
2887
2888 // Lambda to read the unhashed control block the first time it's called.
2889 //
2890 // For PCM files, the unhashed control block cannot be read until after the
2891 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2892 // need to look ahead before reading the IMPORTS record. For consistency,
2893 // this block is always read somehow (see BitstreamEntry::EndBlock).
2894 bool HasReadUnhashedControlBlock = false;
2895 auto readUnhashedControlBlockOnce = [&]() {
2896 if (!HasReadUnhashedControlBlock) {
2897 HasReadUnhashedControlBlock = true;
2898 if (ASTReadResult Result =
2899 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2900 return Result;
2901 }
2902 return Success;
2903 };
2904
2905 bool DisableValidation = shouldDisableValidationForFile(F);
2906
2907 // Read all of the records and blocks in the control block.
2908 RecordData Record;
2909 unsigned NumInputs = 0;
2910 unsigned NumUserInputs = 0;
2911 StringRef BaseDirectoryAsWritten;
2912 while (true) {
2913 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2914 if (!MaybeEntry) {
2915 Error(MaybeEntry.takeError());
2916 return Failure;
2917 }
2918 llvm::BitstreamEntry Entry = MaybeEntry.get();
2919
2920 switch (Entry.Kind) {
2921 case llvm::BitstreamEntry::Error:
2922 Error("malformed block record in AST file");
2923 return Failure;
2924 case llvm::BitstreamEntry::EndBlock: {
2925 // Validate the module before returning. This call catches an AST with
2926 // no module name and no imports.
2927 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2928 return Result;
2929
2930 // Validate input files.
2931 const HeaderSearchOptions &HSOpts =
2932 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2933
2934 // All user input files reside at the index range [0, NumUserInputs), and
2935 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2936 // loaded module files, ignore missing inputs.
2937 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2938 F.Kind != MK_PrebuiltModule) {
2939 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2940
2941 // If we are reading a module, we will create a verification timestamp,
2942 // so we verify all input files. Otherwise, verify only user input
2943 // files.
2944
2945 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
2949 N = NumUserInputs;
2950
2951 for (unsigned I = 0; I < N; ++I) {
2952 InputFile IF = getInputFile(F, I+1, Complain);
2953 if (!IF.getFile() || IF.isOutOfDate())
2954 return OutOfDate;
2955 }
2956 }
2957
2958 if (Listener)
2959 Listener->visitModuleFile(F.FileName, F.Kind);
2960
2961 if (Listener && Listener->needsInputFileVisitation()) {
2962 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2963 : NumUserInputs;
2964 for (unsigned I = 0; I < N; ++I) {
2965 bool IsSystem = I >= NumUserInputs;
2966 InputFileInfo FI = getInputFileInfo(F, I + 1);
2967 Listener->visitInputFile(
2968 FI.FilenameAsRequested, IsSystem, FI.Overridden,
2970 }
2971 }
2972
2973 return Success;
2974 }
2975
2976 case llvm::BitstreamEntry::SubBlock:
2977 switch (Entry.ID) {
2979 F.InputFilesCursor = Stream;
2980 if (llvm::Error Err = Stream.SkipBlock()) {
2981 Error(std::move(Err));
2982 return Failure;
2983 }
2984 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2985 Error("malformed block record in AST file");
2986 return Failure;
2987 }
2988 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
2989 continue;
2990
2991 case OPTIONS_BLOCK_ID:
2992 // If we're reading the first module for this group, check its options
2993 // are compatible with ours. For modules it imports, no further checking
2994 // is required, because we checked them when we built it.
2995 if (Listener && !ImportedBy) {
2996 // Should we allow the configuration of the module file to differ from
2997 // the configuration of the current translation unit in a compatible
2998 // way?
2999 //
3000 // FIXME: Allow this for files explicitly specified with -include-pch.
3001 bool AllowCompatibleConfigurationMismatch =
3003
3004 ASTReadResult Result =
3005 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities,
3006 AllowCompatibleConfigurationMismatch, *Listener,
3007 SuggestedPredefines);
3008 if (Result == Failure) {
3009 Error("malformed block record in AST file");
3010 return Result;
3011 }
3012
3013 if (DisableValidation ||
3014 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
3015 Result = Success;
3016
3017 // If we can't load the module, exit early since we likely
3018 // will rebuild the module anyway. The stream may be in the
3019 // middle of a block.
3020 if (Result != Success)
3021 return Result;
3022 } else if (llvm::Error Err = Stream.SkipBlock()) {
3023 Error(std::move(Err));
3024 return Failure;
3025 }
3026 continue;
3027
3028 default:
3029 if (llvm::Error Err = Stream.SkipBlock()) {
3030 Error(std::move(Err));
3031 return Failure;
3032 }
3033 continue;
3034 }
3035
3036 case llvm::BitstreamEntry::Record:
3037 // The interesting case.
3038 break;
3039 }
3040
3041 // Read and process a record.
3042 Record.clear();
3043 StringRef Blob;
3044 Expected<unsigned> MaybeRecordType =
3045 Stream.readRecord(Entry.ID, Record, &Blob);
3046 if (!MaybeRecordType) {
3047 Error(MaybeRecordType.takeError());
3048 return Failure;
3049 }
3050 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3051 case METADATA: {
3052 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3053 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3054 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old
3055 : diag::err_ast_file_version_too_new)
3057 return VersionMismatch;
3058 }
3059
3060 bool hasErrors = Record[7];
3061 if (hasErrors && !DisableValidation) {
3062 // If requested by the caller and the module hasn't already been read
3063 // or compiled, mark modules on error as out-of-date.
3064 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3065 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3066 return OutOfDate;
3067
3068 if (!AllowASTWithCompilerErrors) {
3069 Diag(diag::err_ast_file_with_compiler_errors)
3071 return HadErrors;
3072 }
3073 }
3074 if (hasErrors) {
3075 Diags.ErrorOccurred = true;
3076 Diags.UncompilableErrorOccurred = true;
3077 Diags.UnrecoverableErrorOccurred = true;
3078 }
3079
3080 F.RelocatablePCH = Record[4];
3081 // Relative paths in a relocatable PCH are relative to our sysroot.
3082 if (F.RelocatablePCH)
3083 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3084
3086
3087 F.HasTimestamps = Record[6];
3088
3089 const std::string &CurBranch = getClangFullRepositoryVersion();
3090 StringRef ASTBranch = Blob;
3091 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3092 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3093 Diag(diag::err_ast_file_different_branch)
3094 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch
3095 << CurBranch;
3096 return VersionMismatch;
3097 }
3098 break;
3099 }
3100
3101 case IMPORTS: {
3102 // Validate the AST before processing any imports (otherwise, untangling
3103 // them can be error-prone and expensive). A module will have a name and
3104 // will already have been validated, but this catches the PCH case.
3105 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3106 return Result;
3107
3108 // Load each of the imported PCH files.
3109 unsigned Idx = 0, N = Record.size();
3110 while (Idx < N) {
3111 // Read information about the AST file.
3112 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3113 // Whether we're importing a standard c++ module.
3114 bool IsImportingStdCXXModule = Record[Idx++];
3115 // The import location will be the local one for now; we will adjust
3116 // all import locations of module imports after the global source
3117 // location info are setup, in ReadAST.
3118 auto [ImportLoc, ImportModuleFileIndex] =
3119 ReadUntranslatedSourceLocation(Record[Idx++]);
3120 // The import location must belong to the current module file itself.
3121 assert(ImportModuleFileIndex == 0);
3122 off_t StoredSize = !IsImportingStdCXXModule ? (off_t)Record[Idx++] : 0;
3123 time_t StoredModTime =
3124 !IsImportingStdCXXModule ? (time_t)Record[Idx++] : 0;
3125
3126 ASTFileSignature StoredSignature;
3127 if (!IsImportingStdCXXModule) {
3128 auto FirstSignatureByte = Record.begin() + Idx;
3129 StoredSignature = ASTFileSignature::create(
3130 FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
3132 }
3133
3134 std::string ImportedName = ReadString(Record, Idx);
3135 std::string ImportedFile;
3136
3137 // For prebuilt and explicit modules first consult the file map for
3138 // an override. Note that here we don't search prebuilt module
3139 // directories if we're not importing standard c++ module, only the
3140 // explicit name to file mappings. Also, we will still verify the
3141 // size/signature making sure it is essentially the same file but
3142 // perhaps in a different location.
3143 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3144 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3145 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3146
3147 // For C++20 Modules, we won't record the path to the imported modules
3148 // in the BMI
3149 if (!IsImportingStdCXXModule) {
3150 if (ImportedFile.empty()) {
3151 // Use BaseDirectoryAsWritten to ensure we use the same path in the
3152 // ModuleCache as when writing.
3153 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
3154 } else
3155 SkipPath(Record, Idx);
3156 } else if (ImportedFile.empty()) {
3157 Diag(clang::diag::err_failed_to_find_module_file) << ImportedName;
3158 return Missing;
3159 }
3160
3161 // If our client can't cope with us being out of date, we can't cope with
3162 // our dependency being missing.
3163 unsigned Capabilities = ClientLoadCapabilities;
3164 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3165 Capabilities &= ~ARR_Missing;
3166
3167 // Load the AST file.
3168 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3169 Loaded, StoredSize, StoredModTime,
3170 StoredSignature, Capabilities);
3171
3172 // If we diagnosed a problem, produce a backtrace.
3173 bool recompilingFinalized =
3174 Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
3175 getModuleManager().getModuleCache().isPCMFinal(F.FileName);
3176 if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
3177 Diag(diag::note_module_file_imported_by)
3178 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3179 if (recompilingFinalized)
3180 Diag(diag::note_module_file_conflict);
3181
3182 switch (Result) {
3183 case Failure: return Failure;
3184 // If we have to ignore the dependency, we'll have to ignore this too.
3185 case Missing:
3186 case OutOfDate: return OutOfDate;
3187 case VersionMismatch: return VersionMismatch;
3188 case ConfigurationMismatch: return ConfigurationMismatch;
3189 case HadErrors: return HadErrors;
3190 case Success: break;
3191 }
3192 }
3193 break;
3194 }
3195
3196 case ORIGINAL_FILE:
3197 F.OriginalSourceFileID = FileID::get(Record[0]);
3198 F.ActualOriginalSourceFileName = std::string(Blob);
3200 ResolveImportedPath(F, F.OriginalSourceFileName);
3201 break;
3202
3203 case ORIGINAL_FILE_ID:
3204 F.OriginalSourceFileID = FileID::get(Record[0]);
3205 break;
3206
3207 case MODULE_NAME:
3208 F.ModuleName = std::string(Blob);
3209 Diag(diag::remark_module_import)
3210 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3211 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3212 if (Listener)
3213 Listener->ReadModuleName(F.ModuleName);
3214
3215 // Validate the AST as soon as we have a name so we can exit early on
3216 // failure.
3217 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3218 return Result;
3219
3220 break;
3221
3222 case MODULE_DIRECTORY: {
3223 // Save the BaseDirectory as written in the PCM for computing the module
3224 // filename for the ModuleCache.
3225 BaseDirectoryAsWritten = Blob;
3226 assert(!F.ModuleName.empty() &&
3227 "MODULE_DIRECTORY found before MODULE_NAME");
3228 F.BaseDirectory = std::string(Blob);
3229 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3230 break;
3231 // If we've already loaded a module map file covering this module, we may
3232 // have a better path for it (relative to the current build).
3233 Module *M = PP.getHeaderSearchInfo().lookupModule(
3234 F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
3235 /*AllowExtraModuleMapSearch*/ true);
3236 if (M && M->Directory) {
3237 // If we're implicitly loading a module, the base directory can't
3238 // change between the build and use.
3239 // Don't emit module relocation error if we have -fno-validate-pch
3240 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3243 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3244 if (!BuildDir || *BuildDir != M->Directory) {
3245 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3246 Diag(diag::err_imported_module_relocated)
3247 << F.ModuleName << Blob << M->Directory->getName();
3248 return OutOfDate;
3249 }
3250 }
3251 F.BaseDirectory = std::string(M->Directory->getName());
3252 }
3253 break;
3254 }
3255
3256 case MODULE_MAP_FILE:
3257 if (ASTReadResult Result =
3258 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3259 return Result;
3260 break;
3261
3262 case INPUT_FILE_OFFSETS:
3263 NumInputs = Record[0];
3264 NumUserInputs = Record[1];
3266 (const llvm::support::unaligned_uint64_t *)Blob.data();
3267 F.InputFilesLoaded.resize(NumInputs);
3268 F.InputFileInfosLoaded.resize(NumInputs);
3269 F.NumUserInputFiles = NumUserInputs;
3270 break;
3271 }
3272 }
3273}
3274
3275llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3276 unsigned ClientLoadCapabilities) {
3277 BitstreamCursor &Stream = F.Stream;
3278
3279 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3280 return Err;
3281 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3282
3283 // Read all of the records and blocks for the AST file.
3284 RecordData Record;
3285 while (true) {
3286 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3287 if (!MaybeEntry)
3288 return MaybeEntry.takeError();
3289 llvm::BitstreamEntry Entry = MaybeEntry.get();
3290
3291 switch (Entry.Kind) {
3292 case llvm::BitstreamEntry::Error:
3293 return llvm::createStringError(
3294 std::errc::illegal_byte_sequence,
3295 "error at end of module block in AST file");
3296 case llvm::BitstreamEntry::EndBlock:
3297 // Outside of C++, we do not store a lookup map for the translation unit.
3298 // Instead, mark it as needing a lookup map to be built if this module
3299 // contains any declarations lexically within it (which it always does!).
3300 // This usually has no cost, since we very rarely need the lookup map for
3301 // the translation unit outside C++.
3302 if (ASTContext *Ctx = ContextObj) {
3303 DeclContext *DC = Ctx->getTranslationUnitDecl();
3304 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3306 }
3307
3308 return llvm::Error::success();
3309 case llvm::BitstreamEntry::SubBlock:
3310 switch (Entry.ID) {
3311 case DECLTYPES_BLOCK_ID:
3312 // We lazily load the decls block, but we want to set up the
3313 // DeclsCursor cursor to point into it. Clone our current bitcode
3314 // cursor to it, enter the block and read the abbrevs in that block.
3315 // With the main cursor, we just skip over it.
3316 F.DeclsCursor = Stream;
3317 if (llvm::Error Err = Stream.SkipBlock())
3318 return Err;
3319 if (llvm::Error Err = ReadBlockAbbrevs(
3321 return Err;
3322 break;
3323
3325 F.MacroCursor = Stream;
3326 if (!PP.getExternalSource())
3327 PP.setExternalSource(this);
3328
3329 if (llvm::Error Err = Stream.SkipBlock())
3330 return Err;
3331 if (llvm::Error Err =
3332 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3333 return Err;
3334 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3335 break;
3336
3338 F.PreprocessorDetailCursor = Stream;
3339
3340 if (llvm::Error Err = Stream.SkipBlock()) {
3341 return Err;
3342 }
3343 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3345 return Err;
3347 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3348
3349 if (!PP.getPreprocessingRecord())
3350 PP.createPreprocessingRecord();
3351 if (!PP.getPreprocessingRecord()->getExternalSource())
3352 PP.getPreprocessingRecord()->SetExternalSource(*this);
3353 break;
3354
3356 if (llvm::Error Err = ReadSourceManagerBlock(F))
3357 return Err;
3358 break;
3359
3360 case SUBMODULE_BLOCK_ID:
3361 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3362 return Err;
3363 break;
3364
3365 case COMMENTS_BLOCK_ID: {
3366 BitstreamCursor C = Stream;
3367
3368 if (llvm::Error Err = Stream.SkipBlock())
3369 return Err;
3370 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3371 return Err;
3372 CommentsCursors.push_back(std::make_pair(C, &F));
3373 break;
3374 }
3375
3376 default:
3377 if (llvm::Error Err = Stream.SkipBlock())
3378 return Err;
3379 break;
3380 }
3381 continue;
3382
3383 case llvm::BitstreamEntry::Record:
3384 // The interesting case.
3385 break;
3386 }
3387
3388 // Read and process a record.
3389 Record.clear();
3390 StringRef Blob;
3391 Expected<unsigned> MaybeRecordType =
3392 Stream.readRecord(Entry.ID, Record, &Blob);
3393 if (!MaybeRecordType)
3394 return MaybeRecordType.takeError();
3395 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3396
3397 // If we're not loading an AST context, we don't care about most records.
3398 if (!ContextObj) {
3399 switch (RecordType) {
3400 case IDENTIFIER_TABLE:
3401 case IDENTIFIER_OFFSET:
3403 case STATISTICS:
3406 case PP_COUNTER_VALUE:
3408 case MODULE_OFFSET_MAP:
3412 case IMPORTED_MODULES:
3413 case MACRO_OFFSET:
3414 break;
3415 default:
3416 continue;
3417 }
3418 }
3419
3420 switch (RecordType) {
3421 default: // Default behavior: ignore.
3422 break;
3423
3424 case TYPE_OFFSET: {
3425 if (F.LocalNumTypes != 0)
3426 return llvm::createStringError(
3427 std::errc::illegal_byte_sequence,
3428 "duplicate TYPE_OFFSET record in AST file");
3429 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3430 F.LocalNumTypes = Record[0];
3431 F.BaseTypeIndex = getTotalNumTypes();
3432
3433 if (F.LocalNumTypes > 0)
3434 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3435
3436 break;
3437 }
3438
3439 case DECL_OFFSET: {
3440 if (F.LocalNumDecls != 0)
3441 return llvm::createStringError(
3442 std::errc::illegal_byte_sequence,
3443 "duplicate DECL_OFFSET record in AST file");
3444 F.DeclOffsets = (const DeclOffset *)Blob.data();
3445 F.LocalNumDecls = Record[0];
3446 F.BaseDeclIndex = getTotalNumDecls();
3447
3448 if (F.LocalNumDecls > 0)
3449 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3450
3451 break;
3452 }
3453
3454 case TU_UPDATE_LEXICAL: {
3455 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3456 LexicalContents Contents(
3457 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3458 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3459 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3461 break;
3462 }
3463
3464 case UPDATE_VISIBLE: {
3465 unsigned Idx = 0;
3466 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3467 auto *Data = (const unsigned char*)Blob.data();
3468 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3469 // If we've already loaded the decl, perform the updates when we finish
3470 // loading this block.
3471 if (Decl *D = GetExistingDecl(ID))
3472 PendingUpdateRecords.push_back(
3473 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3474 break;
3475 }
3476
3477 case IDENTIFIER_TABLE:
3479 reinterpret_cast<const unsigned char *>(Blob.data());
3480 if (Record[0]) {
3481 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3483 F.IdentifierTableData + sizeof(uint32_t),
3485 ASTIdentifierLookupTrait(*this, F));
3486
3487 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3488 }
3489 break;
3490
3491 case IDENTIFIER_OFFSET: {
3492 if (F.LocalNumIdentifiers != 0)
3493 return llvm::createStringError(
3494 std::errc::illegal_byte_sequence,
3495 "duplicate IDENTIFIER_OFFSET record in AST file");
3496 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3498 F.BaseIdentifierID = getTotalNumIdentifiers();
3499
3500 if (F.LocalNumIdentifiers > 0)
3501 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3503 break;
3504 }
3505
3507 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3508 break;
3509
3511 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3512 // about "interesting" decls (for instance, if we're building a module).
3513 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3514 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3515 break;
3516
3518 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3519 // them (ie: if we're not codegenerating this module).
3520 if (F.Kind == MK_MainFile ||
3521 getContext().getLangOpts().BuildingPCHWithObjectFile)
3522 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3523 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3524 break;
3525
3526 case SPECIAL_TYPES:
3527 if (SpecialTypes.empty()) {
3528 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3529 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3530 break;
3531 }
3532
3533 if (SpecialTypes.size() != Record.size())
3534 return llvm::createStringError(std::errc::illegal_byte_sequence,
3535 "invalid special-types record");
3536
3537 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3538 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3539 if (!SpecialTypes[I])
3540 SpecialTypes[I] = ID;
3541 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3542 // merge step?
3543 }
3544 break;
3545
3546 case STATISTICS:
3547 TotalNumStatements += Record[0];
3548 TotalNumMacros += Record[1];
3549 TotalLexicalDeclContexts += Record[2];
3550 TotalVisibleDeclContexts += Record[3];
3551 break;
3552
3554 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3555 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
3556 break;
3557
3558 case DELEGATING_CTORS:
3559 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3560 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
3561 break;
3562
3564 if (Record.size() % 3 != 0)
3565 return llvm::createStringError(std::errc::illegal_byte_sequence,
3566 "invalid weak identifiers record");
3567
3568 // FIXME: Ignore weak undeclared identifiers from non-original PCH
3569 // files. This isn't the way to do it :)
3570 WeakUndeclaredIdentifiers.clear();
3571
3572 // Translate the weak, undeclared identifiers into global IDs.
3573 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3574 WeakUndeclaredIdentifiers.push_back(
3575 getGlobalIdentifierID(F, Record[I++]));
3576 WeakUndeclaredIdentifiers.push_back(
3577 getGlobalIdentifierID(F, Record[I++]));
3578 WeakUndeclaredIdentifiers.push_back(
3579 ReadSourceLocation(F, Record, I).getRawEncoding());
3580 }
3581 break;
3582
3583 case SELECTOR_OFFSETS: {
3584 F.SelectorOffsets = (const uint32_t *)Blob.data();
3586 unsigned LocalBaseSelectorID = Record[1];
3587 F.BaseSelectorID = getTotalNumSelectors();
3588
3589 if (F.LocalNumSelectors > 0) {
3590 // Introduce the global -> local mapping for selectors within this
3591 // module.
3592 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3593
3594 // Introduce the local -> global mapping for selectors within this
3595 // module.
3597 std::make_pair(LocalBaseSelectorID,
3598 F.BaseSelectorID - LocalBaseSelectorID));
3599
3600 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3601 }
3602 break;
3603 }
3604
3605 case METHOD_POOL:
3606 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3607 if (Record[0])
3609 = ASTSelectorLookupTable::Create(
3612 ASTSelectorLookupTrait(*this, F));
3613 TotalNumMethodPoolEntries += Record[1];
3614 break;
3615
3617 if (!Record.empty()) {
3618 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3619 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3620 Record[Idx++]));
3621 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3622 getRawEncoding());
3623 }
3624 }
3625 break;
3626
3627 case PP_ASSUME_NONNULL_LOC: {
3628 unsigned Idx = 0;
3629 if (!Record.empty())
3630 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3631 ReadSourceLocation(F, Record, Idx));
3632 break;
3633 }
3634
3636 if (!Record.empty()) {
3638 unsigned Idx = 0;
3639 while (Idx < Record.size())
3640 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
3641 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
3642 }
3643 break;
3644 }
3645
3647 if (!Record.empty()) {
3648 unsigned Idx = 0, End = Record.size() - 1;
3649 bool ReachedEOFWhileSkipping = Record[Idx++];
3650 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3651 if (ReachedEOFWhileSkipping) {
3652 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3653 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3654 bool FoundNonSkipPortion = Record[Idx++];
3655 bool FoundElse = Record[Idx++];
3656 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3657 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3658 FoundElse, ElseLoc);
3659 }
3660 SmallVector<PPConditionalInfo, 4> ConditionalStack;
3661 while (Idx < End) {
3662 auto Loc = ReadSourceLocation(F, Record, Idx);
3663 bool WasSkipping = Record[Idx++];
3664 bool FoundNonSkip = Record[Idx++];
3665 bool FoundElse = Record[Idx++];
3666 ConditionalStack.push_back(
3667 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3668 }
3669 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3670 }
3671 break;
3672
3673 case PP_COUNTER_VALUE:
3674 if (!Record.empty() && Listener)
3675 Listener->ReadCounter(F, Record[0]);
3676 break;
3677
3678 case FILE_SORTED_DECLS:
3679 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
3681 break;
3682
3684 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3686 SourceLocation::UIntTy SLocSpaceSize = Record[1];
3688 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3689 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3690 SLocSpaceSize);
3691 if (!F.SLocEntryBaseID) {
3692 if (!Diags.isDiagnosticInFlight()) {
3693 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
3694 SourceMgr.noteSLocAddressSpaceUsage(Diags);
3695 }
3696 return llvm::createStringError(std::errc::invalid_argument,
3697 "ran out of source locations");
3698 }
3699 // Make our entry in the range map. BaseID is negative and growing, so
3700 // we invert it. Because we invert it, though, we need the other end of
3701 // the range.
3702 unsigned RangeStart =
3704 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3706
3707 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3708 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
3709 GlobalSLocOffsetMap.insert(
3710 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3711 - SLocSpaceSize,&F));
3712
3713 TotalNumSLocEntries += F.LocalNumSLocEntries;
3714 break;
3715 }
3716
3717 case MODULE_OFFSET_MAP:
3718 F.ModuleOffsetMap = Blob;
3719 break;
3720
3722 ParseLineTable(F, Record);
3723 break;
3724
3725 case EXT_VECTOR_DECLS:
3726 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3727 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
3728 break;
3729
3730 case VTABLE_USES:
3731 if (Record.size() % 3 != 0)
3732 return llvm::createStringError(std::errc::illegal_byte_sequence,
3733 "Invalid VTABLE_USES record");
3734
3735 // Later tables overwrite earlier ones.
3736 // FIXME: Modules will have some trouble with this. This is clearly not
3737 // the right way to do this.
3738 VTableUses.clear();
3739
3740 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3741 VTableUses.push_back(
3742 {ReadDeclID(F, Record, Idx),
3743 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
3744 (bool)Record[Idx++]});
3745 }
3746 break;
3747
3749
3750 if (Record.size() % 2 != 0)
3751 return llvm::createStringError(
3752 std::errc::illegal_byte_sequence,
3753 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3754
3755 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3756 PendingInstantiations.push_back(
3757 {ReadDeclID(F, Record, I),
3758 ReadSourceLocation(F, Record, I).getRawEncoding()});
3759 }
3760 break;
3761
3762 case SEMA_DECL_REFS:
3763 if (Record.size() != 3)
3764 return llvm::createStringError(std::errc::illegal_byte_sequence,
3765 "Invalid SEMA_DECL_REFS block");
3766 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3767 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
3768 break;
3769
3770 case PPD_ENTITIES_OFFSETS: {
3771 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3772 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3773 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3774
3775 unsigned LocalBasePreprocessedEntityID = Record[0];
3776
3777 unsigned StartingID;
3778 if (!PP.getPreprocessingRecord())
3779 PP.createPreprocessingRecord();
3780 if (!PP.getPreprocessingRecord()->getExternalSource())
3781 PP.getPreprocessingRecord()->SetExternalSource(*this);
3782 StartingID
3783 = PP.getPreprocessingRecord()
3784 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3785 F.BasePreprocessedEntityID = StartingID;
3786
3787 if (F.NumPreprocessedEntities > 0) {
3788 // Introduce the global -> local mapping for preprocessed entities in
3789 // this module.
3790 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3791
3792 // Introduce the local -> global mapping for preprocessed entities in
3793 // this module.
3795 std::make_pair(LocalBasePreprocessedEntityID,
3796 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3797 }
3798
3799 break;
3800 }
3801
3802 case PPD_SKIPPED_RANGES: {
3803 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3804 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3805 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3806
3807 if (!PP.getPreprocessingRecord())
3808 PP.createPreprocessingRecord();
3809 if (!PP.getPreprocessingRecord()->getExternalSource())
3810 PP.getPreprocessingRecord()->SetExternalSource(*this);
3811 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3812 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3813
3815 GlobalSkippedRangeMap.insert(
3816 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3817 break;
3818 }
3819
3821 if (Record.size() % 2 != 0)
3822 return llvm::createStringError(
3823 std::errc::illegal_byte_sequence,
3824 "invalid DECL_UPDATE_OFFSETS block in AST file");
3825 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
3826 GlobalDeclID ID = ReadDeclID(F, Record, I);
3827 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
3828
3829 // If we've already loaded the decl, perform the updates when we finish
3830 // loading this block.
3831 if (Decl *D = GetExistingDecl(ID))
3832 PendingUpdateRecords.push_back(
3833 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3834 }
3835 break;
3836
3838 if (Record.size() % 3 != 0)
3839 return llvm::createStringError(
3840 std::errc::illegal_byte_sequence,
3841 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
3842 "file");
3843 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
3844 GlobalDeclID ID = ReadDeclID(F, Record, I);
3845
3846 uint64_t BaseOffset = F.DeclsBlockStartOffset;
3847 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
3848 uint64_t LocalLexicalOffset = Record[I++];
3849 uint64_t LexicalOffset =
3850 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
3851 uint64_t LocalVisibleOffset = Record[I++];
3852 uint64_t VisibleOffset =
3853 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
3854
3855 DelayedNamespaceOffsetMap[ID] = {LexicalOffset, VisibleOffset};
3856
3857 assert(!GetExistingDecl(ID) &&
3858 "We shouldn't load the namespace in the front of delayed "
3859 "namespace lexical and visible block");
3860 }
3861 break;
3862 }
3863
3865 if (F.LocalNumObjCCategoriesInMap != 0)
3866 return llvm::createStringError(
3867 std::errc::illegal_byte_sequence,
3868 "duplicate OBJC_CATEGORIES_MAP record in AST file");
3869
3871 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3872 break;
3873
3874 case OBJC_CATEGORIES:
3875 F.ObjCCategories.swap(Record);
3876 break;
3877
3879 // Later tables overwrite earlier ones.
3880 // FIXME: Modules will have trouble with this.
3881 CUDASpecialDeclRefs.clear();
3882 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3883 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
3884 break;
3885
3887 F.HeaderFileInfoTableData = Blob.data();
3889 if (Record[0]) {
3891 = HeaderFileInfoLookupTable::Create(
3892 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3893 (const unsigned char *)F.HeaderFileInfoTableData,
3894 HeaderFileInfoTrait(*this, F,
3895 &PP.getHeaderSearchInfo(),
3896 Blob.data() + Record[2]));
3897
3898 PP.getHeaderSearchInfo().SetExternalSource(this);
3899 if (!PP.getHeaderSearchInfo().getExternalLookup())
3900 PP.getHeaderSearchInfo().SetExternalLookup(this);
3901 }
3902 break;
3903
3904 case FP_PRAGMA_OPTIONS:
3905 // Later tables overwrite earlier ones.
3906 FPPragmaOptions.swap(Record);
3907 break;
3908
3909 case OPENCL_EXTENSIONS:
3910 for (unsigned I = 0, E = Record.size(); I != E; ) {
3911 auto Name = ReadString(Record, I);
3912 auto &OptInfo = OpenCLExtensions.OptMap[Name];
3913 OptInfo.Supported = Record[I++] != 0;
3914 OptInfo.Enabled = Record[I++] != 0;
3915 OptInfo.WithPragma = Record[I++] != 0;
3916 OptInfo.Avail = Record[I++];
3917 OptInfo.Core = Record[I++];
3918 OptInfo.Opt = Record[I++];
3919 }
3920 break;
3921
3923 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3924 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
3925 break;
3926
3927 case KNOWN_NAMESPACES:
3928 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3929 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
3930 break;
3931
3932 case UNDEFINED_BUT_USED:
3933 if (Record.size() % 2 != 0)
3934 return llvm::createStringError(std::errc::illegal_byte_sequence,
3935 "invalid undefined-but-used record");
3936 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3937 UndefinedButUsed.push_back(
3938 {ReadDeclID(F, Record, I),
3939 ReadSourceLocation(F, Record, I).getRawEncoding()});
3940 }
3941 break;
3942
3944 for (unsigned I = 0, N = Record.size(); I != N;) {
3945 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
3946 const uint64_t Count = Record[I++];
3947 DelayedDeleteExprs.push_back(Count);
3948 for (uint64_t C = 0; C < Count; ++C) {
3949 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3950 bool IsArrayForm = Record[I++] == 1;
3951 DelayedDeleteExprs.push_back(IsArrayForm);
3952 }
3953 }
3954 break;
3955
3956 case VTABLES_TO_EMIT:
3957 if (F.Kind == MK_MainFile ||
3958 getContext().getLangOpts().BuildingPCHWithObjectFile)
3959 for (unsigned I = 0, N = Record.size(); I != N;)
3960 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
3961 break;
3962
3963 case IMPORTED_MODULES:
3964 if (!F.isModule()) {
3965 // If we aren't loading a module (which has its own exports), make
3966 // all of the imported modules visible.
3967 // FIXME: Deal with macros-only imports.
3968 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3969 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3970 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3971 if (GlobalID) {
3972 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3973 if (DeserializationListener)
3974 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3975 }
3976 }
3977 }
3978 break;
3979
3980 case MACRO_OFFSET: {
3981 if (F.LocalNumMacros != 0)
3982 return llvm::createStringError(
3983 std::errc::illegal_byte_sequence,
3984 "duplicate MACRO_OFFSET record in AST file");
3985 F.MacroOffsets = (const uint32_t *)Blob.data();
3986 F.LocalNumMacros = Record[0];
3987 unsigned LocalBaseMacroID = Record[1];
3989 F.BaseMacroID = getTotalNumMacros();
3990
3991 if (F.LocalNumMacros > 0) {
3992 // Introduce the global -> local mapping for macros within this module.
3993 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3994
3995 // Introduce the local -> global mapping for macros within this module.
3997 std::make_pair(LocalBaseMacroID,
3998 F.BaseMacroID - LocalBaseMacroID));
3999
4000 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4001 }
4002 break;
4003 }
4004
4006 LateParsedTemplates.emplace_back(
4007 std::piecewise_construct, std::forward_as_tuple(&F),
4008 std::forward_as_tuple(Record.begin(), Record.end()));
4009 break;
4010
4012 if (Record.size() != 1)
4013 return llvm::createStringError(std::errc::illegal_byte_sequence,
4014 "invalid pragma optimize record");
4015 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4016 break;
4017
4019 if (Record.size() != 1)
4020 return llvm::createStringError(std::errc::illegal_byte_sequence,
4021 "invalid pragma ms_struct record");
4022 PragmaMSStructState = Record[0];
4023 break;
4024
4026 if (Record.size() != 2)
4027 return llvm::createStringError(
4028 std::errc::illegal_byte_sequence,
4029 "invalid pragma pointers to members record");
4030 PragmaMSPointersToMembersState = Record[0];
4031 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4032 break;
4033
4035 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4036 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4037 break;
4038
4040 if (Record.size() != 1)
4041 return llvm::createStringError(std::errc::illegal_byte_sequence,
4042 "invalid cuda pragma options record");
4043 ForceHostDeviceDepth = Record[0];
4044 break;
4045
4047 if (Record.size() < 3)
4048 return llvm::createStringError(std::errc::illegal_byte_sequence,
4049 "invalid pragma pack record");
4050 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4051 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4052 unsigned NumStackEntries = Record[2];
4053 unsigned Idx = 3;
4054 // Reset the stack when importing a new module.
4055 PragmaAlignPackStack.clear();
4056 for (unsigned I = 0; I < NumStackEntries; ++I) {
4057 PragmaAlignPackStackEntry Entry;
4058 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4059 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4060 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4061 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4062 Entry.SlotLabel = PragmaAlignPackStrings.back();
4063 PragmaAlignPackStack.push_back(Entry);
4064 }
4065 break;
4066 }
4067
4069 if (Record.size() < 3)
4070 return llvm::createStringError(std::errc::illegal_byte_sequence,
4071 "invalid pragma float control record");
4072 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4073 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4074 unsigned NumStackEntries = Record[2];
4075 unsigned Idx = 3;
4076 // Reset the stack when importing a new module.
4077 FpPragmaStack.clear();
4078 for (unsigned I = 0; I < NumStackEntries; ++I) {
4079 FpPragmaStackEntry Entry;
4080 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4081 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4082 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4083 FpPragmaStrings.push_back(ReadString(Record, Idx));
4084 Entry.SlotLabel = FpPragmaStrings.back();
4085 FpPragmaStack.push_back(Entry);
4086 }
4087 break;
4088 }
4089
4091 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4092 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4093 break;
4094 }
4095 }
4096}
4097
4098void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4099 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4100
4101 // Additional remapping information.
4102 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4103 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4104 F.ModuleOffsetMap = StringRef();
4105
4107 RemapBuilder MacroRemap(F.MacroRemap);
4108 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
4109 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4110 RemapBuilder SelectorRemap(F.SelectorRemap);
4111
4112 auto &ImportedModuleVector = F.TransitiveImports;
4113 assert(ImportedModuleVector.empty());
4114
4115 while (Data < DataEnd) {
4116 // FIXME: Looking up dependency modules by filename is horrible. Let's
4117 // start fixing this with prebuilt, explicit and implicit modules and see
4118 // how it goes...
4119 using namespace llvm::support;
4120 ModuleKind Kind = static_cast<ModuleKind>(
4121 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4122 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4123 StringRef Name = StringRef((const char*)Data, Len);
4124 Data += Len;
4127 ? ModuleMgr.lookupByModuleName(Name)
4128 : ModuleMgr.lookupByFileName(Name));
4129 if (!OM) {
4130 std::string Msg = "refers to unknown module, cannot find ";
4131 Msg.append(std::string(Name));
4132 Error(Msg);
4133 return;
4134 }
4135
4136 ImportedModuleVector.push_back(OM);
4137
4138 uint32_t MacroIDOffset =
4139 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4140 uint32_t PreprocessedEntityIDOffset =
4141 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4142 uint32_t SubmoduleIDOffset =
4143 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4144 uint32_t SelectorIDOffset =
4145 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4146
4147 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4148 RemapBuilder &Remap) {
4149 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4150 if (Offset != None)
4151 Remap.insert(std::make_pair(Offset,
4152 static_cast<int>(BaseOffset - Offset)));
4153 };
4154
4155 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
4156 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
4157 PreprocessedEntityRemap);
4158 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4159 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4160 }
4161}
4162
4164ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4165 const ModuleFile *ImportedBy,
4166 unsigned ClientLoadCapabilities) {
4167 unsigned Idx = 0;
4168 F.ModuleMapPath = ReadPath(F, Record, Idx);
4169
4170 // Try to resolve ModuleName in the current header search context and
4171 // verify that it is found in the same module map file as we saved. If the
4172 // top-level AST file is a main file, skip this check because there is no
4173 // usable header search context.
4174 assert(!F.ModuleName.empty() &&
4175 "MODULE_NAME should come before MODULE_MAP_FILE");
4176 if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4177 F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
4178 // An implicitly-loaded module file should have its module listed in some
4179 // module map file that we've already loaded.
4180 Module *M =
4181 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
4182 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4183 OptionalFileEntryRef ModMap =
4184 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4185 // Don't emit module relocation error if we have -fno-validate-pch
4186 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4188 !ModMap) {
4189 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4190 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4191 // This module was defined by an imported (explicit) module.
4192 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4193 << ASTFE->getName();
4194 } else {
4195 // This module was built with a different module map.
4196 Diag(diag::err_imported_module_not_found)
4197 << F.ModuleName << F.FileName
4198 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4199 << !ImportedBy;
4200 // In case it was imported by a PCH, there's a chance the user is
4201 // just missing to include the search path to the directory containing
4202 // the modulemap.
4203 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4204 Diag(diag::note_imported_by_pch_module_not_found)
4205 << llvm::sys::path::parent_path(F.ModuleMapPath);
4206 }
4207 }
4208 return OutOfDate;
4209 }
4210
4211 assert(M && M->Name == F.ModuleName && "found module with different name");
4212
4213 // Check the primary module map file.
4214 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
4215 if (!StoredModMap || *StoredModMap != ModMap) {
4216 assert(ModMap && "found module is missing module map file");
4217 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4218 "top-level import should be verified");
4219 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4220 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4221 Diag(diag::err_imported_module_modmap_changed)
4222 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4223 << ModMap->getName() << F.ModuleMapPath << NotImported;
4224 return OutOfDate;
4225 }
4226
4227 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4228 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4229 // FIXME: we should use input files rather than storing names.
4230 std::string Filename = ReadPath(F, Record, Idx);
4231 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4232 if (!SF) {
4233 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4234 Error("could not find file '" + Filename +"' referenced by AST file");
4235 return OutOfDate;
4236 }
4237 AdditionalStoredMaps.insert(*SF);
4238 }
4239
4240 // Check any additional module map files (e.g. module.private.modulemap)
4241 // that are not in the pcm.
4242 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4243 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4244 // Remove files that match
4245 // Note: SmallPtrSet::erase is really remove
4246 if (!AdditionalStoredMaps.erase(ModMap)) {
4247 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4248 Diag(diag::err_module_different_modmap)
4249 << F.ModuleName << /*new*/0 << ModMap.getName();
4250 return OutOfDate;
4251 }
4252 }
4253 }
4254
4255 // Check any additional module map files that are in the pcm, but not
4256 // found in header search. Cases that match are already removed.
4257 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4258 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4259 Diag(diag::err_module_different_modmap)
4260 << F.ModuleName << /*not new*/1 << ModMap.getName();
4261 return OutOfDate;
4262 }
4263 }
4264
4265 if (Listener)
4266 Listener->ReadModuleMapFile(F.ModuleMapPath);
4267 return Success;
4268}
4269
4270/// Move the given method to the back of the global list of methods.
4272 // Find the entry for this selector in the method pool.
4274 S.ObjC().MethodPool.find(Method->getSelector());
4275 if (Known == S.ObjC().MethodPool.end())
4276 return;
4277
4278 // Retrieve the appropriate method list.
4279 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4280 : Known->second.second;
4281 bool Found = false;
4282 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4283 if (!Found) {
4284 if (List->getMethod() == Method) {
4285 Found = true;
4286 } else {
4287 // Keep searching.
4288 continue;
4289 }
4290 }
4291
4292 if (List->getNext())
4293 List->setMethod(List->getNext()->getMethod());
4294 else
4295 List->setMethod(Method);
4296 }
4297}
4298
4300 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4301 for (Decl *D : Names) {
4302 bool wasHidden = !D->isUnconditionallyVisible();
4304
4305 if (wasHidden && SemaObj) {
4306 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4307 moveMethodToBackOfGlobalList(*SemaObj, Method);
4308 }
4309 }
4310 }
4311}
4312
4314 Module::NameVisibilityKind NameVisibility,
4315 SourceLocation ImportLoc) {
4318 Stack.push_back(Mod);
4319 while (!Stack.empty()) {
4320 Mod = Stack.pop_back_val();
4321
4322 if (NameVisibility <= Mod->NameVisibility) {
4323 // This module already has this level of visibility (or greater), so
4324 // there is nothing more to do.
4325 continue;
4326 }
4327
4328 if (Mod->isUnimportable()) {
4329 // Modules that aren't importable cannot be made visible.
4330 continue;
4331 }
4332
4333 // Update the module's name visibility.
4334 Mod->NameVisibility = NameVisibility;
4335
4336 // If we've already deserialized any names from this module,
4337 // mark them as visible.
4338 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4339 if (Hidden != HiddenNamesMap.end()) {
4340 auto HiddenNames = std::move(*Hidden);
4341 HiddenNamesMap.erase(Hidden);
4342 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4343 assert(!HiddenNamesMap.contains(Mod) &&
4344 "making names visible added hidden names");
4345 }
4346
4347 // Push any exported modules onto the stack to be marked as visible.
4349 Mod->getExportedModules(Exports);
4351 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4352 Module *Exported = *I;
4353 if (Visited.insert(Exported).second)
4354 Stack.push_back(Exported);
4355 }
4356 }
4357}
4358
4359/// We've merged the definition \p MergedDef into the existing definition
4360/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4361/// visible.
4363 NamedDecl *MergedDef) {
4364 if (!Def->isUnconditionallyVisible()) {
4365 // If MergedDef is visible or becomes visible, make the definition visible.
4366 if (MergedDef->isUnconditionallyVisible())
4368 else {
4369 getContext().mergeDefinitionIntoModule(
4370 Def, MergedDef->getImportedOwningModule(),
4371 /*NotifyListeners*/ false);
4372 PendingMergedDefinitionsToDeduplicate.insert(Def);
4373 }
4374 }
4375}
4376
4378 if (GlobalIndex)
4379 return false;
4380
4381 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4382 !PP.getLangOpts().Modules)
4383 return true;
4384
4385 // Try to load the global index.
4386 TriedLoadingGlobalIndex = true;
4387 StringRef ModuleCachePath
4388 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4389 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4390 GlobalModuleIndex::readIndex(ModuleCachePath);
4391 if (llvm::Error Err = std::move(Result.second)) {
4392 assert(!Result.first);
4393 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4394 return true;
4395 }
4396
4397 GlobalIndex.reset(Result.first);
4398 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4399 return false;
4400}
4401
4403 return PP.getLangOpts().Modules && UseGlobalIndex &&
4404 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4405}
4406
4408 // Overwrite the timestamp file contents so that file's mtime changes.
4409 std::string TimestampFilename = MF.getTimestampFilename();
4410 std::error_code EC;
4411 llvm::raw_fd_ostream OS(TimestampFilename, EC,
4412 llvm::sys::fs::OF_TextWithCRLF);
4413 if (EC)
4414 return;
4415 OS << "Timestamp file\n";
4416 OS.close();
4417 OS.clear_error(); // Avoid triggering a fatal error.
4418}
4419
4420/// Given a cursor at the start of an AST file, scan ahead and drop the
4421/// cursor into the start of the given block ID, returning false on success and
4422/// true on failure.
4423static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4424 while (true) {
4425 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4426 if (!MaybeEntry) {
4427 // FIXME this drops errors on the floor.
4428 consumeError(MaybeEntry.takeError());
4429 return true;
4430 }
4431 llvm::BitstreamEntry Entry = MaybeEntry.get();
4432
4433 switch (Entry.Kind) {
4434 case llvm::BitstreamEntry::Error:
4435 case llvm::BitstreamEntry::EndBlock:
4436 return true;
4437
4438 case llvm::BitstreamEntry::Record:
4439 // Ignore top-level records.
4440 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4441 break;
4442 else {
4443 // FIXME this drops errors on the floor.
4444 consumeError(Skipped.takeError());
4445 return true;
4446 }
4447
4448 case llvm::BitstreamEntry::SubBlock:
4449 if (Entry.ID == BlockID) {
4450 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4451 // FIXME this drops the error on the floor.
4452 consumeError(std::move(Err));
4453 return true;
4454 }
4455 // Found it!
4456 return false;
4457 }
4458
4459 if (llvm::Error Err = Cursor.SkipBlock()) {
4460 // FIXME this drops the error on the floor.
4461 consumeError(std::move(Err));
4462 return true;
4463 }
4464 }
4465 }
4466}
4467
4469 SourceLocation ImportLoc,
4470 unsigned ClientLoadCapabilities,
4471 ModuleFile **NewLoadedModuleFile) {
4472 llvm::TimeTraceScope scope("ReadAST", FileName);
4473
4474 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4476 CurrentDeserializingModuleKind, Type);
4477
4478 // Defer any pending actions until we get to the end of reading the AST file.
4479 Deserializing AnASTFile(this);
4480
4481 // Bump the generation number.
4482 unsigned PreviousGeneration = 0;
4483 if (ContextObj)
4484 PreviousGeneration = incrementGeneration(*ContextObj);
4485
4486 unsigned NumModules = ModuleMgr.size();
4488 if (ASTReadResult ReadResult =
4489 ReadASTCore(FileName, Type, ImportLoc,
4490 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4491 ClientLoadCapabilities)) {
4492 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4493
4494 // If we find that any modules are unusable, the global index is going
4495 // to be out-of-date. Just remove it.
4496 GlobalIndex.reset();
4497 ModuleMgr.setGlobalIndex(nullptr);
4498 return ReadResult;
4499 }
4500
4501 if (NewLoadedModuleFile && !Loaded.empty())
4502 *NewLoadedModuleFile = Loaded.back().Mod;
4503
4504 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4505 // remove modules from this point. Various fields are updated during reading
4506 // the AST block and removing the modules would result in dangling pointers.
4507 // They are generally only incidentally dereferenced, ie. a binary search
4508 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4509 // be dereferenced but it wouldn't actually be used.
4510
4511 // Load the AST blocks of all of the modules that we loaded. We can still
4512 // hit errors parsing the ASTs at this point.
4513 for (ImportedModule &M : Loaded) {
4514 ModuleFile &F = *M.Mod;
4515 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4516
4517 // Read the AST block.
4518 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4519 Error(std::move(Err));
4520 return Failure;
4521 }
4522
4523 // The AST block should always have a definition for the main module.
4524 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4525 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4526 return Failure;
4527 }
4528
4529 // Read the extension blocks.
4531 if (llvm::Error Err = ReadExtensionBlock(F)) {
4532 Error(std::move(Err));
4533 return Failure;
4534 }
4535 }
4536
4537 // Once read, set the ModuleFile bit base offset and update the size in
4538 // bits of all files we've seen.
4539 F.GlobalBitOffset = TotalModulesSizeInBits;
4540 TotalModulesSizeInBits += F.SizeInBits;
4541 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4542 }
4543
4544 // Preload source locations and interesting indentifiers.
4545 for (ImportedModule &M : Loaded) {
4546 ModuleFile &F = *M.Mod;
4547
4548 // Map the original source file ID into the ID space of the current
4549 // compilation.
4551 F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
4552
4553 for (auto Offset : F.PreloadIdentifierOffsets) {
4554 const unsigned char *Data = F.IdentifierTableData + Offset;
4555
4556 ASTIdentifierLookupTrait Trait(*this, F);
4557 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4558 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4559
4560 IdentifierInfo *II;
4561 if (!PP.getLangOpts().CPlusPlus) {
4562 // Identifiers present in both the module file and the importing
4563 // instance are marked out-of-date so that they can be deserialized
4564 // on next use via ASTReader::updateOutOfDateIdentifier().
4565 // Identifiers present in the module file but not in the importing
4566 // instance are ignored for now, preventing growth of the identifier
4567 // table. They will be deserialized on first use via ASTReader::get().
4568 auto It = PP.getIdentifierTable().find(Key);
4569 if (It == PP.getIdentifierTable().end())
4570 continue;
4571 II = It->second;
4572 } else {
4573 // With C++ modules, not many identifiers are considered interesting.
4574 // All identifiers in the module file can be placed into the identifier
4575 // table of the importing instance and marked as out-of-date. This makes
4576 // ASTReader::get() a no-op, and deserialization will take place on
4577 // first/next use via ASTReader::updateOutOfDateIdentifier().
4578 II = &PP.getIdentifierTable().getOwn(Key);
4579 }
4580
4581 II->setOutOfDate(true);
4582
4583 // Mark this identifier as being from an AST file so that we can track
4584 // whether we need to serialize it.
4585 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
4586
4587 // Associate the ID with the identifier so that the writer can reuse it.
4588 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4589 SetIdentifierInfo(ID, II);
4590 }
4591 }
4592
4593 // Builtins and library builtins have already been initialized. Mark all
4594 // identifiers as out-of-date, so that they are deserialized on first use.
4595 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
4596 for (auto &Id : PP.getIdentifierTable())
4597 Id.second->setOutOfDate(true);
4598
4599 // Mark selectors as out of date.
4600 for (const auto &Sel : SelectorGeneration)
4601 SelectorOutOfDate[Sel.first] = true;
4602
4603 // Setup the import locations and notify the module manager that we've
4604 // committed to these module files.
4605 for (ImportedModule &M : Loaded) {
4606 ModuleFile &F = *M.Mod;
4607
4608 ModuleMgr.moduleFileAccepted(&F);
4609
4610 // Set the import location.
4611 F.DirectImportLoc = ImportLoc;
4612 // FIXME: We assume that locations from PCH / preamble do not need
4613 // any translation.
4614 if (!M.ImportedBy)
4615 F.ImportLoc = M.ImportLoc;
4616 else
4617 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4618 }
4619
4620 // Resolve any unresolved module exports.
4621 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4622 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4623 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4624 Module *ResolvedMod = getSubmodule(GlobalID);
4625
4626 switch (Unresolved.Kind) {
4627 case UnresolvedModuleRef::Conflict:
4628 if (ResolvedMod) {
4629 Module::Conflict Conflict;
4630 Conflict.Other = ResolvedMod;
4631 Conflict.Message = Unresolved.String.str();
4632 Unresolved.Mod->Conflicts.push_back(Conflict);
4633 }
4634 continue;
4635
4636 case UnresolvedModuleRef::Import:
4637 if (ResolvedMod)
4638 Unresolved.Mod->Imports.insert(ResolvedMod);
4639 continue;
4640
4641 case UnresolvedModuleRef::Affecting:
4642 if (ResolvedMod)
4643 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4644 continue;
4645
4646 case UnresolvedModuleRef::Export:
4647 if (ResolvedMod || Unresolved.IsWildcard)
4648 Unresolved.Mod->Exports.push_back(
4649 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4650 continue;
4651 }
4652 }
4653 UnresolvedModuleRefs.clear();
4654
4655 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4656 // Might be unnecessary as use declarations are only used to build the
4657 // module itself.
4658
4659 if (ContextObj)
4660 InitializeContext();
4661
4662 if (SemaObj)
4663 UpdateSema();
4664
4665 if (DeserializationListener)
4666 DeserializationListener->ReaderInitialized(this);
4667
4668 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4669 if (PrimaryModule.OriginalSourceFileID.isValid()) {
4670 // If this AST file is a precompiled preamble, then set the
4671 // preamble file ID of the source manager to the file source file
4672 // from which the preamble was built.
4673 if (Type == MK_Preamble) {
4674 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4675 } else if (Type == MK_MainFile) {
4676 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4677 }
4678 }
4679
4680 // For any Objective-C class definitions we have already loaded, make sure
4681 // that we load any additional categories.
4682 if (ContextObj) {
4683 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4684 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4685 ObjCClassesLoaded[I], PreviousGeneration);
4686 }
4687 }
4688
4689 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
4691 // Now we are certain that the module and all modules it depends on are
4692 // up-to-date. For implicitly-built module files, ensure the corresponding
4693 // timestamp files are up-to-date in this build session.
4694 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4695 ImportedModule &M = Loaded[I];
4696 if (M.Mod->Kind == MK_ImplicitModule &&
4697 M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp)
4698 updateModuleTimestamp(*M.Mod);
4699 }
4700 }
4701
4702 return Success;
4703}
4704
4705static ASTFileSignature readASTFileSignature(StringRef PCH);
4706
4707/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4708static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4709 // FIXME checking magic headers is done in other places such as
4710 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4711 // always done the same. Unify it all with a helper.
4712 if (!Stream.canSkipToPos(4))
4713 return llvm::createStringError(std::errc::illegal_byte_sequence,
4714 "file too small to contain AST file magic");
4715 for (unsigned C : {'C', 'P', 'C', 'H'})
4716 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4717 if (Res.get() != C)
4718 return llvm::createStringError(
4719 std::errc::illegal_byte_sequence,
4720 "file doesn't start with AST file magic");
4721 } else
4722 return Res.takeError();
4723 return llvm::Error::success();
4724}
4725
4727 switch (Kind) {
4728 case MK_PCH:
4729 return 0; // PCH
4730 case MK_ImplicitModule:
4731 case MK_ExplicitModule:
4732 case MK_PrebuiltModule:
4733 return 1; // module
4734 case MK_MainFile:
4735 case MK_Preamble:
4736 return 2; // main source file
4737 }
4738 llvm_unreachable("unknown module kind");
4739}
4740
4742ASTReader::ReadASTCore(StringRef FileName,
4744 SourceLocation ImportLoc,
4745 ModuleFile *ImportedBy,
4747 off_t ExpectedSize, time_t ExpectedModTime,
4748 ASTFileSignature ExpectedSignature,
4749 unsigned ClientLoadCapabilities) {
4750 ModuleFile *M;
4751 std::string ErrorStr;
4753 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4754 getGeneration(), ExpectedSize, ExpectedModTime,
4755 ExpectedSignature, readASTFileSignature,
4756 M, ErrorStr);
4757
4758 switch (AddResult) {
4760 Diag(diag::remark_module_import)
4761 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4762 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4763 return Success;
4764
4766 // Load module file below.
4767 break;
4768
4770 // The module file was missing; if the client can handle that, return
4771 // it.
4772 if (ClientLoadCapabilities & ARR_Missing)
4773 return Missing;
4774
4775 // Otherwise, return an error.
4776 Diag(diag::err_ast_file_not_found)
4777 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4778 << ErrorStr;
4779 return Failure;
4780
4782 // We couldn't load the module file because it is out-of-date. If the
4783 // client can handle out-of-date, return it.
4784 if (ClientLoadCapabilities & ARR_OutOfDate)
4785 return OutOfDate;
4786
4787 // Otherwise, return an error.
4788 Diag(diag::err_ast_file_out_of_date)
4789 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4790 << ErrorStr;
4791 return Failure;
4792 }
4793
4794 assert(M && "Missing module file");
4795
4796 bool ShouldFinalizePCM = false;
4797 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4798 auto &MC = getModuleManager().getModuleCache();
4799 if (ShouldFinalizePCM)
4800 MC.finalizePCM(FileName);
4801 else
4802 MC.tryToDropPCM(FileName);
4803 });
4804 ModuleFile &F = *M;
4805 BitstreamCursor &Stream = F.Stream;
4806 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4807 F.SizeInBits = F.Buffer->getBufferSize() * 8;
4808
4809 // Sniff for the signature.
4810 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4811 Diag(diag::err_ast_file_invalid)
4812 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4813 return Failure;
4814 }
4815
4816 // This is used for compatibility with older PCH formats.
4817 bool HaveReadControlBlock = false;
4818 while (true) {
4819 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4820 if (!MaybeEntry) {
4821 Error(MaybeEntry.takeError());
4822 return Failure;
4823 }
4824 llvm::BitstreamEntry Entry = MaybeEntry.get();
4825
4826 switch (Entry.Kind) {
4827 case llvm::BitstreamEntry::Error:
4828 case llvm::BitstreamEntry::Record:
4829 case llvm::BitstreamEntry::EndBlock:
4830 Error("invalid record at top-level of AST file");
4831 return Failure;
4832
4833 case llvm::BitstreamEntry::SubBlock:
4834 break;
4835 }
4836
4837 switch (Entry.ID) {
4838 case CONTROL_BLOCK_ID:
4839 HaveReadControlBlock = true;
4840 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4841 case Success:
4842 // Check that we didn't try to load a non-module AST file as a module.
4843 //
4844 // FIXME: Should we also perform the converse check? Loading a module as
4845 // a PCH file sort of works, but it's a bit wonky.
4847 Type == MK_PrebuiltModule) &&
4848 F.ModuleName.empty()) {
4849 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4850 if (Result != OutOfDate ||
4851 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4852 Diag(diag::err_module_file_not_module) << FileName;
4853 return Result;
4854 }
4855 break;
4856
4857 case Failure: return Failure;
4858 case Missing: return Missing;
4859 case OutOfDate: return OutOfDate;
4860 case VersionMismatch: return VersionMismatch;
4861 case ConfigurationMismatch: return ConfigurationMismatch;
4862 case HadErrors: return HadErrors;
4863 }
4864 break;
4865
4866 case AST_BLOCK_ID:
4867 if (!HaveReadControlBlock) {
4868 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4869 Diag(diag::err_ast_file_version_too_old)
4871 return VersionMismatch;
4872 }
4873
4874 // Record that we've loaded this module.
4875 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4876 ShouldFinalizePCM = true;
4877 return Success;
4878
4879 default:
4880 if (llvm::Error Err = Stream.SkipBlock()) {
4881 Error(std::move(Err));
4882 return Failure;
4883 }
4884 break;
4885 }
4886 }
4887
4888 llvm_unreachable("unexpected break; expected return");
4889}
4890
4892ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4893 unsigned ClientLoadCapabilities) {
4894 const HeaderSearchOptions &HSOpts =
4895 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4896 bool AllowCompatibleConfigurationMismatch =
4898 bool DisableValidation = shouldDisableValidationForFile(F);
4899
4900 ASTReadResult Result = readUnhashedControlBlockImpl(
4901 &F, F.Data, F.FileName, ClientLoadCapabilities,
4902 AllowCompatibleConfigurationMismatch, Listener.get(),
4903 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4904
4905 // If F was directly imported by another module, it's implicitly validated by
4906 // the importing module.
4907 if (DisableValidation || WasImportedBy ||
4908 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4909 return Success;
4910
4911 if (Result == Failure) {
4912 Error("malformed block record in AST file");
4913 return Failure;
4914 }
4915
4916 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4917 // If this module has already been finalized in the ModuleCache, we're stuck
4918 // with it; we can only load a single version of each module.
4919 //
4920 // This can happen when a module is imported in two contexts: in one, as a
4921 // user module; in another, as a system module (due to an import from
4922 // another module marked with the [system] flag). It usually indicates a
4923 // bug in the module map: this module should also be marked with [system].
4924 //
4925 // If -Wno-system-headers (the default), and the first import is as a
4926 // system module, then validation will fail during the as-user import,
4927 // since -Werror flags won't have been validated. However, it's reasonable
4928 // to treat this consistently as a system module.
4929 //
4930 // If -Wsystem-headers, the PCM on disk was built with
4931 // -Wno-system-headers, and the first import is as a user module, then
4932 // validation will fail during the as-system import since the PCM on disk
4933 // doesn't guarantee that -Werror was respected. However, the -Werror
4934 // flags were checked during the initial as-user import.
4935 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4936 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4937 return Success;
4938 }
4939 }
4940
4941 return Result;
4942}
4943
4944ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4945 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
4946 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
4947 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
4948 // Initialize a stream.
4949 BitstreamCursor Stream(StreamData);
4950
4951 // Sniff for the signature.
4952 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4953 // FIXME this drops the error on the floor.
4954 consumeError(std::move(Err));
4955 return Failure;
4956 }
4957
4958 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4960 return Failure;
4961
4962 // Read all of the records in the options block.
4963 RecordData Record;
4964 ASTReadResult Result = Success;
4965 while (true) {
4966 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4967 if (!MaybeEntry) {
4968 // FIXME this drops the error on the floor.
4969 consumeError(MaybeEntry.takeError());
4970 return Failure;
4971 }
4972 llvm::BitstreamEntry Entry = MaybeEntry.get();
4973
4974 switch (Entry.Kind) {
4975 case llvm::BitstreamEntry::Error:
4976 case llvm::BitstreamEntry::SubBlock:
4977 return Failure;
4978
4979 case llvm::BitstreamEntry::EndBlock:
4980 return Result;
4981
4982 case llvm::BitstreamEntry::Record:
4983 // The interesting case.
4984 break;
4985 }
4986
4987 // Read and process a record.
4988 Record.clear();
4989 StringRef Blob;
4990 Expected<unsigned> MaybeRecordType =
4991 Stream.readRecord(Entry.ID, Record, &Blob);
4992 if (!MaybeRecordType) {
4993 // FIXME this drops the error.
4994 return Failure;
4995 }
4996 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4997 case SIGNATURE:
4998 if (F) {
4999 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5001 "Dummy AST file signature not backpatched in ASTWriter.");
5002 }
5003 break;
5004 case AST_BLOCK_HASH:
5005 if (F) {
5006 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5008 "Dummy AST block hash not backpatched in ASTWriter.");
5009 }
5010 break;
5011 case DIAGNOSTIC_OPTIONS: {
5012 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5013 if (Listener && ValidateDiagnosticOptions &&
5014 !AllowCompatibleConfigurationMismatch &&
5015 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5016 Result = OutOfDate; // Don't return early. Read the signature.
5017 break;
5018 }
5019 case HEADER_SEARCH_PATHS: {
5020 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5021 if (Listener && !AllowCompatibleConfigurationMismatch &&
5022 ParseHeaderSearchPaths(Record, Complain, *Listener))
5023 Result = ConfigurationMismatch;
5024 break;
5025 }
5027 if (!F)
5028 break;
5029 if (F->PragmaDiagMappings.empty())
5030 F->PragmaDiagMappings.swap(Record);
5031 else
5032 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5033 Record.begin(), Record.end());
5034 break;
5036 if (F)
5037 F->SearchPathUsage = ReadBitVector(Record, Blob);
5038 break;
5039 case VFS_USAGE:
5040 if (F)
5041 F->VFSUsage = ReadBitVector(Record, Blob);
5042 break;
5043 }
5044 }
5045}
5046
5047/// Parse a record and blob containing module file extension metadata.
5050 StringRef Blob,
5051 ModuleFileExtensionMetadata &Metadata) {
5052 if (Record.size() < 4) return true;
5053
5054 Metadata.MajorVersion = Record[0];
5055 Metadata.MinorVersion = Record[1];
5056
5057 unsigned BlockNameLen = Record[2];
5058 unsigned UserInfoLen = Record[3];
5059
5060 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5061
5062 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5063 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5064 Blob.data() + BlockNameLen + UserInfoLen);
5065 return false;
5066}
5067
5068llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5069 BitstreamCursor &Stream = F.Stream;
5070
5071 RecordData Record;
5072 while (true) {
5073 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5074 if (!MaybeEntry)
5075 return MaybeEntry.takeError();
5076 llvm::BitstreamEntry Entry = MaybeEntry.get();
5077
5078 switch (Entry.Kind) {
5079 case llvm::BitstreamEntry::SubBlock:
5080 if (llvm::Error Err = Stream.SkipBlock())
5081 return Err;
5082 continue;
5083 case llvm::BitstreamEntry::EndBlock:
5084 return llvm::Error::success();
5085 case llvm::BitstreamEntry::Error:
5086 return llvm::createStringError(std::errc::illegal_byte_sequence,
5087 "malformed block record in AST file");
5088 case llvm::BitstreamEntry::Record:
5089 break;
5090 }
5091
5092 Record.clear();
5093 StringRef Blob;
5094 Expected<unsigned> MaybeRecCode =
5095 Stream.readRecord(Entry.ID, Record, &Blob);
5096 if (!MaybeRecCode)
5097 return MaybeRecCode.takeError();
5098 switch (MaybeRecCode.get()) {
5099 case EXTENSION_METADATA: {
5101 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5102 return llvm::createStringError(
5103 std::errc::illegal_byte_sequence,
5104 "malformed EXTENSION_METADATA in AST file");
5105
5106 // Find a module file extension with this block name.
5107 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5108 if (Known == ModuleFileExtensions.end()) break;
5109
5110 // Form a reader.
5111 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5112 F, Stream)) {
5113 F.ExtensionReaders.push_back(std::move(Reader));
5114 }
5115
5116 break;
5117 }
5118 }
5119 }
5120
5121 return llvm::Error::success();
5122}
5123
5125 assert(ContextObj && "no context to initialize");
5126 ASTContext &Context = *ContextObj;
5127
5128 // If there's a listener, notify them that we "read" the translation unit.
5129 if (DeserializationListener)
5130 DeserializationListener->DeclRead(
5132 Context.getTranslationUnitDecl());
5133
5134 // FIXME: Find a better way to deal with collisions between these
5135 // built-in types. Right now, we just ignore the problem.
5136
5137 // Load the special types.
5138 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5139 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5140 if (!Context.CFConstantStringTypeDecl)
5141 Context.setCFConstantStringType(GetType(String));
5142 }
5143
5144 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5145 QualType FileType = GetType(File);
5146 if (FileType.isNull()) {
5147 Error("FILE type is NULL");
5148 return;
5149 }
5150
5151 if (!Context.FILEDecl) {
5152 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5153 Context.setFILEDecl(Typedef->getDecl());
5154 else {
5155 const TagType *Tag = FileType->getAs<TagType>();
5156 if (!Tag) {
5157 Error("Invalid FILE type in AST file");
5158 return;
5159 }
5160 Context.setFILEDecl(Tag->getDecl());
5161 }
5162 }
5163 }
5164
5165 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5166 QualType Jmp_bufType = GetType(Jmp_buf);
5167 if (Jmp_bufType.isNull()) {
5168 Error("jmp_buf type is NULL");
5169 return;
5170 }
5171
5172 if (!Context.jmp_bufDecl) {
5173 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5174 Context.setjmp_bufDecl(Typedef->getDecl());
5175 else {
5176 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5177 if (!Tag) {
5178 Error("Invalid jmp_buf type in AST file");
5179 return;
5180 }
5181 Context.setjmp_bufDecl(Tag->getDecl());
5182 }
5183 }
5184 }
5185
5186 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5187 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5188 if (Sigjmp_bufType.isNull()) {
5189 Error("sigjmp_buf type is NULL");
5190 return;
5191 }
5192
5193 if (!Context.sigjmp_bufDecl) {
5194 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5195 Context.setsigjmp_bufDecl(Typedef->getDecl());
5196 else {
5197 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5198 assert(Tag && "Invalid sigjmp_buf type in AST file");
5199 Context.setsigjmp_bufDecl(Tag->getDecl());
5200 }
5201 }
5202 }
5203
5204 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5205 if (Context.ObjCIdRedefinitionType.isNull())
5206 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5207 }
5208
5209 if (TypeID ObjCClassRedef =
5211 if (Context.ObjCClassRedefinitionType.isNull())
5212 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5213 }
5214
5215 if (TypeID ObjCSelRedef =
5216 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5217 if (Context.ObjCSelRedefinitionType.isNull())
5218 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5219 }
5220
5221 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5222 QualType Ucontext_tType = GetType(Ucontext_t);
5223 if (Ucontext_tType.isNull()) {
5224 Error("ucontext_t type is NULL");
5225 return;
5226 }
5227
5228 if (!Context.ucontext_tDecl) {
5229 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5230 Context.setucontext_tDecl(Typedef->getDecl());
5231 else {
5232 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5233 assert(Tag && "Invalid ucontext_t type in AST file");
5234 Context.setucontext_tDecl(Tag->getDecl());
5235 }
5236 }
5237 }
5238 }
5239
5240 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5241
5242 // If there were any CUDA special declarations, deserialize them.
5243 if (!CUDASpecialDeclRefs.empty()) {
5244 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5246 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5247 }
5248
5249 // Re-export any modules that were imported by a non-module AST file.
5250 // FIXME: This does not make macro-only imports visible again.
5251 for (auto &Import : PendingImportedModules) {
5252 if (Module *Imported = getSubmodule(Import.ID)) {
5253 makeModuleVisible(Imported, Module::AllVisible,
5254 /*ImportLoc=*/Import.ImportLoc);
5255 if (Import.ImportLoc.isValid())
5256 PP.makeModuleVisible(Imported, Import.ImportLoc);
5257 // This updates visibility for Preprocessor only. For Sema, which can be
5258 // nullptr here, we do the same later, in UpdateSema().
5259 }
5260 }
5261
5262 // Hand off these modules to Sema.
5263 PendingImportedModulesSema.append(PendingImportedModules);
5264 PendingImportedModules.clear();
5265}
5266
5268 // Nothing to do for now.
5269}
5270
5271/// Reads and return the signature record from \p PCH's control block, or
5272/// else returns 0.
5274 BitstreamCursor Stream(PCH);
5275 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5276 // FIXME this drops the error on the floor.
5277 consumeError(std::move(Err));
5278 return ASTFileSignature();
5279 }
5280
5281 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5283 return ASTFileSignature();
5284
5285 // Scan for SIGNATURE inside the diagnostic options block.
5287 while (true) {
5289 Stream.advanceSkippingSubblocks();
5290 if (!MaybeEntry) {
5291 // FIXME this drops the error on the floor.
5292 consumeError(MaybeEntry.takeError());
5293 return ASTFileSignature();
5294 }
5295 llvm::BitstreamEntry Entry = MaybeEntry.get();
5296
5297 if (Entry.Kind != llvm::BitstreamEntry::Record)
5298 return ASTFileSignature();
5299
5300 Record.clear();
5301 StringRef Blob;
5302 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5303 if (!MaybeRecord) {
5304 // FIXME this drops the error on the floor.
5305 consumeError(MaybeRecord.takeError());
5306 return ASTFileSignature();
5307 }
5308 if (SIGNATURE == MaybeRecord.get()) {
5309 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5310 assert(Signature != ASTFileSignature::createDummy() &&
5311 "Dummy AST file signature not backpatched in ASTWriter.");
5312 return Signature;
5313 }
5314 }
5315}
5316
5317/// Retrieve the name of the original source file name
5318/// directly from the AST file, without actually loading the AST
5319/// file.
5321 const std::string &ASTFileName, FileManager &FileMgr,
5322 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5323 // Open the AST file.
5324 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5325 /*RequiresNullTerminator=*/false);
5326 if (!Buffer) {
5327 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5328 << ASTFileName << Buffer.getError().message();
5329 return std::string();
5330 }
5331
5332 // Initialize the stream
5333 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5334
5335 // Sniff for the signature.
5336 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5337 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5338 return std::string();
5339 }
5340
5341 // Scan for the CONTROL_BLOCK_ID block.
5342 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5343 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5344 return std::string();
5345 }
5346
5347 // Scan for ORIGINAL_FILE inside the control block.
5349 while (true) {
5351 Stream.advanceSkippingSubblocks();
5352 if (!MaybeEntry) {
5353 // FIXME this drops errors on the floor.
5354 consumeError(MaybeEntry.takeError());
5355 return std::string();
5356 }
5357 llvm::BitstreamEntry Entry = MaybeEntry.get();
5358
5359 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5360 return std::string();
5361
5362 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5363 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5364 return std::string();
5365 }
5366
5367 Record.clear();
5368 StringRef Blob;
5369 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5370 if (!MaybeRecord) {
5371 // FIXME this drops the errors on the floor.
5372 consumeError(MaybeRecord.takeError());
5373 return std::string();
5374 }
5375 if (ORIGINAL_FILE == MaybeRecord.get())
5376 return Blob.str();
5377 }
5378}
5379
5380namespace {
5381
5382 class SimplePCHValidator : public ASTReaderListener {
5383 const LangOptions &ExistingLangOpts;
5384 const TargetOptions &ExistingTargetOpts;
5385 const PreprocessorOptions &ExistingPPOpts;
5386 std::string ExistingModuleCachePath;
5387 FileManager &FileMgr;
5388 bool StrictOptionMatches;
5389
5390 public:
5391 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5392 const TargetOptions &ExistingTargetOpts,
5393 const PreprocessorOptions &ExistingPPOpts,
5394 StringRef ExistingModuleCachePath, FileManager &FileMgr,
5395 bool StrictOptionMatches)
5396 : ExistingLangOpts(ExistingLangOpts),
5397 ExistingTargetOpts(ExistingTargetOpts),
5398 ExistingPPOpts(ExistingPPOpts),
5399 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5400 StrictOptionMatches(StrictOptionMatches) {}
5401
5402 bool ReadLanguageOptions(const LangOptions &LangOpts,
5403 StringRef ModuleFilename, bool Complain,
5404 bool AllowCompatibleDifferences) override {
5405 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
5406 nullptr, AllowCompatibleDifferences);
5407 }
5408
5409 bool ReadTargetOptions(const TargetOptions &TargetOpts,
5410 StringRef ModuleFilename, bool Complain,
5411 bool AllowCompatibleDifferences) override {
5412 return checkTargetOptions(ExistingTargetOpts, TargetOpts, ModuleFilename,
5413 nullptr, AllowCompatibleDifferences);
5414 }
5415
5416 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5417 StringRef ModuleFilename,
5418 StringRef SpecificModuleCachePath,
5419 bool Complain) override {
5421 SpecificModuleCachePath,
5422 ExistingModuleCachePath, ModuleFilename,
5423 nullptr, ExistingLangOpts, ExistingPPOpts);
5424 }
5425
5426 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5427 StringRef ModuleFilename, bool ReadMacros,
5428 bool Complain,
5429 std::string &SuggestedPredefines) override {
5431 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
5432 FileMgr, SuggestedPredefines, ExistingLangOpts,
5433 StrictOptionMatches ? OptionValidateStrictMatches
5435 }
5436 };
5437
5438} // namespace
5439
5441 StringRef Filename, FileManager &FileMgr,
5442 const InMemoryModuleCache &ModuleCache,
5443 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5444 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5445 unsigned ClientLoadCapabilities) {
5446 // Open the AST file.
5447 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5448 llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
5449 if (!Buffer) {
5450 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5451 // read again later, but we do not have the context here to determine if it
5452 // is safe to change the result of InMemoryModuleCache::getPCMState().
5453
5454 // FIXME: This allows use of the VFS; we do not allow use of the
5455 // VFS when actually loading a module.
5456 auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5457 if (!BufferOrErr)
5458 return true;
5459 OwnedBuffer = std::move(*BufferOrErr);
5460 Buffer = OwnedBuffer.get();
5461 }
5462
5463 // Initialize the stream
5464 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5465 BitstreamCursor Stream(Bytes);
5466
5467 // Sniff for the signature.
5468 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5469 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5470 return true;
5471 }
5472
5473 // Scan for the CONTROL_BLOCK_ID block.
5475 return true;
5476
5477 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5478 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5479 bool NeedsImports = Listener.needsImportVisitation();
5480 BitstreamCursor InputFilesCursor;
5481 uint64_t InputFilesOffsetBase = 0;
5482
5484 std::string ModuleDir;
5485 bool DoneWithControlBlock = false;
5486 while (!DoneWithControlBlock) {
5487 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5488 if (!MaybeEntry) {
5489 // FIXME this drops the error on the floor.
5490 consumeError(MaybeEntry.takeError());
5491 return true;
5492 }
5493 llvm::BitstreamEntry Entry = MaybeEntry.get();
5494
5495 switch (Entry.Kind) {
5496 case llvm::BitstreamEntry::SubBlock: {
5497 switch (Entry.ID) {
5498 case OPTIONS_BLOCK_ID: {
5499 std::string IgnoredSuggestedPredefines;
5500 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
5501 /*AllowCompatibleConfigurationMismatch*/ false,
5502 Listener, IgnoredSuggestedPredefines) != Success)
5503 return true;
5504 break;
5505 }
5506
5508 InputFilesCursor = Stream;
5509 if (llvm::Error Err = Stream.SkipBlock()) {
5510 // FIXME this drops the error on the floor.
5511 consumeError(std::move(Err));
5512 return true;
5513 }
5514 if (NeedsInputFiles &&
5515 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5516 return true;
5517 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5518 break;
5519
5520 default:
5521 if (llvm::Error Err = Stream.SkipBlock()) {
5522 // FIXME this drops the error on the floor.
5523 consumeError(std::move(Err));
5524 return true;
5525 }
5526 break;
5527 }
5528
5529 continue;
5530 }
5531
5532 case llvm::BitstreamEntry::EndBlock:
5533 DoneWithControlBlock = true;
5534 break;
5535
5536 case llvm::BitstreamEntry::Error:
5537 return true;
5538
5539 case llvm::BitstreamEntry::Record:
5540 break;
5541 }
5542
5543 if (DoneWithControlBlock) break;
5544
5545 Record.clear();
5546 StringRef Blob;
5547 Expected<unsigned> MaybeRecCode =
5548 Stream.readRecord(Entry.ID, Record, &Blob);
5549 if (!MaybeRecCode) {
5550 // FIXME this drops the error.
5551 return Failure;
5552 }
5553 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5554 case METADATA:
5555 if (Record[0] != VERSION_MAJOR)
5556 return true;
5557 if (Listener.ReadFullVersionInformation(Blob))
5558 return true;
5559 break;
5560 case MODULE_NAME:
5561 Listener.ReadModuleName(Blob);
5562 break;
5563 case MODULE_DIRECTORY:
5564 ModuleDir = std::string(Blob);
5565 break;
5566 case MODULE_MAP_FILE: {
5567 unsigned Idx = 0;
5568 auto Path = ReadString(Record, Idx);
5569 ResolveImportedPath(Path, ModuleDir);
5570 Listener.ReadModuleMapFile(Path);
5571 break;
5572 }
5573 case INPUT_FILE_OFFSETS: {
5574 if (!NeedsInputFiles)
5575 break;
5576
5577 unsigned NumInputFiles = Record[0];
5578 unsigned NumUserFiles = Record[1];
5579 const llvm::support::unaligned_uint64_t *InputFileOffs =
5580 (const llvm::support::unaligned_uint64_t *)Blob.data();
5581 for (unsigned I = 0; I != NumInputFiles; ++I) {
5582 // Go find this input file.
5583 bool isSystemFile = I >= NumUserFiles;
5584
5585 if (isSystemFile && !NeedsSystemInputFiles)
5586 break; // the rest are system input files
5587
5588 BitstreamCursor &Cursor = InputFilesCursor;
5589 SavedStreamPosition SavedPosition(Cursor);
5590 if (llvm::Error Err =
5591 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5592 // FIXME this drops errors on the floor.
5593 consumeError(std::move(Err));
5594 }
5595
5596 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5597 if (!MaybeCode) {
5598 // FIXME this drops errors on the floor.
5599 consumeError(MaybeCode.takeError());
5600 }
5601 unsigned Code = MaybeCode.get();
5602
5604 StringRef Blob;
5605 bool shouldContinue = false;
5606 Expected<unsigned> MaybeRecordType =
5607 Cursor.readRecord(Code, Record, &Blob);
5608 if (!MaybeRecordType) {
5609 // FIXME this drops errors on the floor.
5610 consumeError(MaybeRecordType.takeError());
5611 }
5612 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5613 case INPUT_FILE_HASH:
5614 break;
5615 case INPUT_FILE:
5616 bool Overridden = static_cast<bool>(Record[3]);
5617 std::string Filename = std::string(Blob);
5618 ResolveImportedPath(Filename, ModuleDir);
5619 shouldContinue = Listener.visitInputFile(
5620 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5621 break;
5622 }
5623 if (!shouldContinue)
5624 break;
5625 }
5626 break;
5627 }
5628
5629 case IMPORTS: {
5630 if (!NeedsImports)
5631 break;
5632
5633 unsigned Idx = 0, N = Record.size();
5634 while (Idx < N) {
5635 // Read information about the AST file.
5636
5637 // Skip Kind
5638 Idx++;
5639 bool IsStandardCXXModule = Record[Idx++];
5640
5641 // Skip ImportLoc
5642 Idx++;
5643
5644 // In C++20 Modules, we don't record the path to imported
5645 // modules in the BMI files.
5646 if (IsStandardCXXModule) {
5647 std::string ModuleName = ReadString(Record, Idx);
5648 Listener.visitImport(ModuleName, /*Filename=*/"");
5649 continue;
5650 }
5651
5652 // Skip Size, ModTime and Signature
5653 Idx += 1 + 1 + ASTFileSignature::size;
5654 std::string ModuleName = ReadString(Record, Idx);
5655 std::string Filename = ReadString(Record, Idx);
5656 ResolveImportedPath(Filename, ModuleDir);
5657 Listener.visitImport(ModuleName, Filename);
5658 }
5659 break;
5660 }
5661
5662 default:
5663 // No other validation to perform.
5664 break;
5665 }
5666 }
5667
5668 // Look for module file extension blocks, if requested.
5669 if (FindModuleFileExtensions) {
5670 BitstreamCursor SavedStream = Stream;
5671 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5672 bool DoneWithExtensionBlock = false;
5673 while (!DoneWithExtensionBlock) {
5674 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5675 if (!MaybeEntry) {
5676 // FIXME this drops the error.
5677 return true;
5678 }
5679 llvm::BitstreamEntry Entry = MaybeEntry.get();
5680
5681 switch (Entry.Kind) {
5682 case llvm::BitstreamEntry::SubBlock:
5683 if (llvm::Error Err = Stream.SkipBlock()) {
5684 // FIXME this drops the error on the floor.
5685 consumeError(std::move(Err));
5686 return true;
5687 }
5688 continue;
5689
5690 case llvm::BitstreamEntry::EndBlock:
5691 DoneWithExtensionBlock = true;
5692 continue;
5693
5694 case llvm::BitstreamEntry::Error:
5695 return true;
5696
5697 case llvm::BitstreamEntry::Record:
5698 break;
5699 }
5700
5701 Record.clear();
5702 StringRef Blob;
5703 Expected<unsigned> MaybeRecCode =
5704 Stream.readRecord(Entry.ID, Record, &Blob);
5705 if (!MaybeRecCode) {
5706 // FIXME this drops the error.
5707 return true;
5708 }
5709 switch (MaybeRecCode.get()) {
5710 case EXTENSION_METADATA: {
5712 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5713 return true;
5714
5715 Listener.readModuleFileExtension(Metadata);
5716 break;
5717 }
5718 }
5719 }
5720 }
5721 Stream = SavedStream;
5722 }
5723
5724 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5725 if (readUnhashedControlBlockImpl(
5726 nullptr, Bytes, Filename, ClientLoadCapabilities,
5727 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5728 ValidateDiagnosticOptions) != Success)
5729 return true;
5730
5731 return false;
5732}
5733
5735 const InMemoryModuleCache &ModuleCache,
5736 const PCHContainerReader &PCHContainerRdr,
5737 const LangOptions &LangOpts,
5738 const TargetOptions &TargetOpts,
5739 const PreprocessorOptions &PPOpts,
5740 StringRef ExistingModuleCachePath,
5741 bool RequireStrictOptionMatches) {
5742 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5743 ExistingModuleCachePath, FileMgr,
5744 RequireStrictOptionMatches);
5745 return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
5746 PCHContainerRdr,
5747 /*FindModuleFileExtensions=*/false, validator,
5748 /*ValidateDiagnosticOptions=*/true);
5749}
5750
5751llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5752 unsigned ClientLoadCapabilities) {
5753 // Enter the submodule block.
5754 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5755 return Err;
5756
5757 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5758 bool First = true;
5759 Module *CurrentModule = nullptr;
5760 RecordData Record;
5761 while (true) {
5763 F.Stream.advanceSkippingSubblocks();
5764 if (!MaybeEntry)
5765 return MaybeEntry.takeError();
5766 llvm::BitstreamEntry Entry = MaybeEntry.get();
5767
5768 switch (Entry.Kind) {
5769 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5770 case llvm::BitstreamEntry::Error:
5771 return llvm::createStringError(std::errc::illegal_byte_sequence,
5772 "malformed block record in AST file");
5773 case llvm::BitstreamEntry::EndBlock:
5774 return llvm::Error::success();
5775 case llvm::BitstreamEntry::Record:
5776 // The interesting case.
5777 break;
5778 }
5779
5780 // Read a record.
5781 StringRef Blob;
5782 Record.clear();
5783 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5784 if (!MaybeKind)
5785 return MaybeKind.takeError();
5786 unsigned Kind = MaybeKind.get();
5787
5788 if ((Kind == SUBMODULE_METADATA) != First)
5789 return llvm::createStringError(
5790 std::errc::illegal_byte_sequence,
5791 "submodule metadata record should be at beginning of block");
5792 First = false;
5793
5794 // Submodule information is only valid if we have a current module.
5795 // FIXME: Should we error on these cases?
5796 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5797 Kind != SUBMODULE_DEFINITION)
5798 continue;
5799
5800 switch (Kind) {
5801 default: // Default behavior: ignore.
5802 break;
5803
5804 case SUBMODULE_DEFINITION: {
5805 if (Record.size() < 13)
5806 return llvm::createStringError(std::errc::illegal_byte_sequence,
5807 "malformed module definition");
5808
5809 StringRef Name = Blob;
5810 unsigned Idx = 0;
5811 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5812 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5814 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
5815 bool IsFramework = Record[Idx++];
5816 bool IsExplicit = Record[Idx++];
5817 bool IsSystem = Record[Idx++];
5818 bool IsExternC = Record[Idx++];
5819 bool InferSubmodules = Record[Idx++];
5820 bool InferExplicitSubmodules = Record[Idx++];
5821 bool InferExportWildcard = Record[Idx++];
5822 bool ConfigMacrosExhaustive = Record[Idx++];
5823 bool ModuleMapIsPrivate = Record[Idx++];
5824 bool NamedModuleHasInit = Record[Idx++];
5825
5826 Module *ParentModule = nullptr;
5827 if (Parent)
5828 ParentModule = getSubmodule(Parent);
5829
5830 // Retrieve this (sub)module from the module map, creating it if
5831 // necessary.
5832 CurrentModule =
5833 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5834 .first;
5835
5836 // FIXME: Call ModMap.setInferredModuleAllowedBy()
5837
5838 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5839 if (GlobalIndex >= SubmodulesLoaded.size() ||
5840 SubmodulesLoaded[GlobalIndex])
5841 return llvm::createStringError(std::errc::invalid_argument,
5842 "too many submodules");
5843
5844 if (!ParentModule) {
5845 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
5846 // Don't emit module relocation error if we have -fno-validate-pch
5847 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5849 CurFile != F.File) {
5850 auto ConflictError =
5851 PartialDiagnostic(diag::err_module_file_conflict,
5852 ContextObj->DiagAllocator)
5853 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5854 << F.File.getName();
5855 return DiagnosticError::create(CurrentImportLoc, ConflictError);
5856 }
5857 }
5858
5859 F.DidReadTopLevelSubmodule = true;
5860 CurrentModule->setASTFile(F.File);
5861 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5862 }
5863
5864 CurrentModule->Kind = Kind;
5865 CurrentModule->DefinitionLoc = DefinitionLoc;
5866 CurrentModule->Signature = F.Signature;
5867 CurrentModule->IsFromModuleFile = true;
5868 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5869 CurrentModule->IsExternC = IsExternC;
5870 CurrentModule->InferSubmodules = InferSubmodules;
5871 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5872 CurrentModule->InferExportWildcard = InferExportWildcard;
5873 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5874 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5875 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
5876 if (DeserializationListener)
5877 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5878
5879 SubmodulesLoaded[GlobalIndex] = CurrentModule;
5880
5881 // Clear out data that will be replaced by what is in the module file.
5882 CurrentModule->LinkLibraries.clear();
5883 CurrentModule->ConfigMacros.clear();
5884 CurrentModule->UnresolvedConflicts.clear();
5885 CurrentModule->Conflicts.clear();
5886
5887 // The module is available unless it's missing a requirement; relevant
5888 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5889 // Missing headers that were present when the module was built do not
5890 // make it unavailable -- if we got this far, this must be an explicitly
5891 // imported module file.
5892 CurrentModule->Requirements.clear();
5893 CurrentModule->MissingHeaders.clear();
5894 CurrentModule->IsUnimportable =
5895 ParentModule && ParentModule->IsUnimportable;
5896 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
5897 break;
5898 }
5899
5901 // FIXME: This doesn't work for framework modules as `Filename` is the
5902 // name as written in the module file and does not include
5903 // `Headers/`, so this path will never exist.
5904 std::string Filename = std::string(Blob);
5905 ResolveImportedPath(F, Filename);
5906 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
5907 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
5908 // FIXME: NameAsWritten
5909 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
5910 }
5911 // Note that it's too late at this point to return out of date if the
5912 // name from the PCM doesn't match up with the one in the module map,
5913 // but also quite unlikely since we will have already checked the
5914 // modification time and size of the module map file itself.
5915 }
5916 break;
5917 }
5918
5919 case SUBMODULE_HEADER:
5922 // We lazily associate headers with their modules via the HeaderInfo table.
5923 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5924 // of complete filenames or remove it entirely.
5925 break;
5926
5929 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5930 // them here.
5931 break;
5932
5933 case SUBMODULE_TOPHEADER: {
5934 std::string HeaderName(Blob);
5935 ResolveImportedPath(F, HeaderName);
5936 CurrentModule->addTopHeaderFilename(HeaderName);
5937 break;
5938 }
5939
5941 // See comments in SUBMODULE_UMBRELLA_HEADER
5942 std::string Dirname = std::string(Blob);
5943 ResolveImportedPath(F, Dirname);
5944 if (auto Umbrella =
5945 PP.getFileManager().getOptionalDirectoryRef(Dirname)) {
5946 if (!CurrentModule->getUmbrellaDirAsWritten()) {
5947 // FIXME: NameAsWritten
5948 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
5949 }
5950 }
5951 break;
5952 }
5953
5954 case SUBMODULE_METADATA: {
5955 F.BaseSubmoduleID = getTotalNumSubmodules();
5957 unsigned LocalBaseSubmoduleID = Record[1];
5958 if (F.LocalNumSubmodules > 0) {
5959 // Introduce the global -> local mapping for submodules within this
5960 // module.
5961 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5962
5963 // Introduce the local -> global mapping for submodules within this
5964 // module.
5966 std::make_pair(LocalBaseSubmoduleID,
5967 F.BaseSubmoduleID - LocalBaseSubmoduleID));
5968
5969 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5970 }
5971 break;
5972 }
5973
5974 case SUBMODULE_IMPORTS:
5975 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5976 UnresolvedModuleRef Unresolved;
5977 Unresolved.File = &F;
5978 Unresolved.Mod = CurrentModule;
5979 Unresolved.ID = Record[Idx];
5980 Unresolved.Kind = UnresolvedModuleRef::Import;
5981 Unresolved.IsWildcard = false;
5982 UnresolvedModuleRefs.push_back(Unresolved);
5983 }
5984 break;
5985
5987 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5988 UnresolvedModuleRef Unresolved;
5989 Unresolved.File = &F;
5990 Unresolved.Mod = CurrentModule;
5991 Unresolved.ID = Record[Idx];
5992 Unresolved.Kind = UnresolvedModuleRef::Affecting;
5993 Unresolved.IsWildcard = false;
5994 UnresolvedModuleRefs.push_back(Unresolved);
5995 }
5996 break;
5997
5998 case SUBMODULE_EXPORTS:
5999 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6000 UnresolvedModuleRef Unresolved;
6001 Unresolved.File = &F;
6002 Unresolved.Mod = CurrentModule;
6003 Unresolved.ID = Record[Idx];
6004 Unresolved.Kind = UnresolvedModuleRef::Export;
6005 Unresolved.IsWildcard = Record[Idx + 1];
6006 UnresolvedModuleRefs.push_back(Unresolved);
6007 }
6008
6009 // Once we've loaded the set of exports, there's no reason to keep
6010 // the parsed, unresolved exports around.
6011 CurrentModule->UnresolvedExports.clear();
6012 break;
6013
6014 case SUBMODULE_REQUIRES:
6015 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6016 PP.getTargetInfo());
6017 break;
6018
6020 ModMap.resolveLinkAsDependencies(CurrentModule);
6021 CurrentModule->LinkLibraries.push_back(
6022 Module::LinkLibrary(std::string(Blob), Record[0]));
6023 break;
6024
6026 CurrentModule->ConfigMacros.push_back(Blob.str());
6027 break;
6028
6029 case SUBMODULE_CONFLICT: {
6030 UnresolvedModuleRef Unresolved;
6031 Unresolved.File = &F;
6032 Unresolved.Mod = CurrentModule;
6033 Unresolved.ID = Record[0];
6034 Unresolved.Kind = UnresolvedModuleRef::Conflict;
6035 Unresolved.IsWildcard = false;
6036 Unresolved.String = Blob;
6037 UnresolvedModuleRefs.push_back(Unresolved);
6038 break;
6039 }
6040
6042 if (!ContextObj)
6043 break;
6045 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6046 Inits.push_back(ReadDeclID(F, Record, I));
6047 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6048 break;
6049 }
6050
6052 CurrentModule->ExportAsModule = Blob.str();
6053 ModMap.addLinkAsDependency(CurrentModule);
6054 break;
6055 }
6056 }
6057}
6058
6059/// Parse the record that corresponds to a LangOptions data
6060/// structure.
6061///
6062/// This routine parses the language options from the AST file and then gives
6063/// them to the AST listener if one is set.
6064///
6065/// \returns true if the listener deems the file unacceptable, false otherwise.
6066bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6067 StringRef ModuleFilename, bool Complain,
6068 ASTReaderListener &Listener,
6069 bool AllowCompatibleDifferences) {
6070 LangOptions LangOpts;
6071 unsigned Idx = 0;
6072#define LANGOPT(Name, Bits, Default, Description) \
6073 LangOpts.Name = Record[Idx++];
6074#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
6075 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6076#include "clang/Basic/LangOptions.def"
6077#define SANITIZER(NAME, ID) \
6078 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6079#include "clang/Basic/Sanitizers.def"
6080
6081 for (unsigned N = Record[Idx++]; N; --N)
6082 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6083
6084 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6085 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6086 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6087
6088 LangOpts.CurrentModule = ReadString(Record, Idx);
6089
6090 // Comment options.
6091 for (unsigned N = Record[Idx++]; N; --N) {
6092 LangOpts.CommentOpts.BlockCommandNames.push_back(
6093 ReadString(Record, Idx));
6094 }
6095 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6096
6097 // OpenMP offloading options.
6098 for (unsigned N = Record[Idx++]; N; --N) {
6099 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6100 }
6101
6102 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6103
6104 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6105 AllowCompatibleDifferences);
6106}
6107
6108bool ASTReader::ParseTargetOptions(const RecordData &Record,
6109 StringRef ModuleFilename, bool Complain,
6110 ASTReaderListener &Listener,
6111 bool AllowCompatibleDifferences) {
6112 unsigned Idx = 0;
6113 TargetOptions TargetOpts;
6114 TargetOpts.Triple = ReadString(Record, Idx);
6115 TargetOpts.CPU = ReadString(Record, Idx);
6116 TargetOpts.TuneCPU = ReadString(Record, Idx);
6117 TargetOpts.ABI = ReadString(Record, Idx);
6118 for (unsigned N = Record[Idx++]; N; --N) {
6119 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6120 }
6121 for (unsigned N = Record[Idx++]; N; --N) {
6122 TargetOpts.Features.push_back(ReadString(Record, Idx));
6123 }
6124
6125 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6126 AllowCompatibleDifferences);
6127}
6128
6129bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6130 StringRef ModuleFilename, bool Complain,
6131 ASTReaderListener &Listener) {
6133 unsigned Idx = 0;
6134#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
6135#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6136 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
6137#include "clang/Basic/DiagnosticOptions.def"
6138
6139 for (unsigned N = Record[Idx++]; N; --N)
6140 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
6141 for (unsigned N = Record[Idx++]; N; --N)
6142 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
6143
6144 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6145}
6146
6147bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6148 ASTReaderListener &Listener) {
6149 FileSystemOptions FSOpts;
6150 unsigned Idx = 0;
6151 FSOpts.WorkingDir = ReadString(Record, Idx);
6152 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6153}
6154
6155bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6156 StringRef ModuleFilename,
6157 bool Complain,
6158 ASTReaderListener &Listener) {
6159 HeaderSearchOptions HSOpts;
6160 unsigned Idx = 0;
6161 HSOpts.Sysroot = ReadString(Record, Idx);
6162
6163 HSOpts.ResourceDir = ReadString(Record, Idx);
6164 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6165 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6166 HSOpts.DisableModuleHash = Record[Idx++];
6167 HSOpts.ImplicitModuleMaps = Record[Idx++];
6168 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6169 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6170 HSOpts.UseBuiltinIncludes = Record[Idx++];
6171 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6172 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6173 HSOpts.UseLibcxx = Record[Idx++];
6174 std::string SpecificModuleCachePath = ReadString(Record, Idx);
6175
6176 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename,
6177 SpecificModuleCachePath, Complain);
6178}
6179
6180bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6181 ASTReaderListener &Listener) {
6182 HeaderSearchOptions HSOpts;
6183 unsigned Idx = 0;
6184
6185 // Include entries.
6186 for (unsigned N = Record[Idx++]; N; --N) {
6187 std::string Path = ReadString(Record, Idx);
6189 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6190 bool IsFramework = Record[Idx++];
6191 bool IgnoreSysRoot = Record[Idx++];
6192 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6193 IgnoreSysRoot);
6194 }
6195
6196 // System header prefixes.
6197 for (unsigned N = Record[Idx++]; N; --N) {
6198 std::string Prefix = ReadString(Record, Idx);
6199 bool IsSystemHeader = Record[Idx++];
6200 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6201 }
6202
6203 // VFS overlay files.
6204 for (unsigned N = Record[Idx++]; N; --N) {
6205 std::string VFSOverlayFile = ReadString(Record, Idx);
6206 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6207 }
6208
6209 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6210}
6211
6212bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6213 StringRef ModuleFilename,
6214 bool Complain,
6215 ASTReaderListener &Listener,
6216 std::string &SuggestedPredefines) {
6217 PreprocessorOptions PPOpts;
6218 unsigned Idx = 0;
6219
6220 // Macro definitions/undefs
6221 bool ReadMacros = Record[Idx++];
6222 if (ReadMacros) {
6223 for (unsigned N = Record[Idx++]; N; --N) {
6224 std::string Macro = ReadString(Record, Idx);
6225 bool IsUndef = Record[Idx++];
6226 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6227 }
6228 }
6229
6230 // Includes
6231 for (unsigned N = Record[Idx++]; N; --N) {
6232 PPOpts.Includes.push_back(ReadString(Record, Idx));
6233 }
6234
6235 // Macro Includes
6236 for (unsigned N = Record[Idx++]; N; --N) {
6237 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6238 }
6239
6240 PPOpts.UsePredefines = Record[Idx++];
6241 PPOpts.DetailedRecord = Record[Idx++];
6242 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6244 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6245 SuggestedPredefines.clear();
6246 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6247 Complain, SuggestedPredefines);
6248}
6249
6250std::pair<ModuleFile *, unsigned>
6251ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6252 GlobalPreprocessedEntityMapType::iterator
6253 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6254 assert(I != GlobalPreprocessedEntityMap.end() &&
6255 "Corrupted global preprocessed entity map");
6256 ModuleFile *M = I->second;
6257 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6258 return std::make_pair(M, LocalIndex);
6259}
6260
6261llvm::iterator_range<PreprocessingRecord::iterator>
6262ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6263 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6264 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6266
6267 return llvm::make_range(PreprocessingRecord::iterator(),
6269}
6270
6271bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6272 unsigned int ClientLoadCapabilities) {
6273 return ClientLoadCapabilities & ARR_OutOfDate &&
6274 !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
6275}
6276
6277llvm::iterator_range<ASTReader::ModuleDeclIterator>
6279 return llvm::make_range(
6280 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6281 ModuleDeclIterator(this, &Mod,
6283}
6284
6286 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6287 assert(I != GlobalSkippedRangeMap.end() &&
6288 "Corrupted global skipped range map");
6289 ModuleFile *M = I->second;
6290 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6291 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6292 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6293 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6294 ReadSourceLocation(*M, RawRange.getEnd()));
6295 assert(Range.isValid());
6296 return Range;
6297}
6298
6300 PreprocessedEntityID PPID = Index+1;
6301 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6302 ModuleFile &M = *PPInfo.first;
6303 unsigned LocalIndex = PPInfo.second;
6304 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6305
6306 if (!PP.getPreprocessingRecord()) {
6307 Error("no preprocessing record");
6308 return nullptr;
6309 }
6310
6312 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6313 M.MacroOffsetsBase + PPOffs.getOffset())) {
6314 Error(std::move(Err));
6315 return nullptr;
6316 }
6317
6319 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6320 if (!MaybeEntry) {
6321 Error(MaybeEntry.takeError());
6322 return nullptr;
6323 }
6324 llvm::BitstreamEntry Entry = MaybeEntry.get();
6325
6326 if (Entry.Kind != llvm::BitstreamEntry::Record)
6327 return nullptr;
6328
6329 // Read the record.
6330 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6331 ReadSourceLocation(M, PPOffs.getEnd()));
6332 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6333 StringRef Blob;
6335 Expected<unsigned> MaybeRecType =
6336 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6337 if (!MaybeRecType) {
6338 Error(MaybeRecType.takeError());
6339 return nullptr;
6340 }
6341 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6342 case PPD_MACRO_EXPANSION: {
6343 bool isBuiltin = Record[0];
6344 IdentifierInfo *Name = nullptr;
6345 MacroDefinitionRecord *Def = nullptr;
6346 if (isBuiltin)
6347 Name = getLocalIdentifier(M, Record[1]);
6348 else {
6349 PreprocessedEntityID GlobalID =
6350 getGlobalPreprocessedEntityID(M, Record[1]);
6351 Def = cast<MacroDefinitionRecord>(
6352 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6353 }
6354
6355 MacroExpansion *ME;
6356 if (isBuiltin)
6357 ME = new (PPRec) MacroExpansion(Name, Range);
6358 else
6359 ME = new (PPRec) MacroExpansion(Def, Range);
6360
6361 return ME;
6362 }
6363
6364 case PPD_MACRO_DEFINITION: {
6365 // Decode the identifier info and then check again; if the macro is
6366 // still defined and associated with the identifier,
6367 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6368 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6369
6370 if (DeserializationListener)
6371 DeserializationListener->MacroDefinitionRead(PPID, MD);
6372
6373 return MD;
6374 }
6375
6377 const char *FullFileNameStart = Blob.data() + Record[0];
6378 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6380 if (!FullFileName.empty())
6381 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6382
6383 // FIXME: Stable encoding
6385 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6387 = new (PPRec) InclusionDirective(PPRec, Kind,
6388 StringRef(Blob.data(), Record[0]),
6389 Record[1], Record[3],
6390 File,
6391 Range);
6392 return ID;
6393 }
6394 }
6395
6396 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6397}
6398
6399/// Find the next module that contains entities and return the ID
6400/// of the first entry.
6401///
6402/// \param SLocMapI points at a chunk of a module that contains no
6403/// preprocessed entities or the entities it contains are not the ones we are
6404/// looking for.
6405PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6406 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6407 ++SLocMapI;
6408 for (GlobalSLocOffsetMapType::const_iterator
6409 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6410 ModuleFile &M = *SLocMapI->second;
6412 return M.BasePreprocessedEntityID;
6413 }
6414
6415 return getTotalNumPreprocessedEntities();
6416}
6417
6418namespace {
6419
6420struct PPEntityComp {
6421 const ASTReader &Reader;
6422 ModuleFile &M;
6423
6424 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6425
6426 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6427 SourceLocation LHS = getLoc(L);
6428 SourceLocation RHS = getLoc(R);
6429 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6430 }
6431
6432 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6433 SourceLocation LHS = getLoc(L);
6434 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6435 }
6436
6437 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6438 SourceLocation RHS = getLoc(R);
6439 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6440 }
6441
6442 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6443 return Reader.ReadSourceLocation(M, PPE.getBegin());
6444 }
6445};
6446
6447} // namespace
6448
6449PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6450 bool EndsAfter) const {
6451 if (SourceMgr.isLocalSourceLocation(Loc))
6452 return getTotalNumPreprocessedEntities();
6453
6454 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6455 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6456 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6457 "Corrupted global sloc offset map");
6458
6459 if (SLocMapI->second->NumPreprocessedEntities == 0)
6460 return findNextPreprocessedEntity(SLocMapI);
6461
6462 ModuleFile &M = *SLocMapI->second;
6463
6464 using pp_iterator = const PPEntityOffset *;
6465
6466 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6467 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6468
6469 size_t Count = M.NumPreprocessedEntities;
6470 size_t Half;
6471 pp_iterator First = pp_begin;
6472 pp_iterator PPI;
6473
6474 if (EndsAfter) {
6475 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6476 PPEntityComp(*this, M));
6477 } else {
6478 // Do a binary search manually instead of using std::lower_bound because
6479 // The end locations of entities may be unordered (when a macro expansion
6480 // is inside another macro argument), but for this case it is not important
6481 // whether we get the first macro expansion or its containing macro.
6482 while (Count > 0) {
6483 Half = Count / 2;
6484 PPI = First;
6485 std::advance(PPI, Half);
6486 if (SourceMgr.isBeforeInTranslationUnit(
6487 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
6488 First = PPI;
6489 ++First;
6490 Count = Count - Half - 1;
6491 } else
6492 Count = Half;
6493 }
6494 }
6495
6496 if (PPI == pp_end)
6497 return findNextPreprocessedEntity(SLocMapI);
6498
6499 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6500}
6501
6502/// Returns a pair of [Begin, End) indices of preallocated
6503/// preprocessed entities that \arg Range encompasses.
6504std::pair<unsigned, unsigned>
6506 if (Range.isInvalid())
6507 return std::make_pair(0,0);
6508 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6509
6510 PreprocessedEntityID BeginID =
6511 findPreprocessedEntity(Range.getBegin(), false);
6512 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6513 return std::make_pair(BeginID, EndID);
6514}
6515
6516/// Optionally returns true or false if the preallocated preprocessed
6517/// entity with index \arg Index came from file \arg FID.
6518std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6519 FileID FID) {
6520 if (FID.isInvalid())
6521 return false;
6522
6523 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6524 ModuleFile &M = *PPInfo.first;
6525 unsigned LocalIndex = PPInfo.second;
6526 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6527
6528 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
6529 if (Loc.isInvalid())
6530 return false;
6531
6532 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6533 return true;
6534 else
6535 return false;
6536}
6537
6538namespace {
6539
6540 /// Visitor used to search for information about a header file.
6541 class HeaderFileInfoVisitor {
6542 FileEntryRef FE;
6543 std::optional<HeaderFileInfo> HFI;
6544
6545 public:
6546 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
6547
6548 bool operator()(ModuleFile &M) {
6551 if (!Table)
6552 return false;
6553
6554 // Look in the on-disk hash table for an entry for this file name.
6555 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6556 if (Pos == Table->end())
6557 return false;
6558
6559 HFI = *Pos;
6560 return true;
6561 }
6562
6563 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6564 };
6565
6566} // namespace
6567
6569 HeaderFileInfoVisitor Visitor(FE);
6570 ModuleMgr.visit(Visitor);
6571 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6572 return *HFI;
6573
6574 return HeaderFileInfo();
6575}
6576
6578 using DiagState = DiagnosticsEngine::DiagState;
6580
6581 for (ModuleFile &F : ModuleMgr) {
6582 unsigned Idx = 0;
6583 auto &Record = F.PragmaDiagMappings;
6584 if (Record.empty())
6585 continue;
6586
6587 DiagStates.clear();
6588
6589 auto ReadDiagState = [&](const DiagState &BasedOn,
6590 bool IncludeNonPragmaStates) {
6591 unsigned BackrefID = Record[Idx++];
6592 if (BackrefID != 0)
6593 return DiagStates[BackrefID - 1];
6594
6595 // A new DiagState was created here.
6596 Diag.DiagStates.push_back(BasedOn);
6597 DiagState *NewState = &Diag.DiagStates.back();
6598 DiagStates.push_back(NewState);
6599 unsigned Size = Record[Idx++];
6600 assert(Idx + Size * 2 <= Record.size() &&
6601 "Invalid data, not enough diag/map pairs");
6602 while (Size--) {
6603 unsigned DiagID = Record[Idx++];
6604 DiagnosticMapping NewMapping =
6606 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6607 continue;
6608
6609 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6610
6611 // If this mapping was specified as a warning but the severity was
6612 // upgraded due to diagnostic settings, simulate the current diagnostic
6613 // settings (and use a warning).
6614 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6616 NewMapping.setUpgradedFromWarning(false);
6617 }
6618
6619 Mapping = NewMapping;
6620 }
6621 return NewState;
6622 };
6623
6624 // Read the first state.
6625 DiagState *FirstState;
6626 if (F.Kind == MK_ImplicitModule) {
6627 // Implicitly-built modules are reused with different diagnostic
6628 // settings. Use the initial diagnostic state from Diag to simulate this
6629 // compilation's diagnostic settings.
6630 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6631 DiagStates.push_back(FirstState);
6632
6633 // Skip the initial diagnostic state from the serialized module.
6634 assert(Record[1] == 0 &&
6635 "Invalid data, unexpected backref in initial state");
6636 Idx = 3 + Record[2] * 2;
6637 assert(Idx < Record.size() &&
6638 "Invalid data, not enough state change pairs in initial state");
6639 } else if (F.isModule()) {
6640 // For an explicit module, preserve the flags from the module build
6641 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6642 // -Wblah flags.
6643 unsigned Flags = Record[Idx++];
6644 DiagState Initial;
6645 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6646 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6647 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6648 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6649 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6650 Initial.ExtBehavior = (diag::Severity)Flags;
6651 FirstState = ReadDiagState(Initial, true);
6652
6653 assert(F.OriginalSourceFileID.isValid());
6654
6655 // Set up the root buffer of the module to start with the initial
6656 // diagnostic state of the module itself, to cover files that contain no
6657 // explicit transitions (for which we did not serialize anything).
6658 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6659 .StateTransitions.push_back({FirstState, 0});
6660 } else {
6661 // For prefix ASTs, start with whatever the user configured on the
6662 // command line.
6663 Idx++; // Skip flags.
6664 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
6665 }
6666
6667 // Read the state transitions.
6668 unsigned NumLocations = Record[Idx++];
6669 while (NumLocations--) {
6670 assert(Idx < Record.size() &&
6671 "Invalid data, missing pragma diagnostic states");
6672 FileID FID = ReadFileID(F, Record, Idx);
6673 assert(FID.isValid() && "invalid FileID for transition");
6674 unsigned Transitions = Record[Idx++];
6675
6676 // Note that we don't need to set up Parent/ParentOffset here, because
6677 // we won't be changing the diagnostic state within imported FileIDs
6678 // (other than perhaps appending to the main source file, which has no
6679 // parent).
6680 auto &F = Diag.DiagStatesByLoc.Files[FID];
6681 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6682 for (unsigned I = 0; I != Transitions; ++I) {
6683 unsigned Offset = Record[Idx++];
6684 auto *State = ReadDiagState(*FirstState, false);
6685 F.StateTransitions.push_back({State, Offset});
6686 }
6687 }
6688
6689 // Read the final state.
6690 assert(Idx < Record.size() &&
6691 "Invalid data, missing final pragma diagnostic state");
6692 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
6693 auto *CurState = ReadDiagState(*FirstState, false);
6694
6695 if (!F.isModule()) {
6696 Diag.DiagStatesByLoc.CurDiagState = CurState;
6697 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6698
6699 // Preserve the property that the imaginary root file describes the
6700 // current state.
6701 FileID NullFile;
6702 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6703 if (T.empty())
6704 T.push_back({CurState, 0});
6705 else
6706 T[0].State = CurState;
6707 }
6708
6709 // Don't try to read these mappings again.
6710 Record.clear();
6711 }
6712}
6713
6714/// Get the correct cursor and offset for loading a type.
6715ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
6716 auto [M, Index] = translateTypeIDToIndex(ID);
6717 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
6719}
6720
6721static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6722 switch (code) {
6723#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6724 case TYPE_##CODE_ID: return Type::CLASS_ID;
6725#include "clang/Serialization/TypeBitCodes.def"
6726 default:
6727 return std::nullopt;
6728 }
6729}
6730
6731/// Read and return the type with the given index..
6732///
6733/// The index is the type ID, shifted and minus the number of predefs. This
6734/// routine actually reads the record corresponding to the type at the given
6735/// location. It is a helper routine for GetType, which deals with reading type
6736/// IDs.
6737QualType ASTReader::readTypeRecord(TypeID ID) {
6738 assert(ContextObj && "reading type with no AST context");
6739 ASTContext &Context = *ContextObj;
6740 RecordLocation Loc = TypeCursorForIndex(ID);
6741 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6742
6743 // Keep track of where we are in the stream, then jump back there
6744 // after reading this type.
6745 SavedStreamPosition SavedPosition(DeclsCursor);
6746
6747 ReadingKindTracker ReadingKind(Read_Type, *this);
6748
6749 // Note that we are loading a type record.
6750 Deserializing AType(this);
6751
6752 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6753 Error(std::move(Err));
6754 return QualType();
6755 }
6756 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6757 if (!RawCode) {
6758 Error(RawCode.takeError());
6759 return QualType();
6760 }
6761
6762 ASTRecordReader Record(*this, *Loc.F);
6763 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6764 if (!Code) {
6765 Error(Code.takeError());
6766 return QualType();
6767 }
6768 if (Code.get() == TYPE_EXT_QUAL) {
6769 QualType baseType = Record.readQualType();
6770 Qualifiers quals = Record.readQualifiers();
6771 return Context.getQualifiedType(baseType, quals);
6772 }
6773
6774 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6775 if (!maybeClass) {
6776 Error("Unexpected code for type");
6777 return QualType();
6778 }
6779
6781 return TypeReader.read(*maybeClass);
6782}
6783
6784namespace clang {
6785
6786class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6788
6789 ASTRecordReader &Reader;
6790 LocSeq *Seq;
6791
6792 SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
6793 SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
6794
6795 TypeSourceInfo *GetTypeSourceInfo() {
6796 return Reader.readTypeSourceInfo();
6797 }
6798
6799 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6800 return Reader.readNestedNameSpecifierLoc();
6801 }
6802
6803 Attr *ReadAttr() {
6804 return Reader.readAttr();
6805 }
6806
6807public:
6809 : Reader(Reader), Seq(Seq) {}
6810
6811 // We want compile-time assurance that we've enumerated all of
6812 // these, so unfortunately we have to declare them first, then
6813 // define them out-of-line.
6814#define ABSTRACT_TYPELOC(CLASS, PARENT)
6815#define TYPELOC(CLASS, PARENT) \
6816 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6817#include "clang/AST/TypeLocNodes.def"
6818
6819 void VisitFunctionTypeLoc(FunctionTypeLoc);
6820 void VisitArrayTypeLoc(ArrayTypeLoc);
6821};
6822
6823} // namespace clang
6824
6825void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6826 // nothing to do
6827}
6828
6829void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6830 TL.setBuiltinLoc(readSourceLocation());
6831 if (TL.needsExtraLocalData()) {
6832 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6833 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6834 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6835 TL.setModeAttr(Reader.readInt());
6836 }
6837}
6838
6839void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6840 TL.setNameLoc(readSourceLocation());
6841}
6842
6843void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6844 TL.setStarLoc(readSourceLocation());
6845}
6846
6847void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6848 // nothing to do
6849}
6850
6851void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6852 // nothing to do
6853}
6854
6855void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6856 // nothing to do
6857}
6858
6859void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6860 TL.setExpansionLoc(readSourceLocation());
6861}
6862
6863void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6864 TL.setCaretLoc(readSourceLocation());
6865}
6866
6867void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6868 TL.setAmpLoc(readSourceLocation());
6869}
6870
6871void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6872 TL.setAmpAmpLoc(readSourceLocation());
6873}
6874
6875void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6876 TL.setStarLoc(readSourceLocation());
6877 TL.setClassTInfo(GetTypeSourceInfo());
6878}
6879
6881 TL.setLBracketLoc(readSourceLocation());
6882 TL.setRBracketLoc(readSourceLocation());
6883 if (Reader.readBool())
6884 TL.setSizeExpr(Reader.readExpr());
6885 else
6886 TL.setSizeExpr(nullptr);
6887}
6888
6889void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6890 VisitArrayTypeLoc(TL);
6891}
6892
6893void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6894 VisitArrayTypeLoc(TL);
6895}
6896
6897void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6898 VisitArrayTypeLoc(TL);
6899}
6900
6901void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6903 VisitArrayTypeLoc(TL);
6904}
6905
6906void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6908
6909 TL.setAttrNameLoc(readSourceLocation());
6910 TL.setAttrOperandParensRange(readSourceRange());
6911 TL.setAttrExprOperand(Reader.readExpr());
6912}
6913
6914void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6916 TL.setNameLoc(readSourceLocation());
6917}
6918
6919void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6920 TL.setNameLoc(readSourceLocation());
6921}
6922
6923void TypeLocReader::VisitDependentVectorTypeLoc(
6925 TL.setNameLoc(readSourceLocation());
6926}
6927
6928void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6929 TL.setNameLoc(readSourceLocation());
6930}
6931
6932void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6933 TL.setAttrNameLoc(readSourceLocation());
6934 TL.setAttrOperandParensRange(readSourceRange());
6935 TL.setAttrRowOperand(Reader.readExpr());
6936 TL.setAttrColumnOperand(Reader.readExpr());
6937}
6938
6939void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6941 TL.setAttrNameLoc(readSourceLocation());
6942 TL.setAttrOperandParensRange(readSourceRange());
6943 TL.setAttrRowOperand(Reader.readExpr());
6944 TL.setAttrColumnOperand(Reader.readExpr());
6945}
6946
6948 TL.setLocalRangeBegin(readSourceLocation());
6949 TL.setLParenLoc(readSourceLocation());
6950 TL.setRParenLoc(readSourceLocation());
6951 TL.setExceptionSpecRange(readSourceRange());
6952 TL.setLocalRangeEnd(readSourceLocation());
6953 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6954 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6955 }
6956}
6957
6958void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6959 VisitFunctionTypeLoc(TL);
6960}
6961
6962void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6963 VisitFunctionTypeLoc(TL);
6964}
6965
6966void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6967 TL.setNameLoc(readSourceLocation());
6968}
6969
6970void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
6971 TL.setNameLoc(readSourceLocation());
6972}
6973
6974void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6975 TL.setNameLoc(readSourceLocation());
6976}
6977
6978void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6979 TL.setTypeofLoc(readSourceLocation());
6980 TL.setLParenLoc(readSourceLocation());
6981 TL.setRParenLoc(readSourceLocation());
6982}
6983
6984void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6985 TL.setTypeofLoc(readSourceLocation());
6986 TL.setLParenLoc(readSourceLocation());
6987 TL.setRParenLoc(readSourceLocation());
6988 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
6989}
6990
6991void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6992 TL.setDecltypeLoc(readSourceLocation());
6993 TL.setRParenLoc(readSourceLocation());
6994}
6995
6996void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6997 TL.setEllipsisLoc(readSourceLocation());
6998}
6999
7000void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7001 TL.setKWLoc(readSourceLocation());
7002 TL.setLParenLoc(readSourceLocation());
7003 TL.setRParenLoc(readSourceLocation());
7004 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7005}
7006
7008 auto NNS = readNestedNameSpecifierLoc();
7009 auto TemplateKWLoc = readSourceLocation();
7010 auto ConceptNameLoc = readDeclarationNameInfo();
7011 auto FoundDecl = readDeclAs<NamedDecl>();
7012 auto NamedConcept = readDeclAs<ConceptDecl>();
7013 auto *CR = ConceptReference::Create(
7014 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7015 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7016 return CR;
7017}
7018
7019void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7020 TL.setNameLoc(readSourceLocation());
7021 if (Reader.readBool())
7022 TL.setConceptReference(Reader.readConceptReference());
7023 if (Reader.readBool())
7024 TL.setRParenLoc(readSourceLocation());
7025}
7026
7027void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7029 TL.setTemplateNameLoc(readSourceLocation());
7030}
7031
7032void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7033 TL.setNameLoc(readSourceLocation());
7034}
7035
7036void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
7037 TL.setNameLoc(readSourceLocation());
7038}
7039
7040void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7041 TL.setAttr(ReadAttr());
7042}
7043
7044void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7045 // Nothing to do
7046}
7047
7048void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7049 // Nothing to do.
7050}
7051
7052void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7053 TL.setNameLoc(readSourceLocation());
7054}
7055
7056void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7058 TL.setNameLoc(readSourceLocation());
7059}
7060
7061void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7063 TL.setNameLoc(readSourceLocation());
7064}
7065
7066void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7068 TL.setTemplateKeywordLoc(readSourceLocation());
7069 TL.setTemplateNameLoc(readSourceLocation());
7070 TL.setLAngleLoc(readSourceLocation());
7071 TL.setRAngleLoc(readSourceLocation());
7072 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
7073 TL.setArgLocInfo(i,
7074 Reader.readTemplateArgumentLocInfo(
7075 TL.getTypePtr()->template_arguments()[i].getKind()));
7076}
7077
7078void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7079 TL.setLParenLoc(readSourceLocation());
7080 TL.setRParenLoc(readSourceLocation());
7081}
7082
7083void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
7084 TL.setElaboratedKeywordLoc(readSourceLocation());
7085 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7086}
7087
7088void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7089 TL.setNameLoc(readSourceLocation());
7090}
7091
7092void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7093 TL.setElaboratedKeywordLoc(readSourceLocation());
7094 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7095 TL.setNameLoc(readSourceLocation());
7096}
7097
7098void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7100 TL.setElaboratedKeywordLoc(readSourceLocation());
7101 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7102 TL.setTemplateKeywordLoc(readSourceLocation());
7103 TL.setTemplateNameLoc(readSourceLocation());
7104 TL.setLAngleLoc(readSourceLocation());
7105 TL.setRAngleLoc(readSourceLocation());
7106 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7107 TL.setArgLocInfo(I,
7108 Reader.readTemplateArgumentLocInfo(
7109 TL.getTypePtr()->template_arguments()[I].getKind()));
7110}
7111
7112void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7113 TL.setEllipsisLoc(readSourceLocation());
7114}
7115
7116void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7117 TL.setNameLoc(readSourceLocation());
7118 TL.setNameEndLoc(readSourceLocation());
7119}
7120
7121void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7122 if (TL.getNumProtocols()) {
7123 TL.setProtocolLAngleLoc(readSourceLocation());
7124 TL.setProtocolRAngleLoc(readSourceLocation());
7125 }
7126 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7127 TL.setProtocolLoc(i, readSourceLocation());
7128}
7129
7130void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7131 TL.setHasBaseTypeAsWritten(Reader.readBool());
7132 TL.setTypeArgsLAngleLoc(readSourceLocation());
7133 TL.setTypeArgsRAngleLoc(readSourceLocation());
7134 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7135 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7136 TL.setProtocolLAngleLoc(readSourceLocation());
7137 TL.setProtocolRAngleLoc(readSourceLocation());
7138 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7139 TL.setProtocolLoc(i, readSourceLocation());
7140}
7141
7142void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7143 TL.setStarLoc(readSourceLocation());
7144}
7145
7146void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7147 TL.setKWLoc(readSourceLocation());
7148 TL.setLParenLoc(readSourceLocation());
7149 TL.setRParenLoc(readSourceLocation());
7150}
7151
7152void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7153 TL.setKWLoc(readSourceLocation());
7154}
7155
7156void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7157 TL.setNameLoc(readSourceLocation());
7158}
7159void TypeLocReader::VisitDependentBitIntTypeLoc(
7161 TL.setNameLoc(readSourceLocation());
7162}
7163
7165 LocSeq::State Seq(ParentSeq);
7166 TypeLocReader TLR(*this, Seq);
7167 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7168 TLR.Visit(TL);
7169}
7170
7172 QualType InfoTy = readType();
7173 if (InfoTy.isNull())
7174 return nullptr;
7175
7176 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7177 readTypeLoc(TInfo->getTypeLoc());
7178 return TInfo;
7179}
7180
7182 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7183}
7184
7186 return ID >> 32;
7187}
7188
7190 // We don't need to erase the higher bits since if these bits are not 0,
7191 // it must be larger than NUM_PREDEF_TYPE_IDS.
7193}
7194
7195std::pair<ModuleFile *, unsigned>
7196ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7197 assert(!isPredefinedType(ID) &&
7198 "Predefined type shouldn't be in TypesLoaded");
7199 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7200 assert(ModuleFileIndex && "Untranslated Local Decl?");
7201
7202 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7203 assert(OwningModuleFile &&
7204 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7205
7206 return {OwningModuleFile,
7207 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7208}
7209
7211 assert(ContextObj && "reading type with no AST context");
7212 ASTContext &Context = *ContextObj;
7213
7214 unsigned FastQuals = ID & Qualifiers::FastMask;
7215
7216 if (isPredefinedType(ID)) {
7217 QualType T;
7218 unsigned Index = getIndexForTypeID(ID);
7219 switch ((PredefinedTypeIDs)Index) {
7221 // We should never use this one.
7222 llvm_unreachable("Invalid predefined type");
7223 break;
7225 return QualType();
7227 T = Context.VoidTy;
7228 break;
7230 T = Context.BoolTy;
7231 break;
7234 // FIXME: Check that the signedness of CharTy is correct!
7235 T = Context.CharTy;
7236 break;
7238 T = Context.UnsignedCharTy;
7239 break;
7241 T = Context.UnsignedShortTy;
7242 break;
7244 T = Context.UnsignedIntTy;
7245 break;
7247 T = Context.UnsignedLongTy;
7248 break;
7250 T = Context.UnsignedLongLongTy;
7251 break;
7253 T = Context.UnsignedInt128Ty;
7254 break;
7256 T = Context.SignedCharTy;
7257 break;
7259 T = Context.WCharTy;
7260 break;
7262 T = Context.ShortTy;
7263 break;
7264 case PREDEF_TYPE_INT_ID:
7265 T = Context.IntTy;
7266 break;
7268 T = Context.LongTy;
7269 break;
7271 T = Context.LongLongTy;
7272 break;
7274 T = Context.Int128Ty;
7275 break;
7277 T = Context.BFloat16Ty;
7278 break;
7280 T = Context.HalfTy;
7281 break;
7283 T = Context.FloatTy;
7284 break;
7286 T = Context.DoubleTy;
7287 break;
7289 T = Context.LongDoubleTy;
7290 break;
7292 T = Context.ShortAccumTy;
7293 break;
7295 T = Context.AccumTy;
7296 break;
7298 T = Context.LongAccumTy;
7299 break;
7301 T = Context.UnsignedShortAccumTy;
7302 break;
7304 T = Context.UnsignedAccumTy;
7305 break;
7307 T = Context.UnsignedLongAccumTy;
7308 break;
7310 T = Context.ShortFractTy;
7311 break;
7313 T = Context.FractTy;
7314 break;
7316 T = Context.LongFractTy;
7317 break;
7319 T = Context.UnsignedShortFractTy;
7320 break;
7322 T = Context.UnsignedFractTy;
7323 break;
7325 T = Context.UnsignedLongFractTy;
7326 break;
7328 T = Context.SatShortAccumTy;
7329 break;
7331 T = Context.SatAccumTy;
7332 break;
7334 T = Context.SatLongAccumTy;
7335 break;
7337 T = Context.SatUnsignedShortAccumTy;
7338 break;
7340 T = Context.SatUnsignedAccumTy;
7341 break;
7343 T = Context.SatUnsignedLongAccumTy;
7344 break;
7346 T = Context.SatShortFractTy;
7347 break;
7349 T = Context.SatFractTy;
7350 break;
7352 T = Context.SatLongFractTy;
7353 break;
7355 T = Context.SatUnsignedShortFractTy;
7356 break;
7358 T = Context.SatUnsignedFractTy;
7359 break;
7361 T = Context.SatUnsignedLongFractTy;
7362 break;
7364 T = Context.Float16Ty;
7365 break;
7367 T = Context.Float128Ty;
7368 break;
7370 T = Context.Ibm128Ty;
7371 break;
7373 T = Context.OverloadTy;
7374 break;
7376 T = Context.UnresolvedTemplateTy;
7377 break;
7379 T = Context.BoundMemberTy;
7380 break;
7382 T = Context.PseudoObjectTy;
7383 break;
7385 T = Context.DependentTy;
7386 break;
7388 T = Context.UnknownAnyTy;
7389 break;
7391 T = Context.NullPtrTy;
7392 break;
7394 T = Context.Char8Ty;
7395 break;
7397 T = Context.Char16Ty;
7398 break;
7400 T = Context.Char32Ty;
7401 break;
7403 T = Context.ObjCBuiltinIdTy;
7404 break;
7406 T = Context.ObjCBuiltinClassTy;
7407 break;
7409 T = Context.ObjCBuiltinSelTy;
7410 break;
7411#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7412 case PREDEF_TYPE_##Id##_ID: \
7413 T = Context.SingletonId; \
7414 break;
7415#include "clang/Basic/OpenCLImageTypes.def"
7416#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7417 case PREDEF_TYPE_##Id##_ID: \
7418 T = Context.Id##Ty; \
7419 break;
7420#include "clang/Basic/OpenCLExtensionTypes.def"
7422 T = Context.OCLSamplerTy;
7423 break;
7425 T = Context.OCLEventTy;
7426 break;
7428 T = Context.OCLClkEventTy;
7429 break;
7431 T = Context.OCLQueueTy;
7432 break;
7434 T = Context.OCLReserveIDTy;
7435 break;
7437 T = Context.getAutoDeductType();
7438 break;
7440 T = Context.getAutoRRefDeductType();
7441 break;
7443 T = Context.ARCUnbridgedCastTy;
7444 break;
7446 T = Context.BuiltinFnTy;
7447 break;
7449 T = Context.IncompleteMatrixIdxTy;
7450 break;
7452 T = Context.ArraySectionTy;
7453 break;
7455 T = Context.OMPArrayShapingTy;
7456 break;
7458 T = Context.OMPIteratorTy;
7459 break;
7460#define SVE_TYPE(Name, Id, SingletonId) \
7461 case PREDEF_TYPE_##Id##_ID: \
7462 T = Context.SingletonId; \
7463 break;
7464#include "clang/Basic/AArch64SVEACLETypes.def"
7465#define PPC_VECTOR_TYPE(Name, Id, Size) \
7466 case PREDEF_TYPE_##Id##_ID: \
7467 T = Context.Id##Ty; \
7468 break;
7469#include "clang/Basic/PPCTypes.def"
7470#define RVV_TYPE(Name, Id, SingletonId) \
7471 case PREDEF_TYPE_##Id##_ID: \
7472 T = Context.SingletonId; \
7473 break;
7474#include "clang/Basic/RISCVVTypes.def"
7475#define WASM_TYPE(Name, Id, SingletonId) \
7476 case PREDEF_TYPE_##Id##_ID: \
7477 T = Context.SingletonId; \
7478 break;
7479#include "clang/Basic/WebAssemblyReferenceTypes.def"
7480#define AMDGPU_TYPE(Name, Id, SingletonId) \
7481 case PREDEF_TYPE_##Id##_ID: \
7482 T = Context.SingletonId; \
7483 break;
7484#include "clang/Basic/AMDGPUTypes.def"
7485#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
7486 case PREDEF_TYPE_##Id##_ID: \
7487 T = Context.SingletonId; \
7488 break;
7489#include "clang/Basic/HLSLIntangibleTypes.def"
7490 }
7491
7492 assert(!T.isNull() && "Unknown predefined type");
7493 return T.withFastQualifiers(FastQuals);
7494 }
7495
7496 unsigned Index = translateTypeIDToIndex(ID).second;
7497
7498 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7499 if (TypesLoaded[Index].isNull()) {
7500 TypesLoaded[Index] = readTypeRecord(ID);
7501 if (TypesLoaded[Index].isNull())
7502 return QualType();
7503
7504 TypesLoaded[Index]->setFromAST();
7505 if (DeserializationListener)
7506 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7507 TypesLoaded[Index]);
7508 }
7509
7510 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7511}
7512
7514 return GetType(getGlobalTypeID(F, LocalID));
7515}
7516
7518 LocalTypeID LocalID) const {
7519 if (isPredefinedType(LocalID))
7520 return LocalID;
7521
7522 if (!F.ModuleOffsetMap.empty())
7523 ReadModuleOffsetMap(F);
7524
7525 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
7526 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
7527
7528 if (ModuleFileIndex == 0)
7530
7531 ModuleFile &MF =
7532 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
7533 ModuleFileIndex = MF.Index + 1;
7534 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
7535}
7536
7539 switch (Kind) {
7541 return readExpr();
7543 return readTypeSourceInfo();
7545 NestedNameSpecifierLoc QualifierLoc =
7546 readNestedNameSpecifierLoc();
7547 SourceLocation TemplateNameLoc = readSourceLocation();
7548 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7549 TemplateNameLoc, SourceLocation());
7550 }
7552 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7553 SourceLocation TemplateNameLoc = readSourceLocation();
7554 SourceLocation EllipsisLoc = readSourceLocation();
7555 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7556 TemplateNameLoc, EllipsisLoc);
7557 }
7564 // FIXME: Is this right?
7565 return TemplateArgumentLocInfo();
7566 }
7567 llvm_unreachable("unexpected template argument loc");
7568}
7569
7571 TemplateArgument Arg = readTemplateArgument();
7572
7574 if (readBool()) // bool InfoHasSameExpr.
7576 }
7577 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7578}
7579
7582 Result.setLAngleLoc(readSourceLocation());
7583 Result.setRAngleLoc(readSourceLocation());
7584 unsigned NumArgsAsWritten = readInt();
7585 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7586 Result.addArgument(readTemplateArgumentLoc());
7587}
7588
7592 readTemplateArgumentListInfo(Result);
7593 return ASTTemplateArgumentListInfo::Create(getContext(), Result);
7594}
7595
7597
7599 if (NumCurrentElementsDeserializing) {
7600 // We arrange to not care about the complete redeclaration chain while we're
7601 // deserializing. Just remember that the AST has marked this one as complete
7602 // but that it's not actually complete yet, so we know we still need to
7603 // complete it later.
7604 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7605 return;
7606 }
7607
7608 if (!D->getDeclContext()) {
7609 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7610 return;
7611 }
7612
7613 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7614
7615 // If this is a named declaration, complete it by looking it up
7616 // within its context.
7617 //
7618 // FIXME: Merging a function definition should merge
7619 // all mergeable entities within it.
7620 if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
7621 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7622 if (!getContext().getLangOpts().CPlusPlus &&
7623 isa<TranslationUnitDecl>(DC)) {
7624 // Outside of C++, we don't have a lookup table for the TU, so update
7625 // the identifier instead. (For C++ modules, we don't store decls
7626 // in the serialized identifier table, so we do the lookup in the TU.)
7627 auto *II = Name.getAsIdentifierInfo();
7628 assert(II && "non-identifier name in C?");
7629 if (II->isOutOfDate())
7630 updateOutOfDateIdentifier(*II);
7631 } else
7632 DC->lookup(Name);
7633 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7634 // Find all declarations of this kind from the relevant context.
7635 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7636 auto *DC = cast<DeclContext>(DCDecl);
7638 FindExternalLexicalDecls(
7639 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7640 }
7641 }
7642 }
7643
7644 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7645 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7646 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7647 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7648 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7649 if (auto *Template = FD->getPrimaryTemplate())
7650 Template->LoadLazySpecializations();
7651 }
7652}
7653
7656 RecordLocation Loc = getLocalBitOffset(Offset);
7657 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7658 SavedStreamPosition SavedPosition(Cursor);
7659 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7660 Error(std::move(Err));
7661 return nullptr;
7662 }
7663 ReadingKindTracker ReadingKind(Read_Decl, *this);
7664 Deserializing D(this);
7665
7666 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7667 if (!MaybeCode) {
7668 Error(MaybeCode.takeError());
7669 return nullptr;
7670 }
7671 unsigned Code = MaybeCode.get();
7672
7673 ASTRecordReader Record(*this, *Loc.F);
7674 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7675 if (!MaybeRecCode) {
7676 Error(MaybeRecCode.takeError());
7677 return nullptr;
7678 }
7679 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7680 Error("malformed AST file: missing C++ ctor initializers");
7681 return nullptr;
7682 }
7683
7684 return Record.readCXXCtorInitializers();
7685}
7686
7688 assert(ContextObj && "reading base specifiers with no AST context");
7689 ASTContext &Context = *ContextObj;
7690
7691 RecordLocation Loc = getLocalBitOffset(Offset);
7692 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7693 SavedStreamPosition SavedPosition(Cursor);
7694 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7695 Error(std::move(Err));
7696 return nullptr;
7697 }
7698 ReadingKindTracker ReadingKind(Read_Decl, *this);
7699 Deserializing D(this);
7700
7701 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7702 if (!MaybeCode) {
7703 Error(MaybeCode.takeError());
7704 return nullptr;
7705 }
7706 unsigned Code = MaybeCode.get();
7707
7708 ASTRecordReader Record(*this, *Loc.F);
7709 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7710 if (!MaybeRecCode) {
7711 Error(MaybeCode.takeError());
7712 return nullptr;
7713 }
7714 unsigned RecCode = MaybeRecCode.get();
7715
7716 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7717 Error("malformed AST file: missing C++ base specifiers");
7718 return nullptr;
7719 }
7720
7721 unsigned NumBases = Record.readInt();
7722 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7723 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7724 for (unsigned I = 0; I != NumBases; ++I)
7725 Bases[I] = Record.readCXXBaseSpecifier();
7726 return Bases;
7727}
7728
7730 LocalDeclID LocalID) const {
7731 if (LocalID < NUM_PREDEF_DECL_IDS)
7732 return GlobalDeclID(LocalID.getRawValue());
7733
7734 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
7735 DeclID ID = LocalID.getLocalDeclIndex();
7736
7737 if (!F.ModuleOffsetMap.empty())
7738 ReadModuleOffsetMap(F);
7739
7740 ModuleFile *OwningModuleFile =
7741 OwningModuleFileIndex == 0
7742 ? &F
7743 : F.TransitiveImports[OwningModuleFileIndex - 1];
7744
7745 if (OwningModuleFileIndex == 0)
7746 ID -= NUM_PREDEF_DECL_IDS;
7747
7748 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
7749 return GlobalDeclID(NewModuleFileIndex, ID);
7750}
7751
7753 // Predefined decls aren't from any module.
7754 if (ID < NUM_PREDEF_DECL_IDS)
7755 return false;
7756
7757 unsigned ModuleFileIndex = ID.getModuleFileIndex();
7758 return M.Index == ModuleFileIndex - 1;
7759}
7760
7762 // Predefined decls aren't from any module.
7763 if (ID < NUM_PREDEF_DECL_IDS)
7764 return nullptr;
7765
7766 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
7767 assert(ModuleFileIndex && "Untranslated Local Decl?");
7768
7769 return &getModuleManager()[ModuleFileIndex - 1];
7770}
7771
7773 if (!D->isFromASTFile())
7774 return nullptr;
7775
7776 return getOwningModuleFile(D->getGlobalID());
7777}
7778
7780 if (ID < NUM_PREDEF_DECL_IDS)
7781 return SourceLocation();
7782
7783 if (Decl *D = GetExistingDecl(ID))
7784 return D->getLocation();
7785
7787 DeclCursorForID(ID, Loc);
7788 return Loc;
7789}
7790
7791Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
7792 assert(ContextObj && "reading predefined decl without AST context");
7793 ASTContext &Context = *ContextObj;
7794 Decl *NewLoaded = nullptr;
7795 switch (ID) {
7797 return nullptr;
7798
7800 return Context.getTranslationUnitDecl();
7801
7803 if (Context.ObjCIdDecl)
7804 return Context.ObjCIdDecl;
7805 NewLoaded = Context.getObjCIdDecl();
7806 break;
7807
7809 if (Context.ObjCSelDecl)
7810 return Context.ObjCSelDecl;
7811 NewLoaded = Context.getObjCSelDecl();
7812 break;
7813
7815 if (Context.ObjCClassDecl)
7816 return Context.ObjCClassDecl;
7817 NewLoaded = Context.getObjCClassDecl();
7818 break;
7819
7821 if (Context.ObjCProtocolClassDecl)
7822 return Context.ObjCProtocolClassDecl;
7823 NewLoaded = Context.getObjCProtocolDecl();
7824 break;
7825
7827 if (Context.Int128Decl)
7828 return Context.Int128Decl;
7829 NewLoaded = Context.getInt128Decl();
7830 break;
7831
7833 if (Context.UInt128Decl)
7834 return Context.UInt128Decl;
7835 NewLoaded = Context.getUInt128Decl();
7836 break;
7837
7839 if (Context.ObjCInstanceTypeDecl)
7840 return Context.ObjCInstanceTypeDecl;
7841 NewLoaded = Context.getObjCInstanceTypeDecl();
7842 break;
7843
7845 if (Context.BuiltinVaListDecl)
7846 return Context.BuiltinVaListDecl;
7847 NewLoaded = Context.getBuiltinVaListDecl();
7848 break;
7849
7851 if (Context.VaListTagDecl)
7852 return Context.VaListTagDecl;
7853 NewLoaded = Context.getVaListTagDecl();
7854 break;
7855
7857 if (Context.BuiltinMSVaListDecl)
7858 return Context.BuiltinMSVaListDecl;
7859 NewLoaded = Context.getBuiltinMSVaListDecl();
7860 break;
7861
7863 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
7864 return Context.getMSGuidTagDecl();
7865
7867 if (Context.ExternCContext)
7868 return Context.ExternCContext;
7869 NewLoaded = Context.getExternCContextDecl();
7870 break;
7871
7873 if (Context.MakeIntegerSeqDecl)
7874 return Context.MakeIntegerSeqDecl;
7875 NewLoaded = Context.getMakeIntegerSeqDecl();
7876 break;
7877
7879 if (Context.CFConstantStringTypeDecl)
7880 return Context.CFConstantStringTypeDecl;
7881 NewLoaded = Context.getCFConstantStringDecl();
7882 break;
7883
7885 if (Context.CFConstantStringTagDecl)
7886 return Context.CFConstantStringTagDecl;
7887 NewLoaded = Context.getCFConstantStringTagDecl();
7888 break;
7889
7891 if (Context.TypePackElementDecl)
7892 return Context.TypePackElementDecl;
7893 NewLoaded = Context.getTypePackElementDecl();
7894 break;
7895 }
7896
7897 assert(NewLoaded && "Failed to load predefined decl?");
7898
7899 if (DeserializationListener)
7900 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
7901
7902 return NewLoaded;
7903}
7904
7905unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
7906 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
7907 if (!OwningModuleFile) {
7908 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
7909 return GlobalID.getRawValue();
7910 }
7911
7912 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
7913}
7914
7916 assert(ContextObj && "reading decl with no AST context");
7917
7918 if (ID < NUM_PREDEF_DECL_IDS) {
7919 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
7920 if (D) {
7921 // Track that we have merged the declaration with ID \p ID into the
7922 // pre-existing predefined declaration \p D.
7923 auto &Merged = KeyDecls[D->getCanonicalDecl()];
7924 if (Merged.empty())
7925 Merged.push_back(ID);
7926 }
7927 return D;
7928 }
7929
7930 unsigned Index = translateGlobalDeclIDToIndex(ID);
7931
7932 if (Index >= DeclsLoaded.size()) {
7933 assert(0 && "declaration ID out-of-range for AST file");
7934 Error("declaration ID out-of-range for AST file");
7935 return nullptr;
7936 }
7937
7938 return DeclsLoaded[Index];
7939}
7940
7942 if (ID < NUM_PREDEF_DECL_IDS)
7943 return GetExistingDecl(ID);
7944
7945 unsigned Index = translateGlobalDeclIDToIndex(ID);
7946
7947 if (Index >= DeclsLoaded.size()) {
7948 assert(0 && "declaration ID out-of-range for AST file");
7949 Error("declaration ID out-of-range for AST file");
7950 return nullptr;
7951 }
7952
7953 if (!DeclsLoaded[Index]) {
7954 ReadDeclRecord(ID);
7955 if (DeserializationListener)
7956 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7957 }
7958
7959 return DeclsLoaded[Index];
7960}
7961
7963 GlobalDeclID GlobalID) {
7964 if (GlobalID < NUM_PREDEF_DECL_IDS)
7965 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
7966
7967 if (!M.ModuleOffsetMap.empty())
7968 ReadModuleOffsetMap(M);
7969
7970 ModuleFile *Owner = getOwningModuleFile(GlobalID);
7971 DeclID ID = GlobalID.getLocalDeclIndex();
7972
7973 if (Owner == &M) {
7974 ID += NUM_PREDEF_DECL_IDS;
7975 return LocalDeclID::get(*this, M, ID);
7976 }
7977
7978 uint64_t OrignalModuleFileIndex = 0;
7979 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
7980 if (M.TransitiveImports[I] == Owner) {
7981 OrignalModuleFileIndex = I + 1;
7982 break;
7983 }
7984
7985 if (!OrignalModuleFileIndex)
7986 return LocalDeclID();
7987
7988 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
7989}
7990
7992 unsigned &Idx) {
7993 if (Idx >= Record.size()) {
7994 Error("Corrupted AST file");
7995 return GlobalDeclID(0);
7996 }
7997
7998 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
7999}
8000
8001/// Resolve the offset of a statement into a statement.
8002///
8003/// This operation will read a new statement from the external
8004/// source each time it is called, and is meant to be used via a
8005/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8007 // Switch case IDs are per Decl.
8008 ClearSwitchCaseIDs();
8009
8010 // Offset here is a global offset across the entire chain.
8011 RecordLocation Loc = getLocalBitOffset(Offset);
8012 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8013 Error(std::move(Err));
8014 return nullptr;
8015 }
8016 assert(NumCurrentElementsDeserializing == 0 &&
8017 "should not be called while already deserializing");
8018 Deserializing D(this);
8019 return ReadStmtFromStream(*Loc.F);
8020}
8021
8023 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8024 SmallVectorImpl<Decl *> &Decls) {
8025 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8026
8027 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8028 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8029 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8030 auto K = (Decl::Kind)+LexicalDecls[I];
8031 if (!IsKindWeWant(K))
8032 continue;
8033
8034 auto ID = (DeclID) + LexicalDecls[I + 1];
8035
8036 // Don't add predefined declarations to the lexical context more
8037 // than once.
8038 if (ID < NUM_PREDEF_DECL_IDS) {
8039 if (PredefsVisited[ID])
8040 continue;
8041
8042 PredefsVisited[ID] = true;
8043 }
8044
8045 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8046 assert(D->getKind() == K && "wrong kind for lexical decl");
8047 if (!DC->isDeclInLexicalTraversal(D))
8048 Decls.push_back(D);
8049 }
8050 }
8051 };
8052
8053 if (isa<TranslationUnitDecl>(DC)) {
8054 for (const auto &Lexical : TULexicalDecls)
8055 Visit(Lexical.first, Lexical.second);
8056 } else {
8057 auto I = LexicalDecls.find(DC);
8058 if (I != LexicalDecls.end())
8059 Visit(I->second.first, I->second.second);
8060 }
8061
8062 ++NumLexicalDeclContextsRead;
8063}
8064
8065namespace {
8066
8067class UnalignedDeclIDComp {
8068 ASTReader &Reader;
8069 ModuleFile &Mod;
8070
8071public:
8072 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8073 : Reader(Reader), Mod(M) {}
8074
8075 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8076 SourceLocation LHS = getLocation(L);
8077 SourceLocation RHS = getLocation(R);
8078 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8079 }
8080
8081 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8082 SourceLocation RHS = getLocation(R);
8083 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8084 }
8085
8086 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8087 SourceLocation LHS = getLocation(L);
8088 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8089 }
8090
8091 SourceLocation getLocation(unaligned_decl_id_t ID) const {
8092 return Reader.getSourceManager().getFileLoc(
8094 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
8095 }
8096};
8097
8098} // namespace
8099
8101 unsigned Offset, unsigned Length,
8102 SmallVectorImpl<Decl *> &Decls) {
8103 SourceManager &SM = getSourceManager();
8104
8105 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8106 if (I == FileDeclIDs.end())
8107 return;
8108
8109 FileDeclsInfo &DInfo = I->second;
8110 if (DInfo.Decls.empty())
8111 return;
8112
8114 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8115 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8116
8117 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8119 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8120 if (BeginIt != DInfo.Decls.begin())
8121 --BeginIt;
8122
8123 // If we are pointing at a top-level decl inside an objc container, we need
8124 // to backtrack until we find it otherwise we will fail to report that the
8125 // region overlaps with an objc container.
8126 while (BeginIt != DInfo.Decls.begin() &&
8127 GetDecl(getGlobalDeclID(*DInfo.Mod,
8128 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8129 ->isTopLevelDeclInObjCContainer())
8130 --BeginIt;
8131
8133 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8134 if (EndIt != DInfo.Decls.end())
8135 ++EndIt;
8136
8137 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8138 ++DIt)
8139 Decls.push_back(GetDecl(getGlobalDeclID(
8140 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8141}
8142
8143bool
8145 DeclarationName Name) {
8146 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8147 "DeclContext has no visible decls in storage");
8148 if (!Name)
8149 return false;
8150
8151 auto It = Lookups.find(DC);
8152 if (It == Lookups.end())
8153 return false;
8154
8155 Deserializing LookupResults(this);
8156
8157 // Load the list of declarations.
8160
8161 for (GlobalDeclID ID : It->second.Table.find(Name)) {
8162 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8163 if (ND->getDeclName() == Name && Found.insert(ND).second)
8164 Decls.push_back(ND);
8165 }
8166
8167 ++NumVisibleDeclContextsRead;
8168 SetExternalVisibleDeclsForName(DC, Name, Decls);
8169 return !Decls.empty();
8170}
8171
8173 if (!DC->hasExternalVisibleStorage())
8174 return;
8175
8176 auto It = Lookups.find(DC);
8177 assert(It != Lookups.end() &&
8178 "have external visible storage but no lookup tables");
8179
8180 DeclsMap Decls;
8181
8182 for (GlobalDeclID ID : It->second.Table.findAll()) {
8183 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8184 Decls[ND->getDeclName()].push_back(ND);
8185 }
8186
8187 ++NumVisibleDeclContextsRead;
8188
8189 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8190 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8191 }
8192 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8193}
8194
8197 auto I = Lookups.find(Primary);
8198 return I == Lookups.end() ? nullptr : &I->second;
8199}
8200
8201/// Under non-PCH compilation the consumer receives the objc methods
8202/// before receiving the implementation, and codegen depends on this.
8203/// We simulate this by deserializing and passing to consumer the methods of the
8204/// implementation before passing the deserialized implementation decl.
8206 ASTConsumer *Consumer) {
8207 assert(ImplD && Consumer);
8208
8209 for (auto *I : ImplD->methods())
8210 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8211
8212 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8213}
8214
8215void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8216 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8217 PassObjCImplDeclToConsumer(ImplD, Consumer);
8218 else
8219 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8220}
8221
8222void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
8223 Consumer->HandleVTable(RD);
8224}
8225
8227 this->Consumer = Consumer;
8228
8229 if (Consumer)
8230 PassInterestingDeclsToConsumer();
8231
8232 if (DeserializationListener)
8233 DeserializationListener->ReaderInitialized(this);
8234}
8235
8237 std::fprintf(stderr, "*** AST File Statistics:\n");
8238
8239 unsigned NumTypesLoaded =
8240 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8241 unsigned NumDeclsLoaded =
8242 DeclsLoaded.size() -
8243 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8244 unsigned NumIdentifiersLoaded =
8245 IdentifiersLoaded.size() -
8246 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8247 unsigned NumMacrosLoaded =
8248 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8249 unsigned NumSelectorsLoaded =
8250 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8251
8252 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8253 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8254 NumSLocEntriesRead, TotalNumSLocEntries,
8255 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8256 if (!TypesLoaded.empty())
8257 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8258 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8259 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8260 if (!DeclsLoaded.empty())
8261 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8262 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8263 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8264 if (!IdentifiersLoaded.empty())
8265 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8266 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8267 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8268 if (!MacrosLoaded.empty())
8269 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8270 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8271 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8272 if (!SelectorsLoaded.empty())
8273 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8274 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8275 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8276 if (TotalNumStatements)
8277 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8278 NumStatementsRead, TotalNumStatements,
8279 ((float)NumStatementsRead/TotalNumStatements * 100));
8280 if (TotalNumMacros)
8281 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8282 NumMacrosRead, TotalNumMacros,
8283 ((float)NumMacrosRead/TotalNumMacros * 100));
8284 if (TotalLexicalDeclContexts)
8285 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8286 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8287 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8288 * 100));
8289 if (TotalVisibleDeclContexts)
8290 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8291 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8292 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8293 * 100));
8294 if (TotalNumMethodPoolEntries)
8295 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8296 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8297 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8298 * 100));
8299 if (NumMethodPoolLookups)
8300 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8301 NumMethodPoolHits, NumMethodPoolLookups,
8302 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8303 if (NumMethodPoolTableLookups)
8304 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8305 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8306 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8307 * 100.0));
8308 if (NumIdentifierLookupHits)
8309 std::fprintf(stderr,
8310 " %u / %u identifier table lookups succeeded (%f%%)\n",
8311 NumIdentifierLookupHits, NumIdentifierLookups,
8312 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8313
8314 if (GlobalIndex) {
8315 std::fprintf(stderr, "\n");
8316 GlobalIndex->printStats();
8317 }
8318
8319 std::fprintf(stderr, "\n");
8320 dump();
8321 std::fprintf(stderr, "\n");
8322}
8323
8324template<typename Key, typename ModuleFile, unsigned InitialCapacity>
8325LLVM_DUMP_METHOD static void
8326dumpModuleIDMap(StringRef Name,
8327 const ContinuousRangeMap<Key, ModuleFile *,
8328 InitialCapacity> &Map) {
8329 if (Map.begin() == Map.end())
8330 return;
8331
8333
8334 llvm::errs() << Name << ":\n";
8335 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8336 I != IEnd; ++I)
8337 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
8338 << "\n";
8339}
8340
8341LLVM_DUMP_METHOD void ASTReader::dump() {
8342 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8343 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8344 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8345 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8346 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8347 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
8348 dumpModuleIDMap("Global preprocessed entity map",
8349 GlobalPreprocessedEntityMap);
8350
8351 llvm::errs() << "\n*** PCH/Modules Loaded:";
8352 for (ModuleFile &M : ModuleMgr)
8353 M.dump();
8354}
8355
8356/// Return the amount of memory used by memory buffers, breaking down
8357/// by heap-backed versus mmap'ed memory.
8359 for (ModuleFile &I : ModuleMgr) {
8360 if (llvm::MemoryBuffer *buf = I.Buffer) {
8361 size_t bytes = buf->getBufferSize();
8362 switch (buf->getBufferKind()) {
8363 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8364 sizes.malloc_bytes += bytes;
8365 break;
8366 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8367 sizes.mmap_bytes += bytes;
8368 break;
8369 }
8370 }
8371 }
8372}
8373
8375 SemaObj = &S;
8376 S.addExternalSource(this);
8377
8378 // Makes sure any declarations that were deserialized "too early"
8379 // still get added to the identifier's declaration chains.
8380 for (GlobalDeclID ID : PreloadedDeclIDs) {
8381 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
8382 pushExternalDeclIntoScope(D, D->getDeclName());
8383 }
8384 PreloadedDeclIDs.clear();
8385
8386 // FIXME: What happens if these are changed by a module import?
8387 if (!FPPragmaOptions.empty()) {
8388 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
8389 FPOptionsOverride NewOverrides =
8390 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
8391 SemaObj->CurFPFeatures =
8392 NewOverrides.applyOverrides(SemaObj->getLangOpts());
8393 }
8394
8395 SemaObj->OpenCLFeatures = OpenCLExtensions;
8396
8397 UpdateSema();
8398}
8399
8401 assert(SemaObj && "no Sema to update");
8402
8403 // Load the offsets of the declarations that Sema references.
8404 // They will be lazily deserialized when needed.
8405 if (!SemaDeclRefs.empty()) {
8406 assert(SemaDeclRefs.size() % 3 == 0);
8407 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
8408 if (!SemaObj->StdNamespace)
8409 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
8410 if (!SemaObj->StdBadAlloc)
8411 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
8412 if (!SemaObj->StdAlignValT)
8413 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
8414 }
8415 SemaDeclRefs.clear();
8416 }
8417
8418 // Update the state of pragmas. Use the same API as if we had encountered the
8419 // pragma in the source.
8420 if(OptimizeOffPragmaLocation.isValid())
8421 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
8422 if (PragmaMSStructState != -1)
8423 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
8424 if (PointersToMembersPragmaLocation.isValid()) {
8425 SemaObj->ActOnPragmaMSPointersToMembers(
8427 PragmaMSPointersToMembersState,
8428 PointersToMembersPragmaLocation);
8429 }
8430 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
8431
8432 if (PragmaAlignPackCurrentValue) {
8433 // The bottom of the stack might have a default value. It must be adjusted
8434 // to the current value to ensure that the packing state is preserved after
8435 // popping entries that were included/imported from a PCH/module.
8436 bool DropFirst = false;
8437 if (!PragmaAlignPackStack.empty() &&
8438 PragmaAlignPackStack.front().Location.isInvalid()) {
8439 assert(PragmaAlignPackStack.front().Value ==
8440 SemaObj->AlignPackStack.DefaultValue &&
8441 "Expected a default alignment value");
8442 SemaObj->AlignPackStack.Stack.emplace_back(
8443 PragmaAlignPackStack.front().SlotLabel,
8444 SemaObj->AlignPackStack.CurrentValue,
8445 SemaObj->AlignPackStack.CurrentPragmaLocation,
8446 PragmaAlignPackStack.front().PushLocation);
8447 DropFirst = true;
8448 }
8449 for (const auto &Entry :
8450 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
8451 SemaObj->AlignPackStack.Stack.emplace_back(
8452 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8453 }
8454 if (PragmaAlignPackCurrentLocation.isInvalid()) {
8455 assert(*PragmaAlignPackCurrentValue ==
8456 SemaObj->AlignPackStack.DefaultValue &&
8457 "Expected a default align and pack value");
8458 // Keep the current values.
8459 } else {
8460 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
8461 SemaObj->AlignPackStack.CurrentPragmaLocation =
8462 PragmaAlignPackCurrentLocation;
8463 }
8464 }
8465 if (FpPragmaCurrentValue) {
8466 // The bottom of the stack might have a default value. It must be adjusted
8467 // to the current value to ensure that fp-pragma state is preserved after
8468 // popping entries that were included/imported from a PCH/module.
8469 bool DropFirst = false;
8470 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
8471 assert(FpPragmaStack.front().Value ==
8472 SemaObj->FpPragmaStack.DefaultValue &&
8473 "Expected a default pragma float_control value");
8474 SemaObj->FpPragmaStack.Stack.emplace_back(
8475 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
8476 SemaObj->FpPragmaStack.CurrentPragmaLocation,
8477 FpPragmaStack.front().PushLocation);
8478 DropFirst = true;
8479 }
8480 for (const auto &Entry :
8481 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
8482 SemaObj->FpPragmaStack.Stack.emplace_back(
8483 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8484 if (FpPragmaCurrentLocation.isInvalid()) {
8485 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
8486 "Expected a default pragma float_control value");
8487 // Keep the current values.
8488 } else {
8489 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
8490 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
8491 }
8492 }
8493
8494 // For non-modular AST files, restore visiblity of modules.
8495 for (auto &Import : PendingImportedModulesSema) {
8496 if (Import.ImportLoc.isInvalid())
8497 continue;
8498 if (Module *Imported = getSubmodule(Import.ID)) {
8499 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8500 }
8501 }
8502 PendingImportedModulesSema.clear();
8503}
8504
8506 // Note that we are loading an identifier.
8507 Deserializing AnIdentifier(this);
8508
8509 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
8510 NumIdentifierLookups,
8511 NumIdentifierLookupHits);
8512
8513 // We don't need to do identifier table lookups in C++ modules (we preload
8514 // all interesting declarations, and don't need to use the scope for name
8515 // lookups). Perform the lookup in PCH files, though, since we don't build
8516 // a complete initial identifier table if we're carrying on from a PCH.
8517 if (PP.getLangOpts().CPlusPlus) {
8518 for (auto *F : ModuleMgr.pch_modules())
8519 if (Visitor(*F))
8520 break;
8521 } else {
8522 // If there is a global index, look there first to determine which modules
8523 // provably do not have any results for this identifier.
8525 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8526 if (!loadGlobalIndex()) {
8527 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8528 HitsPtr = &Hits;
8529 }
8530 }
8531
8532 ModuleMgr.visit(Visitor, HitsPtr);
8533 }
8534
8535 IdentifierInfo *II = Visitor.getIdentifierInfo();
8536 markIdentifierUpToDate(II);
8537 return II;
8538}
8539
8540namespace clang {
8541
8542 /// An identifier-lookup iterator that enumerates all of the
8543 /// identifiers stored within a set of AST files.
8545 /// The AST reader whose identifiers are being enumerated.
8546 const ASTReader &Reader;
8547
8548 /// The current index into the chain of AST files stored in
8549 /// the AST reader.
8550 unsigned Index;
8551
8552 /// The current position within the identifier lookup table
8553 /// of the current AST file.
8554 ASTIdentifierLookupTable::key_iterator Current;
8555
8556 /// The end position within the identifier lookup table of
8557 /// the current AST file.
8558 ASTIdentifierLookupTable::key_iterator End;
8559
8560 /// Whether to skip any modules in the ASTReader.
8561 bool SkipModules;
8562
8563 public:
8564 explicit ASTIdentifierIterator(const ASTReader &Reader,
8565 bool SkipModules = false);
8566
8567 StringRef Next() override;
8568 };
8569
8570} // namespace clang
8571
8573 bool SkipModules)
8574 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8575}
8576
8578 while (Current == End) {
8579 // If we have exhausted all of our AST files, we're done.
8580 if (Index == 0)
8581 return StringRef();
8582
8583 --Index;
8584 ModuleFile &F = Reader.ModuleMgr[Index];
8585 if (SkipModules && F.isModule())
8586 continue;
8587
8588 ASTIdentifierLookupTable *IdTable =
8590 Current = IdTable->key_begin();
8591 End = IdTable->key_end();
8592 }
8593
8594 // We have any identifiers remaining in the current AST file; return
8595 // the next one.
8596 StringRef Result = *Current;
8597 ++Current;
8598 return Result;
8599}
8600
8601namespace {
8602
8603/// A utility for appending two IdentifierIterators.
8604class ChainedIdentifierIterator : public IdentifierIterator {
8605 std::unique_ptr<IdentifierIterator> Current;
8606 std::unique_ptr<IdentifierIterator> Queued;
8607
8608public:
8609 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8610 std::unique_ptr<IdentifierIterator> Second)
8611 : Current(std::move(First)), Queued(std::move(Second)) {}
8612
8613 StringRef Next() override {
8614 if (!Current)
8615 return StringRef();
8616
8617 StringRef result = Current->Next();
8618 if (!result.empty())
8619 return result;
8620
8621 // Try the queued iterator, which may itself be empty.
8622 Current.reset();
8623 std::swap(Current, Queued);
8624 return Next();
8625 }
8626};
8627
8628} // namespace
8629
8631 if (!loadGlobalIndex()) {
8632 std::unique_ptr<IdentifierIterator> ReaderIter(
8633 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8634 std::unique_ptr<IdentifierIterator> ModulesIter(
8635 GlobalIndex->createIdentifierIterator());
8636 return new ChainedIdentifierIterator(std::move(ReaderIter),
8637 std::move(ModulesIter));
8638 }
8639
8640 return new ASTIdentifierIterator(*this);
8641}
8642
8643namespace clang {
8644namespace serialization {
8645
8647 ASTReader &Reader;
8648 Selector Sel;
8649 unsigned PriorGeneration;
8650 unsigned InstanceBits = 0;
8651 unsigned FactoryBits = 0;
8652 bool InstanceHasMoreThanOneDecl = false;
8653 bool FactoryHasMoreThanOneDecl = false;
8654 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8655 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8656
8657 public:
8659 unsigned PriorGeneration)
8660 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8661
8663 if (!M.SelectorLookupTable)
8664 return false;
8665
8666 // If we've already searched this module file, skip it now.
8667 if (M.Generation <= PriorGeneration)
8668 return true;
8669
8670 ++Reader.NumMethodPoolTableLookups;
8671 ASTSelectorLookupTable *PoolTable
8673 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8674 if (Pos == PoolTable->end())
8675 return false;
8676
8677 ++Reader.NumMethodPoolTableHits;
8678 ++Reader.NumSelectorsRead;
8679 // FIXME: Not quite happy with the statistics here. We probably should
8680 // disable this tracking when called via LoadSelector.
8681 // Also, should entries without methods count as misses?
8682 ++Reader.NumMethodPoolEntriesRead;
8684 if (Reader.DeserializationListener)
8685 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8686
8687 // Append methods in the reverse order, so that later we can process them
8688 // in the order they appear in the source code by iterating through
8689 // the vector in the reverse order.
8690 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8691 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8692 InstanceBits = Data.InstanceBits;
8693 FactoryBits = Data.FactoryBits;
8694 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8695 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8696 return false;
8697 }
8698
8699 /// Retrieve the instance methods found by this visitor.
8701 return InstanceMethods;
8702 }
8703
8704 /// Retrieve the instance methods found by this visitor.
8706 return FactoryMethods;
8707 }
8708
8709 unsigned getInstanceBits() const { return InstanceBits; }
8710 unsigned getFactoryBits() const { return FactoryBits; }
8711
8713 return InstanceHasMoreThanOneDecl;
8714 }
8715
8716 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8717 };
8718
8719} // namespace serialization
8720} // namespace clang
8721
8722/// Add the given set of methods to the method list.
8724 ObjCMethodList &List) {
8725 for (ObjCMethodDecl *M : llvm::reverse(Methods))
8726 S.ObjC().addMethodToGlobalList(&List, M);
8727}
8728
8730 // Get the selector generation and update it to the current generation.
8731 unsigned &Generation = SelectorGeneration[Sel];
8732 unsigned PriorGeneration = Generation;
8733 Generation = getGeneration();
8734 SelectorOutOfDate[Sel] = false;
8735
8736 // Search for methods defined with this selector.
8737 ++NumMethodPoolLookups;
8738 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8739 ModuleMgr.visit(Visitor);
8740
8741 if (Visitor.getInstanceMethods().empty() &&
8742 Visitor.getFactoryMethods().empty())
8743 return;
8744
8745 ++NumMethodPoolHits;
8746
8747 if (!getSema())
8748 return;
8749
8750 Sema &S = *getSema();
8752 S.ObjC()
8753 .MethodPool
8754 .insert(std::make_pair(Sel, SemaObjC::GlobalMethodPool::Lists()))
8755 .first;
8756
8757 Pos->second.first.setBits(Visitor.getInstanceBits());
8758 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8759 Pos->second.second.setBits(Visitor.getFactoryBits());
8760 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8761
8762 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8763 // when building a module we keep every method individually and may need to
8764 // update hasMoreThanOneDecl as we add the methods.
8765 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8766 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8767}
8768
8770 if (SelectorOutOfDate[Sel])
8771 ReadMethodPool(Sel);
8772}
8773
8776 Namespaces.clear();
8777
8778 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8779 if (NamespaceDecl *Namespace
8780 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8781 Namespaces.push_back(Namespace);
8782 }
8783}
8784
8786 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8787 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8788 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
8789 NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID));
8791 Undefined.insert(std::make_pair(D, Loc));
8792 }
8793 UndefinedButUsed.clear();
8794}
8795
8797 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8798 Exprs) {
8799 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8800 FieldDecl *FD =
8801 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
8802 uint64_t Count = DelayedDeleteExprs[Idx++];
8803 for (uint64_t C = 0; C < Count; ++C) {
8804 SourceLocation DeleteLoc =
8805 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8806 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8807 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8808 }
8809 }
8810}
8811
8813 SmallVectorImpl<VarDecl *> &TentativeDefs) {
8814 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8815 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8816 if (Var)
8817 TentativeDefs.push_back(Var);
8818 }
8819 TentativeDefinitions.clear();
8820}
8821
8824 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8826 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8827 if (D)
8828 Decls.push_back(D);
8829 }
8830 UnusedFileScopedDecls.clear();
8831}
8832
8835 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8837 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8838 if (D)
8839 Decls.push_back(D);
8840 }
8841 DelegatingCtorDecls.clear();
8842}
8843
8845 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8847 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8848 if (D)
8849 Decls.push_back(D);
8850 }
8851 ExtVectorDecls.clear();
8852}
8853
8856 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8857 ++I) {
8858 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8859 GetDecl(UnusedLocalTypedefNameCandidates[I]));
8860 if (D)
8861 Decls.insert(D);
8862 }
8863 UnusedLocalTypedefNameCandidates.clear();
8864}
8865
8868 for (auto I : DeclsToCheckForDeferredDiags) {
8869 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
8870 if (D)
8871 Decls.insert(D);
8872 }
8873 DeclsToCheckForDeferredDiags.clear();
8874}
8875
8877 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8878 if (ReferencedSelectorsData.empty())
8879 return;
8880
8881 // If there are @selector references added them to its pool. This is for
8882 // implementation of -Wselector.
8883 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8884 unsigned I = 0;
8885 while (I < DataSize) {
8886 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8887 SourceLocation SelLoc
8888 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8889 Sels.push_back(std::make_pair(Sel, SelLoc));
8890 }
8891 ReferencedSelectorsData.clear();
8892}
8893
8895 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8896 if (WeakUndeclaredIdentifiers.empty())
8897 return;
8898
8899 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8900 IdentifierInfo *WeakId
8901 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8902 IdentifierInfo *AliasId
8903 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8905 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8906 WeakInfo WI(AliasId, Loc);
8907 WeakIDs.push_back(std::make_pair(WeakId, WI));
8908 }
8909 WeakUndeclaredIdentifiers.clear();
8910}
8911
8913 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8915 VTableUse &TableInfo = VTableUses[Idx++];
8916 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
8917 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
8918 VT.DefinitionRequired = TableInfo.Used;
8919 VTables.push_back(VT);
8920 }
8921
8922 VTableUses.clear();
8923}
8924
8926 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8927 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8928 PendingInstantiation &Inst = PendingInstantiations[Idx++];
8929 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
8931
8932 Pending.push_back(std::make_pair(D, Loc));
8933 }
8934 PendingInstantiations.clear();
8935}
8936
8938 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8939 &LPTMap) {
8940 for (auto &LPT : LateParsedTemplates) {
8941 ModuleFile *FMod = LPT.first;
8942 RecordDataImpl &LateParsed = LPT.second;
8943 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
8944 /* In loop */) {
8945 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
8946
8947 auto LT = std::make_unique<LateParsedTemplate>();
8948 LT->D = ReadDecl(*FMod, LateParsed, Idx);
8949 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
8950
8952 assert(F && "No module");
8953
8954 unsigned TokN = LateParsed[Idx++];
8955 LT->Toks.reserve(TokN);
8956 for (unsigned T = 0; T < TokN; ++T)
8957 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
8958
8959 LPTMap.insert(std::make_pair(FD, std::move(LT)));
8960 }
8961 }
8962
8963 LateParsedTemplates.clear();
8964}
8965
8967 if (Lambda->getLambdaContextDecl()) {
8968 // Keep track of this lambda so it can be merged with another lambda that
8969 // is loaded later.
8970 LambdaDeclarationsForMerging.insert(
8972 Lambda->getLambdaIndexInContext()},
8973 const_cast<CXXRecordDecl *>(Lambda)});
8974 }
8975}
8976
8978 // It would be complicated to avoid reading the methods anyway. So don't.
8979 ReadMethodPool(Sel);
8980}
8981
8983 assert(ID && "Non-zero identifier ID required");
8984 unsigned Index = translateIdentifierIDToIndex(ID).second;
8985 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
8986 IdentifiersLoaded[Index] = II;
8987 if (DeserializationListener)
8988 DeserializationListener->IdentifierRead(ID, II);
8989}
8990
8991/// Set the globally-visible declarations associated with the given
8992/// identifier.
8993///
8994/// If the AST reader is currently in a state where the given declaration IDs
8995/// cannot safely be resolved, they are queued until it is safe to resolve
8996/// them.
8997///
8998/// \param II an IdentifierInfo that refers to one or more globally-visible
8999/// declarations.
9000///
9001/// \param DeclIDs the set of declaration IDs with the name @p II that are
9002/// visible at global scope.
9003///
9004/// \param Decls if non-null, this vector will be populated with the set of
9005/// deserialized declarations. These declarations will not be pushed into
9006/// scope.
9009 SmallVectorImpl<Decl *> *Decls) {
9010 if (NumCurrentElementsDeserializing && !Decls) {
9011 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
9012 return;
9013 }
9014
9015 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
9016 if (!SemaObj) {
9017 // Queue this declaration so that it will be added to the
9018 // translation unit scope and identifier's declaration chain
9019 // once a Sema object is known.
9020 PreloadedDeclIDs.push_back(DeclIDs[I]);
9021 continue;
9022 }
9023
9024 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
9025
9026 // If we're simply supposed to record the declarations, do so now.
9027 if (Decls) {
9028 Decls->push_back(D);
9029 continue;
9030 }
9031
9032 // Introduce this declaration into the translation-unit scope
9033 // and add it to the declaration chain for this identifier, so
9034 // that (unqualified) name lookup will find it.
9035 pushExternalDeclIntoScope(D, II);
9036 }
9037}
9038
9039std::pair<ModuleFile *, unsigned>
9040ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
9041 if (ID == 0)
9042 return {nullptr, 0};
9043
9044 unsigned ModuleFileIndex = ID >> 32;
9045 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
9046
9047 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
9048 assert(getModuleManager().size() > ModuleFileIndex - 1);
9049
9050 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9051 assert(LocalID < MF.LocalNumIdentifiers);
9052 return {&MF, MF.BaseIdentifierID + LocalID};
9053}
9054
9056 if (ID == 0)
9057 return nullptr;
9058
9059 if (IdentifiersLoaded.empty()) {
9060 Error("no identifier table in AST file");
9061 return nullptr;
9062 }
9063
9064 auto [M, Index] = translateIdentifierIDToIndex(ID);
9065 if (!IdentifiersLoaded[Index]) {
9066 assert(M != nullptr && "Untranslated Identifier ID?");
9067 assert(Index >= M->BaseIdentifierID);
9068 unsigned LocalIndex = Index - M->BaseIdentifierID;
9069 const unsigned char *Data =
9070 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
9071
9072 ASTIdentifierLookupTrait Trait(*this, *M);
9073 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
9074 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
9075 auto &II = PP.getIdentifierTable().get(Key);
9076 IdentifiersLoaded[Index] = &II;
9077 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
9078 markIdentifierFromAST(*this, II, IsModule);
9079 if (DeserializationListener)
9080 DeserializationListener->IdentifierRead(ID, &II);
9081 }
9082
9083 return IdentifiersLoaded[Index];
9084}
9085
9087 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
9088}
9089
9091 if (LocalID < NUM_PREDEF_IDENT_IDS)
9092 return LocalID;
9093
9094 if (!M.ModuleOffsetMap.empty())
9095 ReadModuleOffsetMap(M);
9096
9097 unsigned ModuleFileIndex = LocalID >> 32;
9098 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
9099 ModuleFile *MF =
9100 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9101 assert(MF && "malformed identifier ID encoding?");
9102
9103 if (!ModuleFileIndex)
9104 LocalID -= NUM_PREDEF_IDENT_IDS;
9105
9106 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
9107}
9108
9110 if (ID == 0)
9111 return nullptr;
9112
9113 if (MacrosLoaded.empty()) {
9114 Error("no macro table in AST file");
9115 return nullptr;
9116 }
9117
9119 if (!MacrosLoaded[ID]) {
9121 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
9122 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
9123 ModuleFile *M = I->second;
9124 unsigned Index = ID - M->BaseMacroID;
9125 MacrosLoaded[ID] =
9126 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
9127
9128 if (DeserializationListener)
9129 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
9130 MacrosLoaded[ID]);
9131 }
9132
9133 return MacrosLoaded[ID];
9134}
9135
9137 if (LocalID < NUM_PREDEF_MACRO_IDS)
9138 return LocalID;
9139
9140 if (!M.ModuleOffsetMap.empty())
9141 ReadModuleOffsetMap(M);
9142
9144 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
9145 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
9146
9147 return LocalID + I->second;
9148}
9149
9151ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
9152 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
9153 return LocalID;
9154
9155 if (!M.ModuleOffsetMap.empty())
9156 ReadModuleOffsetMap(M);
9157
9160 assert(I != M.SubmoduleRemap.end()
9161 && "Invalid index into submodule index remap");
9162
9163 return LocalID + I->second;
9164}
9165
9167 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
9168 assert(GlobalID == 0 && "Unhandled global submodule ID");
9169 return nullptr;
9170 }
9171
9172 if (GlobalID > SubmodulesLoaded.size()) {
9173 Error("submodule ID out of range in AST file");
9174 return nullptr;
9175 }
9176
9177 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
9178}
9179
9181 return getSubmodule(ID);
9182}
9183
9185 if (ID & 1) {
9186 // It's a module, look it up by submodule ID.
9187 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
9188 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9189 } else {
9190 // It's a prefix (preamble, PCH, ...). Look it up by index.
9191 unsigned IndexFromEnd = ID >> 1;
9192 assert(IndexFromEnd && "got reference to unknown module file");
9193 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9194 }
9195}
9196
9198 if (!M)
9199 return 1;
9200
9201 // For a file representing a module, use the submodule ID of the top-level
9202 // module as the file ID. For any other kind of file, the number of such
9203 // files loaded beforehand will be the same on reload.
9204 // FIXME: Is this true even if we have an explicit module file and a PCH?
9205 if (M->isModule())
9206 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9207
9208 auto PCHModules = getModuleManager().pch_modules();
9209 auto I = llvm::find(PCHModules, M);
9210 assert(I != PCHModules.end() && "emitting reference to unknown file");
9211 return (I - PCHModules.end()) << 1;
9212}
9213
9214std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9215 if (Module *M = getSubmodule(ID))
9216 return ASTSourceDescriptor(*M);
9217
9218 // If there is only a single PCH, return it instead.
9219 // Chained PCH are not supported.
9220 const auto &PCHChain = ModuleMgr.pch_modules();
9221 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9222 ModuleFile &MF = ModuleMgr.getPrimaryModule();
9223 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9224 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9225 return ASTSourceDescriptor(ModuleName,
9226 llvm::sys::path::parent_path(MF.FileName),
9227 FileName, MF.Signature);
9228 }
9229 return std::nullopt;
9230}
9231
9233 auto I = DefinitionSource.find(FD);
9234 if (I == DefinitionSource.end())
9235 return EK_ReplyHazy;
9236 return I->second ? EK_Never : EK_Always;
9237}
9238
9240 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9241}
9242
9244 if (ID == 0)
9245 return Selector();
9246
9247 if (ID > SelectorsLoaded.size()) {
9248 Error("selector ID out of range in AST file");
9249 return Selector();
9250 }
9251
9252 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9253 // Load this selector from the selector table.
9254 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9255 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9256 ModuleFile &M = *I->second;
9257 ASTSelectorLookupTrait Trait(*this, M);
9258 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9259 SelectorsLoaded[ID - 1] =
9260 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9261 if (DeserializationListener)
9262 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9263 }
9264
9265 return SelectorsLoaded[ID - 1];
9266}
9267
9269 return DecodeSelector(ID);
9270}
9271
9273 // ID 0 (the null selector) is considered an external selector.
9274 return getTotalNumSelectors() + 1;
9275}
9276
9278ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9279 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9280 return LocalID;
9281
9282 if (!M.ModuleOffsetMap.empty())
9283 ReadModuleOffsetMap(M);
9284
9287 assert(I != M.SelectorRemap.end()
9288 && "Invalid index into selector index remap");
9289
9290 return LocalID + I->second;
9291}
9292
9295 switch (Name.getNameKind()) {
9300
9303
9307
9314 break;
9315 }
9316 return DeclarationNameLoc();
9317}
9318
9320 DeclarationNameInfo NameInfo;
9321 NameInfo.setName(readDeclarationName());
9322 NameInfo.setLoc(readSourceLocation());
9323 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
9324 return NameInfo;
9325}
9326
9328 return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool());
9329}
9330
9333 unsigned NumTPLists = readInt();
9334 Info.NumTemplParamLists = NumTPLists;
9335 if (NumTPLists) {
9336 Info.TemplParamLists =
9337 new (getContext()) TemplateParameterList *[NumTPLists];
9338 for (unsigned i = 0; i != NumTPLists; ++i)
9340 }
9341}
9342
9345 SourceLocation TemplateLoc = readSourceLocation();
9346 SourceLocation LAngleLoc = readSourceLocation();
9347 SourceLocation RAngleLoc = readSourceLocation();
9348
9349 unsigned NumParams = readInt();
9351 Params.reserve(NumParams);
9352 while (NumParams--)
9353 Params.push_back(readDeclAs<NamedDecl>());
9354
9355 bool HasRequiresClause = readBool();
9356 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
9357
9359 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
9360 return TemplateParams;
9361}
9362
9365 bool Canonicalize) {
9366 unsigned NumTemplateArgs = readInt();
9367 TemplArgs.reserve(NumTemplateArgs);
9368 while (NumTemplateArgs--)
9369 TemplArgs.push_back(readTemplateArgument(Canonicalize));
9370}
9371
9372/// Read a UnresolvedSet structure.
9374 unsigned NumDecls = readInt();
9375 Set.reserve(getContext(), NumDecls);
9376 while (NumDecls--) {
9377 GlobalDeclID ID = readDeclID();
9379 Set.addLazyDecl(getContext(), ID, AS);
9380 }
9381}
9382
9385 bool isVirtual = readBool();
9386 bool isBaseOfClass = readBool();
9387 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
9388 bool inheritConstructors = readBool();
9391 SourceLocation EllipsisLoc = readSourceLocation();
9392 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
9393 EllipsisLoc);
9394 Result.setInheritConstructors(inheritConstructors);
9395 return Result;
9396}
9397
9400 ASTContext &Context = getContext();
9401 unsigned NumInitializers = readInt();
9402 assert(NumInitializers && "wrote ctor initializers but have no inits");
9403 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
9404 for (unsigned i = 0; i != NumInitializers; ++i) {
9405 TypeSourceInfo *TInfo = nullptr;
9406 bool IsBaseVirtual = false;
9407 FieldDecl *Member = nullptr;
9408 IndirectFieldDecl *IndirectMember = nullptr;
9409
9411 switch (Type) {
9413 TInfo = readTypeSourceInfo();
9414 IsBaseVirtual = readBool();
9415 break;
9416
9418 TInfo = readTypeSourceInfo();
9419 break;
9420
9422 Member = readDeclAs<FieldDecl>();
9423 break;
9424
9426 IndirectMember = readDeclAs<IndirectFieldDecl>();
9427 break;
9428 }
9429
9430 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
9431 Expr *Init = readExpr();
9432 SourceLocation LParenLoc = readSourceLocation();
9433 SourceLocation RParenLoc = readSourceLocation();
9434
9435 CXXCtorInitializer *BOMInit;
9437 BOMInit = new (Context)
9438 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9439 RParenLoc, MemberOrEllipsisLoc);
9441 BOMInit = new (Context)
9442 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
9443 else if (Member)
9444 BOMInit = new (Context)
9445 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9446 Init, RParenLoc);
9447 else
9448 BOMInit = new (Context)
9449 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9450 LParenLoc, Init, RParenLoc);
9451
9452 if (/*IsWritten*/readBool()) {
9453 unsigned SourceOrder = readInt();
9454 BOMInit->setSourceOrder(SourceOrder);
9455 }
9456
9457 CtorInitializers[i] = BOMInit;
9458 }
9459
9460 return CtorInitializers;
9461}
9462
9465 ASTContext &Context = getContext();
9466 unsigned N = readInt();
9468 for (unsigned I = 0; I != N; ++I) {
9469 auto Kind = readNestedNameSpecifierKind();
9470 switch (Kind) {
9474 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9475 break;
9476 }
9477
9479 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
9481 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9482 break;
9483 }
9484
9486 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
9488 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9489 break;
9490 }
9491
9494 bool Template = readBool();
9496 if (!T)
9497 return NestedNameSpecifierLoc();
9498 SourceLocation ColonColonLoc = readSourceLocation();
9499
9500 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
9501 Builder.Extend(Context,
9502 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9503 T->getTypeLoc(), ColonColonLoc);
9504 break;
9505 }
9506
9508 SourceLocation ColonColonLoc = readSourceLocation();
9509 Builder.MakeGlobal(Context, ColonColonLoc);
9510 break;
9511 }
9512
9514 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
9516 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9517 break;
9518 }
9519 }
9520 }
9521
9522 return Builder.getWithLocInContext(Context);
9523}
9524
9526 unsigned &Idx, LocSeq *Seq) {
9529 return SourceRange(beg, end);
9530}
9531
9533 const StringRef Blob) {
9534 unsigned Count = Record[0];
9535 const char *Byte = Blob.data();
9536 llvm::BitVector Ret = llvm::BitVector(Count, false);
9537 for (unsigned I = 0; I < Count; ++Byte)
9538 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
9539 if (*Byte & (1 << Bit))
9540 Ret[I] = true;
9541 return Ret;
9542}
9543
9544/// Read a floating-point value
9545llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9546 return llvm::APFloat(Sem, readAPInt());
9547}
9548
9549// Read a string
9550std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
9551 unsigned Len = Record[Idx++];
9552 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9553 Idx += Len;
9554 return Result;
9555}
9556
9558 unsigned &Idx) {
9559 std::string Filename = ReadString(Record, Idx);
9561 return Filename;
9562}
9563
9564std::string ASTReader::ReadPath(StringRef BaseDirectory,
9565 const RecordData &Record, unsigned &Idx) {
9566 std::string Filename = ReadString(Record, Idx);
9567 if (!BaseDirectory.empty())
9568 ResolveImportedPath(Filename, BaseDirectory);
9569 return Filename;
9570}
9571
9573 unsigned &Idx) {
9574 unsigned Major = Record[Idx++];
9575 unsigned Minor = Record[Idx++];
9576 unsigned Subminor = Record[Idx++];
9577 if (Minor == 0)
9578 return VersionTuple(Major);
9579 if (Subminor == 0)
9580 return VersionTuple(Major, Minor - 1);
9581 return VersionTuple(Major, Minor - 1, Subminor - 1);
9582}
9583
9585 const RecordData &Record,
9586 unsigned &Idx) {
9587 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9589}
9590
9591DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9592 return Diag(CurrentImportLoc, DiagID);
9593}
9594
9596 return Diags.Report(Loc, DiagID);
9597}
9598
9600 // When Sema is available, avoid duplicate errors.
9601 if (SemaObj) {
9602 SemaObj->warnStackExhausted(Loc);
9603 return;
9604 }
9605
9606 if (WarnedStackExhausted)
9607 return;
9608 WarnedStackExhausted = true;
9609
9610 Diag(Loc, diag::warn_stack_exhausted);
9611}
9612
9613/// Retrieve the identifier table associated with the
9614/// preprocessor.
9616 return PP.getIdentifierTable();
9617}
9618
9619/// Record that the given ID maps to the given switch-case
9620/// statement.
9622 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9623 "Already have a SwitchCase with this ID");
9624 (*CurrSwitchCaseStmts)[ID] = SC;
9625}
9626
9627/// Retrieve the switch-case statement with the given ID.
9629 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9630 return (*CurrSwitchCaseStmts)[ID];
9631}
9632
9634 CurrSwitchCaseStmts->clear();
9635}
9636
9638 ASTContext &Context = getContext();
9639 std::vector<RawComment *> Comments;
9640 for (SmallVectorImpl<std::pair<BitstreamCursor,
9641 serialization::ModuleFile *>>::iterator
9642 I = CommentsCursors.begin(),
9643 E = CommentsCursors.end();
9644 I != E; ++I) {
9645 Comments.clear();
9646 BitstreamCursor &Cursor = I->first;
9647 serialization::ModuleFile &F = *I->second;
9648 SavedStreamPosition SavedPosition(Cursor);
9649
9651 while (true) {
9653 Cursor.advanceSkippingSubblocks(
9654 BitstreamCursor::AF_DontPopBlockAtEnd);
9655 if (!MaybeEntry) {
9656 Error(MaybeEntry.takeError());
9657 return;
9658 }
9659 llvm::BitstreamEntry Entry = MaybeEntry.get();
9660
9661 switch (Entry.Kind) {
9662 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9663 case llvm::BitstreamEntry::Error:
9664 Error("malformed block record in AST file");
9665 return;
9666 case llvm::BitstreamEntry::EndBlock:
9667 goto NextCursor;
9668 case llvm::BitstreamEntry::Record:
9669 // The interesting case.
9670 break;
9671 }
9672
9673 // Read a record.
9674 Record.clear();
9675 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9676 if (!MaybeComment) {
9677 Error(MaybeComment.takeError());
9678 return;
9679 }
9680 switch ((CommentRecordTypes)MaybeComment.get()) {
9681 case COMMENTS_RAW_COMMENT: {
9682 unsigned Idx = 0;
9683 SourceRange SR = ReadSourceRange(F, Record, Idx);
9686 bool IsTrailingComment = Record[Idx++];
9687 bool IsAlmostTrailingComment = Record[Idx++];
9688 Comments.push_back(new (Context) RawComment(
9689 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9690 break;
9691 }
9692 }
9693 }
9694 NextCursor:
9695 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9696 FileToOffsetToComment;
9697 for (RawComment *C : Comments) {
9698 SourceLocation CommentLoc = C->getBeginLoc();
9699 if (CommentLoc.isValid()) {
9700 std::pair<FileID, unsigned> Loc =
9701 SourceMgr.getDecomposedLoc(CommentLoc);
9702 if (Loc.first.isValid())
9703 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9704 }
9705 }
9706 }
9707}
9708
9710 serialization::ModuleFile &MF, bool IncludeSystem,
9711 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
9712 bool IsSystem)>
9713 Visitor) {
9714 unsigned NumUserInputs = MF.NumUserInputFiles;
9715 unsigned NumInputs = MF.InputFilesLoaded.size();
9716 assert(NumUserInputs <= NumInputs);
9717 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9718 for (unsigned I = 0; I < N; ++I) {
9719 bool IsSystem = I >= NumUserInputs;
9720 InputFileInfo IFI = getInputFileInfo(MF, I+1);
9721 Visitor(IFI, IsSystem);
9722 }
9723}
9724
9726 bool IncludeSystem, bool Complain,
9727 llvm::function_ref<void(const serialization::InputFile &IF,
9728 bool isSystem)> Visitor) {
9729 unsigned NumUserInputs = MF.NumUserInputFiles;
9730 unsigned NumInputs = MF.InputFilesLoaded.size();
9731 assert(NumUserInputs <= NumInputs);
9732 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9733 for (unsigned I = 0; I < N; ++I) {
9734 bool IsSystem = I >= NumUserInputs;
9735 InputFile IF = getInputFile(MF, I+1, Complain);
9736 Visitor(IF, IsSystem);
9737 }
9738}
9739
9742 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
9743 unsigned NumInputs = MF.InputFilesLoaded.size();
9744 for (unsigned I = 0; I < NumInputs; ++I) {
9745 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
9746 if (IFI.TopLevel && IFI.ModuleMap)
9747 if (auto FE = getInputFile(MF, I + 1).getFile())
9748 Visitor(*FE);
9749 }
9750}
9751
9752void ASTReader::finishPendingActions() {
9753 while (
9754 !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() ||
9755 !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() ||
9756 !PendingDeclChains.empty() || !PendingMacroIDs.empty() ||
9757 !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() ||
9758 !PendingObjCExtensionIvarRedeclarations.empty()) {
9759 // If any identifiers with corresponding top-level declarations have
9760 // been loaded, load those declarations now.
9761 using TopLevelDeclsMap =
9762 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9763 TopLevelDeclsMap TopLevelDecls;
9764
9765 while (!PendingIdentifierInfos.empty()) {
9766 IdentifierInfo *II = PendingIdentifierInfos.back().first;
9768 std::move(PendingIdentifierInfos.back().second);
9769 PendingIdentifierInfos.pop_back();
9770
9771 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9772 }
9773
9774 // Load each function type that we deferred loading because it was a
9775 // deduced type that might refer to a local type declared within itself.
9776 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
9777 auto *FD = PendingDeducedFunctionTypes[I].first;
9778 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
9779
9780 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
9781 // If we gave a function a deduced return type, remember that we need to
9782 // propagate that along the redeclaration chain.
9783 if (DT->isDeduced()) {
9784 PendingDeducedTypeUpdates.insert(
9785 {FD->getCanonicalDecl(), FD->getReturnType()});
9786 continue;
9787 }
9788
9789 // The function has undeduced DeduceType return type. We hope we can
9790 // find the deduced type by iterating the redecls in other modules
9791 // later.
9792 PendingUndeducedFunctionDecls.push_back(FD);
9793 continue;
9794 }
9795 }
9796 PendingDeducedFunctionTypes.clear();
9797
9798 // Load each variable type that we deferred loading because it was a
9799 // deduced type that might refer to a local type declared within itself.
9800 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
9801 auto *VD = PendingDeducedVarTypes[I].first;
9802 VD->setType(GetType(PendingDeducedVarTypes[I].second));
9803 }
9804 PendingDeducedVarTypes.clear();
9805
9806 // For each decl chain that we wanted to complete while deserializing, mark
9807 // it as "still needs to be completed".
9808 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9809 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9810 }
9811 PendingIncompleteDeclChains.clear();
9812
9813 // Load pending declaration chains.
9814 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9815 loadPendingDeclChain(PendingDeclChains[I].first,
9816 PendingDeclChains[I].second);
9817 PendingDeclChains.clear();
9818
9819 // Make the most recent of the top-level declarations visible.
9820 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9821 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9822 IdentifierInfo *II = TLD->first;
9823 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9824 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9825 }
9826 }
9827
9828 // Load any pending macro definitions.
9829 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9830 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9832 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9833 // Initialize the macro history from chained-PCHs ahead of module imports.
9834 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9835 ++IDIdx) {
9836 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9837 if (!Info.M->isModule())
9838 resolvePendingMacro(II, Info);
9839 }
9840 // Handle module imports.
9841 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9842 ++IDIdx) {
9843 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9844 if (Info.M->isModule())
9845 resolvePendingMacro(II, Info);
9846 }
9847 }
9848 PendingMacroIDs.clear();
9849
9850 // Wire up the DeclContexts for Decls that we delayed setting until
9851 // recursive loading is completed.
9852 while (!PendingDeclContextInfos.empty()) {
9853 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9854 PendingDeclContextInfos.pop_front();
9855 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9856 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9857 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9858 }
9859
9860 // Perform any pending declaration updates.
9861 while (!PendingUpdateRecords.empty()) {
9862 auto Update = PendingUpdateRecords.pop_back_val();
9863 ReadingKindTracker ReadingKind(Read_Decl, *this);
9864 loadDeclUpdateRecords(Update);
9865 }
9866
9867 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
9868 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
9869 auto DuplicateIvars =
9870 PendingObjCExtensionIvarRedeclarations.back().second;
9871 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9873 ExtensionsPair.first->getASTContext(),
9874 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
9875 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
9876 /*Complain =*/false,
9877 /*ErrorOnTagTypeMismatch =*/true);
9878 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
9879 // Merge redeclared ivars with their predecessors.
9880 for (auto IvarPair : DuplicateIvars) {
9881 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
9882 // Change semantic DeclContext but keep the lexical one.
9883 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
9884 Ivar->getLexicalDeclContext(),
9885 getContext());
9886 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
9887 }
9888 // Invalidate duplicate extension and the cached ivar list.
9889 ExtensionsPair.first->setInvalidDecl();
9890 ExtensionsPair.second->getClassInterface()
9891 ->getDefinition()
9892 ->setIvarList(nullptr);
9893 } else {
9894 for (auto IvarPair : DuplicateIvars) {
9895 Diag(IvarPair.first->getLocation(),
9896 diag::err_duplicate_ivar_declaration)
9897 << IvarPair.first->getIdentifier();
9898 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
9899 }
9900 }
9901 PendingObjCExtensionIvarRedeclarations.pop_back();
9902 }
9903 }
9904
9905 // At this point, all update records for loaded decls are in place, so any
9906 // fake class definitions should have become real.
9907 assert(PendingFakeDefinitionData.empty() &&
9908 "faked up a class definition but never saw the real one");
9909
9910 // If we deserialized any C++ or Objective-C class definitions, any
9911 // Objective-C protocol definitions, or any redeclarable templates, make sure
9912 // that all redeclarations point to the definitions. Note that this can only
9913 // happen now, after the redeclaration chains have been fully wired.
9914 for (Decl *D : PendingDefinitions) {
9915 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9916 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9917 // Make sure that the TagType points at the definition.
9918 const_cast<TagType*>(TagT)->decl = TD;
9919 }
9920
9921 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9922 for (auto *R = getMostRecentExistingDecl(RD); R;
9923 R = R->getPreviousDecl()) {
9924 assert((R == D) ==
9925 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9926 "declaration thinks it's the definition but it isn't");
9927 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9928 }
9929 }
9930
9931 continue;
9932 }
9933
9934 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9935 // Make sure that the ObjCInterfaceType points at the definition.
9936 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9937 ->Decl = ID;
9938
9939 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9940 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9941
9942 continue;
9943 }
9944
9945 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9946 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9947 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9948
9949 continue;
9950 }
9951
9952 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9953 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9954 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9955 }
9956 PendingDefinitions.clear();
9957
9958 // Load the bodies of any functions or methods we've encountered. We do
9959 // this now (delayed) so that we can be sure that the declaration chains
9960 // have been fully wired up (hasBody relies on this).
9961 // FIXME: We shouldn't require complete redeclaration chains here.
9962 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9963 PBEnd = PendingBodies.end();
9964 PB != PBEnd; ++PB) {
9965 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9966 // For a function defined inline within a class template, force the
9967 // canonical definition to be the one inside the canonical definition of
9968 // the template. This ensures that we instantiate from a correct view
9969 // of the template.
9970 //
9971 // Sadly we can't do this more generally: we can't be sure that all
9972 // copies of an arbitrary class definition will have the same members
9973 // defined (eg, some member functions may not be instantiated, and some
9974 // special members may or may not have been implicitly defined).
9975 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9977 continue;
9978
9979 // FIXME: Check for =delete/=default?
9980 const FunctionDecl *Defn = nullptr;
9981 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9982 FD->setLazyBody(PB->second);
9983 } else {
9984 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9985 mergeDefinitionVisibility(NonConstDefn, FD);
9986
9987 if (!FD->isLateTemplateParsed() &&
9988 !NonConstDefn->isLateTemplateParsed() &&
9989 // We only perform ODR checks for decls not in the explicit
9990 // global module fragment.
9991 !shouldSkipCheckingODR(FD) &&
9992 !shouldSkipCheckingODR(NonConstDefn) &&
9993 FD->getODRHash() != NonConstDefn->getODRHash()) {
9994 if (!isa<CXXMethodDecl>(FD)) {
9995 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9996 } else if (FD->getLexicalParent()->isFileContext() &&
9997 NonConstDefn->getLexicalParent()->isFileContext()) {
9998 // Only diagnose out-of-line method definitions. If they are
9999 // in class definitions, then an error will be generated when
10000 // processing the class bodies.
10001 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10002 }
10003 }
10004 }
10005 continue;
10006 }
10007
10008 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
10009 if (!getContext().getLangOpts().Modules || !MD->hasBody())
10010 MD->setLazyBody(PB->second);
10011 }
10012 PendingBodies.clear();
10013
10014 // Inform any classes that had members added that they now have more members.
10015 for (auto [RD, MD] : PendingAddedClassMembers) {
10016 RD->addedMember(MD);
10017 }
10018 PendingAddedClassMembers.clear();
10019
10020 // Do some cleanup.
10021 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10023 PendingMergedDefinitionsToDeduplicate.clear();
10024}
10025
10026void ASTReader::diagnoseOdrViolations() {
10027 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
10028 PendingRecordOdrMergeFailures.empty() &&
10029 PendingFunctionOdrMergeFailures.empty() &&
10030 PendingEnumOdrMergeFailures.empty() &&
10031 PendingObjCInterfaceOdrMergeFailures.empty() &&
10032 PendingObjCProtocolOdrMergeFailures.empty())
10033 return;
10034
10035 // Trigger the import of the full definition of each class that had any
10036 // odr-merging problems, so we can produce better diagnostics for them.
10037 // These updates may in turn find and diagnose some ODR failures, so take
10038 // ownership of the set first.
10039 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10040 PendingOdrMergeFailures.clear();
10041 for (auto &Merge : OdrMergeFailures) {
10042 Merge.first->buildLookup();
10043 Merge.first->decls_begin();
10044 Merge.first->bases_begin();
10045 Merge.first->vbases_begin();
10046 for (auto &RecordPair : Merge.second) {
10047 auto *RD = RecordPair.first;
10048 RD->decls_begin();
10049 RD->bases_begin();
10050 RD->vbases_begin();
10051 }
10052 }
10053
10054 // Trigger the import of the full definition of each record in C/ObjC.
10055 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
10056 PendingRecordOdrMergeFailures.clear();
10057 for (auto &Merge : RecordOdrMergeFailures) {
10058 Merge.first->decls_begin();
10059 for (auto &D : Merge.second)
10060 D->decls_begin();
10061 }
10062
10063 // Trigger the import of the full interface definition.
10064 auto ObjCInterfaceOdrMergeFailures =
10065 std::move(PendingObjCInterfaceOdrMergeFailures);
10066 PendingObjCInterfaceOdrMergeFailures.clear();
10067 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10068 Merge.first->decls_begin();
10069 for (auto &InterfacePair : Merge.second)
10070 InterfacePair.first->decls_begin();
10071 }
10072
10073 // Trigger the import of functions.
10074 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10075 PendingFunctionOdrMergeFailures.clear();
10076 for (auto &Merge : FunctionOdrMergeFailures) {
10077 Merge.first->buildLookup();
10078 Merge.first->decls_begin();
10079 Merge.first->getBody();
10080 for (auto &FD : Merge.second) {
10081 FD->buildLookup();
10082 FD->decls_begin();
10083 FD->getBody();
10084 }
10085 }
10086
10087 // Trigger the import of enums.
10088 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10089 PendingEnumOdrMergeFailures.clear();
10090 for (auto &Merge : EnumOdrMergeFailures) {
10091 Merge.first->decls_begin();
10092 for (auto &Enum : Merge.second) {
10093 Enum->decls_begin();
10094 }
10095 }
10096
10097 // Trigger the import of the full protocol definition.
10098 auto ObjCProtocolOdrMergeFailures =
10099 std::move(PendingObjCProtocolOdrMergeFailures);
10100 PendingObjCProtocolOdrMergeFailures.clear();
10101 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10102 Merge.first->decls_begin();
10103 for (auto &ProtocolPair : Merge.second)
10104 ProtocolPair.first->decls_begin();
10105 }
10106
10107 // For each declaration from a merged context, check that the canonical
10108 // definition of that context also contains a declaration of the same
10109 // entity.
10110 //
10111 // Caution: this loop does things that might invalidate iterators into
10112 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10113 while (!PendingOdrMergeChecks.empty()) {
10114 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10115
10116 // FIXME: Skip over implicit declarations for now. This matters for things
10117 // like implicitly-declared special member functions. This isn't entirely
10118 // correct; we can end up with multiple unmerged declarations of the same
10119 // implicit entity.
10120 if (D->isImplicit())
10121 continue;
10122
10123 DeclContext *CanonDef = D->getDeclContext();
10124
10125 bool Found = false;
10126 const Decl *DCanon = D->getCanonicalDecl();
10127
10128 for (auto *RI : D->redecls()) {
10129 if (RI->getLexicalDeclContext() == CanonDef) {
10130 Found = true;
10131 break;
10132 }
10133 }
10134 if (Found)
10135 continue;
10136
10137 // Quick check failed, time to do the slow thing. Note, we can't just
10138 // look up the name of D in CanonDef here, because the member that is
10139 // in CanonDef might not be found by name lookup (it might have been
10140 // replaced by a more recent declaration in the lookup table), and we
10141 // can't necessarily find it in the redeclaration chain because it might
10142 // be merely mergeable, not redeclarable.
10144 for (auto *CanonMember : CanonDef->decls()) {
10145 if (CanonMember->getCanonicalDecl() == DCanon) {
10146 // This can happen if the declaration is merely mergeable and not
10147 // actually redeclarable (we looked for redeclarations earlier).
10148 //
10149 // FIXME: We should be able to detect this more efficiently, without
10150 // pulling in all of the members of CanonDef.
10151 Found = true;
10152 break;
10153 }
10154 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10155 if (ND->getDeclName() == D->getDeclName())
10156 Candidates.push_back(ND);
10157 }
10158
10159 if (!Found) {
10160 // The AST doesn't like TagDecls becoming invalid after they've been
10161 // completed. We only really need to mark FieldDecls as invalid here.
10162 if (!isa<TagDecl>(D))
10163 D->setInvalidDecl();
10164
10165 // Ensure we don't accidentally recursively enter deserialization while
10166 // we're producing our diagnostic.
10167 Deserializing RecursionGuard(this);
10168
10169 std::string CanonDefModule =
10171 cast<Decl>(CanonDef));
10172 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10174 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10175
10176 if (Candidates.empty())
10177 Diag(cast<Decl>(CanonDef)->getLocation(),
10178 diag::note_module_odr_violation_no_possible_decls) << D;
10179 else {
10180 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10181 Diag(Candidates[I]->getLocation(),
10182 diag::note_module_odr_violation_possible_decl)
10183 << Candidates[I];
10184 }
10185
10186 DiagnosedOdrMergeFailures.insert(CanonDef);
10187 }
10188 }
10189
10190 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
10191 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
10192 ObjCInterfaceOdrMergeFailures.empty() &&
10193 ObjCProtocolOdrMergeFailures.empty())
10194 return;
10195
10196 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
10197 getPreprocessor().getLangOpts());
10198
10199 // Issue any pending ODR-failure diagnostics.
10200 for (auto &Merge : OdrMergeFailures) {
10201 // If we've already pointed out a specific problem with this class, don't
10202 // bother issuing a general "something's different" diagnostic.
10203 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10204 continue;
10205
10206 bool Diagnosed = false;
10207 CXXRecordDecl *FirstRecord = Merge.first;
10208 for (auto &RecordPair : Merge.second) {
10209 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
10210 RecordPair.second)) {
10211 Diagnosed = true;
10212 break;
10213 }
10214 }
10215
10216 if (!Diagnosed) {
10217 // All definitions are updates to the same declaration. This happens if a
10218 // module instantiates the declaration of a class template specialization
10219 // and two or more other modules instantiate its definition.
10220 //
10221 // FIXME: Indicate which modules had instantiations of this definition.
10222 // FIXME: How can this even happen?
10223 Diag(Merge.first->getLocation(),
10224 diag::err_module_odr_violation_different_instantiations)
10225 << Merge.first;
10226 }
10227 }
10228
10229 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
10230 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
10231 for (auto &Merge : RecordOdrMergeFailures) {
10232 // If we've already pointed out a specific problem with this class, don't
10233 // bother issuing a general "something's different" diagnostic.
10234 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10235 continue;
10236
10237 RecordDecl *FirstRecord = Merge.first;
10238 bool Diagnosed = false;
10239 for (auto *SecondRecord : Merge.second) {
10240 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
10241 Diagnosed = true;
10242 break;
10243 }
10244 }
10245 (void)Diagnosed;
10246 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10247 }
10248
10249 // Issue ODR failures diagnostics for functions.
10250 for (auto &Merge : FunctionOdrMergeFailures) {
10251 FunctionDecl *FirstFunction = Merge.first;
10252 bool Diagnosed = false;
10253 for (auto &SecondFunction : Merge.second) {
10254 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
10255 Diagnosed = true;
10256 break;
10257 }
10258 }
10259 (void)Diagnosed;
10260 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10261 }
10262
10263 // Issue ODR failures diagnostics for enums.
10264 for (auto &Merge : EnumOdrMergeFailures) {
10265 // If we've already pointed out a specific problem with this enum, don't
10266 // bother issuing a general "something's different" diagnostic.
10267 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10268 continue;
10269
10270 EnumDecl *FirstEnum = Merge.first;
10271 bool Diagnosed = false;
10272 for (auto &SecondEnum : Merge.second) {
10273 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
10274 Diagnosed = true;
10275 break;
10276 }
10277 }
10278 (void)Diagnosed;
10279 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10280 }
10281
10282 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10283 // If we've already pointed out a specific problem with this interface,
10284 // don't bother issuing a general "something's different" diagnostic.
10285 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10286 continue;
10287
10288 bool Diagnosed = false;
10289 ObjCInterfaceDecl *FirstID = Merge.first;
10290 for (auto &InterfacePair : Merge.second) {
10291 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
10292 InterfacePair.second)) {
10293 Diagnosed = true;
10294 break;
10295 }
10296 }
10297 (void)Diagnosed;
10298 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10299 }
10300
10301 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10302 // If we've already pointed out a specific problem with this protocol,
10303 // don't bother issuing a general "something's different" diagnostic.
10304 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10305 continue;
10306
10307 ObjCProtocolDecl *FirstProtocol = Merge.first;
10308 bool Diagnosed = false;
10309 for (auto &ProtocolPair : Merge.second) {
10310 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
10311 ProtocolPair.second)) {
10312 Diagnosed = true;
10313 break;
10314 }
10315 }
10316 (void)Diagnosed;
10317 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10318 }
10319}
10320
10322 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
10323 ReadTimer->startTimer();
10324}
10325
10327 assert(NumCurrentElementsDeserializing &&
10328 "FinishedDeserializing not paired with StartedDeserializing");
10329 if (NumCurrentElementsDeserializing == 1) {
10330 // We decrease NumCurrentElementsDeserializing only after pending actions
10331 // are finished, to avoid recursively re-calling finishPendingActions().
10332 finishPendingActions();
10333 }
10334 --NumCurrentElementsDeserializing;
10335
10336 if (NumCurrentElementsDeserializing == 0) {
10337 // Propagate exception specification and deduced type updates along
10338 // redeclaration chains.
10339 //
10340 // We do this now rather than in finishPendingActions because we want to
10341 // be able to walk the complete redeclaration chains of the updated decls.
10342 while (!PendingExceptionSpecUpdates.empty() ||
10343 !PendingDeducedTypeUpdates.empty()) {
10344 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
10345 PendingExceptionSpecUpdates.clear();
10346 for (auto Update : ESUpdates) {
10347 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10348 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
10349 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
10350 if (auto *Listener = getContext().getASTMutationListener())
10351 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
10352 for (auto *Redecl : Update.second->redecls())
10353 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
10354 }
10355
10356 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
10357 PendingDeducedTypeUpdates.clear();
10358 for (auto Update : DTUpdates) {
10359 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10360 // FIXME: If the return type is already deduced, check that it matches.
10362 Update.second);
10363 }
10364
10365 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
10366 PendingUndeducedFunctionDecls.clear();
10367 // We hope we can find the deduced type for the functions by iterating
10368 // redeclarations in other modules.
10369 for (FunctionDecl *UndeducedFD : UDTUpdates)
10370 (void)UndeducedFD->getMostRecentDecl();
10371 }
10372
10373 if (ReadTimer)
10374 ReadTimer->stopTimer();
10375
10376 diagnoseOdrViolations();
10377
10378 // We are not in recursive loading, so it's safe to pass the "interesting"
10379 // decls to the consumer.
10380 if (Consumer)
10381 PassInterestingDeclsToConsumer();
10382 }
10383}
10384
10385void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
10386 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10387 // Remove any fake results before adding any real ones.
10388 auto It = PendingFakeLookupResults.find(II);
10389 if (It != PendingFakeLookupResults.end()) {
10390 for (auto *ND : It->second)
10391 SemaObj->IdResolver.RemoveDecl(ND);
10392 // FIXME: this works around module+PCH performance issue.
10393 // Rather than erase the result from the map, which is O(n), just clear
10394 // the vector of NamedDecls.
10395 It->second.clear();
10396 }
10397 }
10398
10399 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10400 SemaObj->TUScope->AddDecl(D);
10401 } else if (SemaObj->TUScope) {
10402 // Adding the decl to IdResolver may have failed because it was already in
10403 // (even though it was not added in scope). If it is already in, make sure
10404 // it gets in the scope as well.
10405 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
10406 SemaObj->TUScope->AddDecl(D);
10407 }
10408}
10409
10411 ASTContext *Context,
10412 const PCHContainerReader &PCHContainerRdr,
10413 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10414 StringRef isysroot,
10415 DisableValidationForModuleKind DisableValidationKind,
10416 bool AllowASTWithCompilerErrors,
10417 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10418 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
10419 std::unique_ptr<llvm::Timer> ReadTimer)
10420 : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
10422 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
10423 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
10424 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
10425 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
10426 PCHContainerRdr, PP.getHeaderSearchInfo()),
10427 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
10428 DisableValidationKind(DisableValidationKind),
10429 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10430 AllowConfigurationMismatch(AllowConfigurationMismatch),
10431 ValidateSystemInputs(ValidateSystemInputs),
10432 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
10433 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
10434 SourceMgr.setExternalSLocEntrySource(this);
10435
10436 for (const auto &Ext : Extensions) {
10437 auto BlockName = Ext->getExtensionMetadata().BlockName;
10438 auto Known = ModuleFileExtensions.find(BlockName);
10439 if (Known != ModuleFileExtensions.end()) {
10440 Diags.Report(diag::warn_duplicate_module_file_extension)
10441 << BlockName;
10442 continue;
10443 }
10444
10445 ModuleFileExtensions.insert({BlockName, Ext});
10446 }
10447}
10448
10450 if (OwnsDeserializationListener)
10451 delete DeserializationListener;
10452}
10453
10455 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10456}
10457
10459 unsigned AbbrevID) {
10460 Idx = 0;
10461 Record.clear();
10462 return Cursor.readRecord(AbbrevID, Record);
10463}
10464//===----------------------------------------------------------------------===//
10465//// OMPClauseReader implementation
10466////===----------------------------------------------------------------------===//
10467
10468// This has to be in namespace clang because it's friended by all
10469// of the OMP clauses.
10470namespace clang {
10471
10472class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
10474 ASTContext &Context;
10475
10476public:
10478 : Record(Record), Context(Record.getContext()) {}
10479#define GEN_CLANG_CLAUSE_CLASS
10480#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
10481#include "llvm/Frontend/OpenMP/OMP.inc"
10485};
10486
10487} // end namespace clang
10488
10490 return OMPClauseReader(*this).readClause();
10491}
10492
10494 OMPClause *C = nullptr;
10495 switch (llvm::omp::Clause(Record.readInt())) {
10496 case llvm::omp::OMPC_if:
10497 C = new (Context) OMPIfClause();
10498 break;
10499 case llvm::omp::OMPC_final:
10500 C = new (Context) OMPFinalClause();
10501 break;
10502 case llvm::omp::OMPC_num_threads:
10503 C = new (Context) OMPNumThreadsClause();
10504 break;
10505 case llvm::omp::OMPC_safelen:
10506 C = new (Context) OMPSafelenClause();
10507 break;
10508 case llvm::omp::OMPC_simdlen:
10509 C = new (Context) OMPSimdlenClause();
10510 break;
10511 case llvm::omp::OMPC_sizes: {
10512 unsigned NumSizes = Record.readInt();
10513 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
10514 break;
10515 }
10516 case llvm::omp::OMPC_full:
10517 C = OMPFullClause::CreateEmpty(Context);
10518 break;
10519 case llvm::omp::OMPC_partial:
10521 break;
10522 case llvm::omp::OMPC_allocator:
10523 C = new (Context) OMPAllocatorClause();
10524 break;
10525 case llvm::omp::OMPC_collapse:
10526 C = new (Context) OMPCollapseClause();
10527 break;
10528 case llvm::omp::OMPC_default:
10529 C = new (Context) OMPDefaultClause();
10530 break;
10531 case llvm::omp::OMPC_proc_bind:
10532 C = new (Context) OMPProcBindClause();
10533 break;
10534 case llvm::omp::OMPC_schedule:
10535 C = new (Context) OMPScheduleClause();
10536 break;
10537 case llvm::omp::OMPC_ordered:
10538 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
10539 break;
10540 case llvm::omp::OMPC_nowait:
10541 C = new (Context) OMPNowaitClause();
10542 break;
10543 case llvm::omp::OMPC_untied:
10544 C = new (Context) OMPUntiedClause();
10545 break;
10546 case llvm::omp::OMPC_mergeable:
10547 C = new (Context) OMPMergeableClause();
10548 break;
10549 case llvm::omp::OMPC_read:
10550 C = new (Context) OMPReadClause();
10551 break;
10552 case llvm::omp::OMPC_write:
10553 C = new (Context) OMPWriteClause();
10554 break;
10555 case llvm::omp::OMPC_update:
10556 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
10557 break;
10558 case llvm::omp::OMPC_capture:
10559 C = new (Context) OMPCaptureClause();
10560 break;
10561 case llvm::omp::OMPC_compare:
10562 C = new (Context) OMPCompareClause();
10563 break;
10564 case llvm::omp::OMPC_fail:
10565 C = new (Context) OMPFailClause();
10566 break;
10567 case llvm::omp::OMPC_seq_cst:
10568 C = new (Context) OMPSeqCstClause();
10569 break;
10570 case llvm::omp::OMPC_acq_rel:
10571 C = new (Context) OMPAcqRelClause();
10572 break;
10573 case llvm::omp::OMPC_absent: {
10574 unsigned NumKinds = Record.readInt();
10575 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
10576 break;
10577 }
10578 case llvm::omp::OMPC_holds:
10579 C = new (Context) OMPHoldsClause();
10580 break;
10581 case llvm::omp::OMPC_contains: {
10582 unsigned NumKinds = Record.readInt();
10583 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
10584 break;
10585 }
10586 case llvm::omp::OMPC_no_openmp:
10587 C = new (Context) OMPNoOpenMPClause();
10588 break;
10589 case llvm::omp::OMPC_no_openmp_routines:
10590 C = new (Context) OMPNoOpenMPRoutinesClause();
10591 break;
10592 case llvm::omp::OMPC_no_parallelism:
10593 C = new (Context) OMPNoParallelismClause();
10594 break;
10595 case llvm::omp::OMPC_acquire:
10596 C = new (Context) OMPAcquireClause();
10597 break;
10598 case llvm::omp::OMPC_release:
10599 C = new (Context) OMPReleaseClause();
10600 break;
10601 case llvm::omp::OMPC_relaxed:
10602 C = new (Context) OMPRelaxedClause();
10603 break;
10604 case llvm::omp::OMPC_weak:
10605 C = new (Context) OMPWeakClause();
10606 break;
10607 case llvm::omp::OMPC_threads:
10608 C = new (Context) OMPThreadsClause();
10609 break;
10610 case llvm::omp::OMPC_simd:
10611 C = new (Context) OMPSIMDClause();
10612 break;
10613 case llvm::omp::OMPC_nogroup:
10614 C = new (Context) OMPNogroupClause();
10615 break;
10616 case llvm::omp::OMPC_unified_address:
10617 C = new (Context) OMPUnifiedAddressClause();
10618 break;
10619 case llvm::omp::OMPC_unified_shared_memory:
10620 C = new (Context) OMPUnifiedSharedMemoryClause();
10621 break;
10622 case llvm::omp::OMPC_reverse_offload:
10623 C = new (Context) OMPReverseOffloadClause();
10624 break;
10625 case llvm::omp::OMPC_dynamic_allocators:
10626 C = new (Context) OMPDynamicAllocatorsClause();
10627 break;
10628 case llvm::omp::OMPC_atomic_default_mem_order:
10629 C = new (Context) OMPAtomicDefaultMemOrderClause();
10630 break;
10631 case llvm::omp::OMPC_at:
10632 C = new (Context) OMPAtClause();
10633 break;
10634 case llvm::omp::OMPC_severity:
10635 C = new (Context) OMPSeverityClause();
10636 break;
10637 case llvm::omp::OMPC_message:
10638 C = new (Context) OMPMessageClause();
10639 break;
10640 case llvm::omp::OMPC_private:
10641 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
10642 break;
10643 case llvm::omp::OMPC_firstprivate:
10644 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
10645 break;
10646 case llvm::omp::OMPC_lastprivate:
10647 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
10648 break;
10649 case llvm::omp::OMPC_shared:
10650 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
10651 break;
10652 case llvm::omp::OMPC_reduction: {
10653 unsigned N = Record.readInt();
10654 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
10655 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
10656 break;
10657 }
10658 case llvm::omp::OMPC_task_reduction:
10659 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
10660 break;
10661 case llvm::omp::OMPC_in_reduction:
10662 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
10663 break;
10664 case llvm::omp::OMPC_linear:
10665 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
10666 break;
10667 case llvm::omp::OMPC_aligned:
10668 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
10669 break;
10670 case llvm::omp::OMPC_copyin:
10671 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
10672 break;
10673 case llvm::omp::OMPC_copyprivate:
10674 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
10675 break;
10676 case llvm::omp::OMPC_flush:
10677 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
10678 break;
10679 case llvm::omp::OMPC_depobj:
10681 break;
10682 case llvm::omp::OMPC_depend: {
10683 unsigned NumVars = Record.readInt();
10684 unsigned NumLoops = Record.readInt();
10685 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
10686 break;
10687 }
10688 case llvm::omp::OMPC_device:
10689 C = new (Context) OMPDeviceClause();
10690 break;
10691 case llvm::omp::OMPC_map: {
10693 Sizes.NumVars = Record.readInt();
10694 Sizes.NumUniqueDeclarations = Record.readInt();
10695 Sizes.NumComponentLists = Record.readInt();
10696 Sizes.NumComponents = Record.readInt();
10697 C = OMPMapClause::CreateEmpty(Context, Sizes);
10698 break;
10699 }
10700 case llvm::omp::OMPC_num_teams:
10701 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
10702 break;
10703 case llvm::omp::OMPC_thread_limit:
10704 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
10705 break;
10706 case llvm::omp::OMPC_priority:
10707 C = new (Context) OMPPriorityClause();
10708 break;
10709 case llvm::omp::OMPC_grainsize:
10710 C = new (Context) OMPGrainsizeClause();
10711 break;
10712 case llvm::omp::OMPC_num_tasks:
10713 C = new (Context) OMPNumTasksClause();
10714 break;
10715 case llvm::omp::OMPC_hint:
10716 C = new (Context) OMPHintClause();
10717 break;
10718 case llvm::omp::OMPC_dist_schedule:
10719 C = new (Context) OMPDistScheduleClause();
10720 break;
10721 case llvm::omp::OMPC_defaultmap:
10722 C = new (Context) OMPDefaultmapClause();
10723 break;
10724 case llvm::omp::OMPC_to: {
10726 Sizes.NumVars = Record.readInt();
10727 Sizes.NumUniqueDeclarations = Record.readInt();
10728 Sizes.NumComponentLists = Record.readInt();
10729 Sizes.NumComponents = Record.readInt();
10730 C = OMPToClause::CreateEmpty(Context, Sizes);
10731 break;
10732 }
10733 case llvm::omp::OMPC_from: {
10735 Sizes.NumVars = Record.readInt();
10736 Sizes.NumUniqueDeclarations = Record.readInt();
10737 Sizes.NumComponentLists = Record.readInt();
10738 Sizes.NumComponents = Record.readInt();
10739 C = OMPFromClause::CreateEmpty(Context, Sizes);
10740 break;
10741 }
10742 case llvm::omp::OMPC_use_device_ptr: {
10744 Sizes.NumVars = Record.readInt();
10745 Sizes.NumUniqueDeclarations = Record.readInt();
10746 Sizes.NumComponentLists = Record.readInt();
10747 Sizes.NumComponents = Record.readInt();
10748 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
10749 break;
10750 }
10751 case llvm::omp::OMPC_use_device_addr: {
10753 Sizes.NumVars = Record.readInt();
10754 Sizes.NumUniqueDeclarations = Record.readInt();
10755 Sizes.NumComponentLists = Record.readInt();
10756 Sizes.NumComponents = Record.readInt();
10757 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
10758 break;
10759 }
10760 case llvm::omp::OMPC_is_device_ptr: {
10762 Sizes.NumVars = Record.readInt();
10763 Sizes.NumUniqueDeclarations = Record.readInt();
10764 Sizes.NumComponentLists = Record.readInt();
10765 Sizes.NumComponents = Record.readInt();
10766 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
10767 break;
10768 }
10769 case llvm::omp::OMPC_has_device_addr: {
10771 Sizes.NumVars = Record.readInt();
10772 Sizes.NumUniqueDeclarations = Record.readInt();
10773 Sizes.NumComponentLists = Record.readInt();
10774 Sizes.NumComponents = Record.readInt();
10775 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
10776 break;
10777 }
10778 case llvm::omp::OMPC_allocate:
10779 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
10780 break;
10781 case llvm::omp::OMPC_nontemporal:
10782 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
10783 break;
10784 case llvm::omp::OMPC_inclusive:
10785 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
10786 break;
10787 case llvm::omp::OMPC_exclusive:
10788 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
10789 break;
10790 case llvm::omp::OMPC_order:
10791 C = new (Context) OMPOrderClause();
10792 break;
10793 case llvm::omp::OMPC_init:
10794 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
10795 break;
10796 case llvm::omp::OMPC_use:
10797 C = new (Context) OMPUseClause();
10798 break;
10799 case llvm::omp::OMPC_destroy:
10800 C = new (Context) OMPDestroyClause();
10801 break;
10802 case llvm::omp::OMPC_novariants:
10803 C = new (Context) OMPNovariantsClause();
10804 break;
10805 case llvm::omp::OMPC_nocontext:
10806 C = new (Context) OMPNocontextClause();
10807 break;
10808 case llvm::omp::OMPC_detach:
10809 C = new (Context) OMPDetachClause();
10810 break;
10811 case llvm::omp::OMPC_uses_allocators:
10812 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
10813 break;
10814 case llvm::omp::OMPC_affinity:
10815 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
10816 break;
10817 case llvm::omp::OMPC_filter:
10818 C = new (Context) OMPFilterClause();
10819 break;
10820 case llvm::omp::OMPC_bind:
10821 C = OMPBindClause::CreateEmpty(Context);
10822 break;
10823 case llvm::omp::OMPC_align:
10824 C = new (Context) OMPAlignClause();
10825 break;
10826 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
10827 C = new (Context) OMPXDynCGroupMemClause();
10828 break;
10829 case llvm::omp::OMPC_doacross: {
10830 unsigned NumVars = Record.readInt();
10831 unsigned NumLoops = Record.readInt();
10832 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
10833 break;
10834 }
10835 case llvm::omp::OMPC_ompx_attribute:
10836 C = new (Context) OMPXAttributeClause();
10837 break;
10838 case llvm::omp::OMPC_ompx_bare:
10839 C = new (Context) OMPXBareClause();
10840 break;
10841#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
10842 case llvm::omp::Enum: \
10843 break;
10844#include "llvm/Frontend/OpenMP/OMPKinds.def"
10845 default:
10846 break;
10847 }
10848 assert(C && "Unknown OMPClause type");
10849
10850 Visit(C);
10851 C->setLocStart(Record.readSourceLocation());
10852 C->setLocEnd(Record.readSourceLocation());
10853
10854 return C;
10855}
10856
10858 C->setPreInitStmt(Record.readSubStmt(),
10859 static_cast<OpenMPDirectiveKind>(Record.readInt()));
10860}
10861
10864 C->setPostUpdateExpr(Record.readSubExpr());
10865}
10866
10867void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
10869 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
10870 C->setNameModifierLoc(Record.readSourceLocation());
10871 C->setColonLoc(Record.readSourceLocation());
10872 C->setCondition(Record.readSubExpr());
10873 C->setLParenLoc(Record.readSourceLocation());
10874}
10875
10876void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
10878 C->setCondition(Record.readSubExpr());
10879 C->setLParenLoc(Record.readSourceLocation());
10880}
10881
10882void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
10884 C->setNumThreads(Record.readSubExpr());
10885 C->setLParenLoc(Record.readSourceLocation());
10886}
10887
10888void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
10889 C->setSafelen(Record.readSubExpr());
10890 C->setLParenLoc(Record.readSourceLocation());
10891}
10892
10893void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
10894 C->setSimdlen(Record.readSubExpr());
10895 C->setLParenLoc(Record.readSourceLocation());
10896}
10897
10898void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
10899 for (Expr *&E : C->getSizesRefs())
10900 E = Record.readSubExpr();
10901 C->setLParenLoc(Record.readSourceLocation());
10902}
10903
10904void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
10905
10906void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
10907 C->setFactor(Record.readSubExpr());
10908 C->setLParenLoc(Record.readSourceLocation());
10909}
10910
10911void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
10912 C->setAllocator(Record.readExpr());
10913 C->setLParenLoc(Record.readSourceLocation());
10914}
10915
10916void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
10917 C->setNumForLoops(Record.readSubExpr());
10918 C->setLParenLoc(Record.readSourceLocation());
10919}
10920
10921void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
10922 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
10923 C->setLParenLoc(Record.readSourceLocation());
10924 C->setDefaultKindKwLoc(Record.readSourceLocation());
10925}
10926
10927void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
10928 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
10929 C->setLParenLoc(Record.readSourceLocation());
10930 C->setProcBindKindKwLoc(Record.readSourceLocation());
10931}
10932
10933void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
10935 C->setScheduleKind(
10936 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
10937 C->setFirstScheduleModifier(
10938 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10939 C->setSecondScheduleModifier(
10940 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10941 C->setChunkSize(Record.readSubExpr());
10942 C->setLParenLoc(Record.readSourceLocation());
10943 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
10944 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
10945 C->setScheduleKindLoc(Record.readSourceLocation());
10946 C->setCommaLoc(Record.readSourceLocation());
10947}
10948
10949void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
10950 C->setNumForLoops(Record.readSubExpr());
10951 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10952 C->setLoopNumIterations(I, Record.readSubExpr());
10953 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10954 C->setLoopCounter(I, Record.readSubExpr());
10955 C->setLParenLoc(Record.readSourceLocation());
10956}
10957
10958void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
10959 C->setEventHandler(Record.readSubExpr());
10960 C->setLParenLoc(Record.readSourceLocation());
10961}
10962
10963void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
10964
10965void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
10966
10967void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
10968
10969void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
10970
10971void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
10972
10973void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
10974 if (C->isExtended()) {
10975 C->setLParenLoc(Record.readSourceLocation());
10976 C->setArgumentLoc(Record.readSourceLocation());
10977 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
10978 }
10979}
10980
10981void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
10982
10983void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
10984
10985// Read the parameter of fail clause. This will have been saved when
10986// OMPClauseWriter is called.
10987void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
10988 C->setLParenLoc(Record.readSourceLocation());
10989 SourceLocation FailParameterLoc = Record.readSourceLocation();
10990 C->setFailParameterLoc(FailParameterLoc);
10991 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
10992 C->setFailParameter(CKind);
10993}
10994
10995void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
10996 unsigned Count = C->getDirectiveKinds().size();
10997 C->setLParenLoc(Record.readSourceLocation());
10999 DKVec.reserve(Count);
11000 for (unsigned I = 0; I < Count; I++) {
11001 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11002 }
11003 C->setDirectiveKinds(DKVec);
11004}
11005
11006void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
11007 C->setExpr(Record.readExpr());
11008 C->setLParenLoc(Record.readSourceLocation());
11009}
11010
11011void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
11012 unsigned Count = C->getDirectiveKinds().size();
11013 C->setLParenLoc(Record.readSourceLocation());
11015 DKVec.reserve(Count);
11016 for (unsigned I = 0; I < Count; I++) {
11017 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11018 }
11019 C->setDirectiveKinds(DKVec);
11020}
11021
11022void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
11023
11024void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
11026
11027void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
11028
11029void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11030
11031void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
11032
11033void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
11034
11035void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
11036
11037void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
11038
11039void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
11040
11041void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11042
11043void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11044
11045void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11046
11047void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
11048 unsigned NumVars = C->varlist_size();
11050 Vars.reserve(NumVars);
11051 for (unsigned I = 0; I != NumVars; ++I)
11052 Vars.push_back(Record.readSubExpr());
11053 C->setVarRefs(Vars);
11054 C->setIsTarget(Record.readBool());
11055 C->setIsTargetSync(Record.readBool());
11056 C->setLParenLoc(Record.readSourceLocation());
11057 C->setVarLoc(Record.readSourceLocation());
11058}
11059
11060void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
11061 C->setInteropVar(Record.readSubExpr());
11062 C->setLParenLoc(Record.readSourceLocation());
11063 C->setVarLoc(Record.readSourceLocation());
11064}
11065
11066void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
11067 C->setInteropVar(Record.readSubExpr());
11068 C->setLParenLoc(Record.readSourceLocation());
11069 C->setVarLoc(Record.readSourceLocation());
11070}
11071
11072void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
11074 C->setCondition(Record.readSubExpr());
11075 C->setLParenLoc(Record.readSourceLocation());
11076}
11077
11078void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
11080 C->setCondition(Record.readSubExpr());
11081 C->setLParenLoc(Record.readSourceLocation());
11082}
11083
11084void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11085
11086void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
11088
11089void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
11090
11091void
11092OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
11093}
11094
11095void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
11097 C->setAtomicDefaultMemOrderKind(
11098 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
11099 C->setLParenLoc(Record.readSourceLocation());
11100 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
11101}
11102
11103void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
11104 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
11105 C->setLParenLoc(Record.readSourceLocation());
11106 C->setAtKindKwLoc(Record.readSourceLocation());
11107}
11108
11109void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
11110 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
11111 C->setLParenLoc(Record.readSourceLocation());
11112 C->setSeverityKindKwLoc(Record.readSourceLocation());
11113}
11114
11115void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
11116 C->setMessageString(Record.readSubExpr());
11117 C->setLParenLoc(Record.readSourceLocation());
11118}
11119
11120void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11121 C->setLParenLoc(Record.readSourceLocation());
11122 unsigned NumVars = C->varlist_size();
11124 Vars.reserve(NumVars);
11125 for (unsigned i = 0; i != NumVars; ++i)
11126 Vars.push_back(Record.readSubExpr());
11127 C->setVarRefs(Vars);
11128 Vars.clear();
11129 for (unsigned i = 0; i != NumVars; ++i)
11130 Vars.push_back(Record.readSubExpr());
11131 C->setPrivateCopies(Vars);
11132}
11133
11134void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
11136 C->setLParenLoc(Record.readSourceLocation());
11137 unsigned NumVars = C->varlist_size();
11139 Vars.reserve(NumVars);
11140 for (unsigned i = 0; i != NumVars; ++i)
11141 Vars.push_back(Record.readSubExpr());
11142 C->setVarRefs(Vars);
11143 Vars.clear();
11144 for (unsigned i = 0; i != NumVars; ++i)
11145 Vars.push_back(Record.readSubExpr());
11146 C->setPrivateCopies(Vars);
11147 Vars.clear();
11148 for (unsigned i = 0; i != NumVars; ++i)
11149 Vars.push_back(Record.readSubExpr());
11150 C->setInits(Vars);
11151}
11152
11153void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
11155 C->setLParenLoc(Record.readSourceLocation());
11156 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
11157 C->setKindLoc(Record.readSourceLocation());
11158 C->setColonLoc(Record.readSourceLocation());
11159 unsigned NumVars = C->varlist_size();
11161 Vars.reserve(NumVars);
11162 for (unsigned i = 0; i != NumVars; ++i)
11163 Vars.push_back(Record.readSubExpr());
11164 C->setVarRefs(Vars);
11165 Vars.clear();
11166 for (unsigned i = 0; i != NumVars; ++i)
11167 Vars.push_back(Record.readSubExpr());
11168 C->setPrivateCopies(Vars);
11169 Vars.clear();
11170 for (unsigned i = 0; i != NumVars; ++i)
11171 Vars.push_back(Record.readSubExpr());
11172 C->setSourceExprs(Vars);
11173 Vars.clear();
11174 for (unsigned i = 0; i != NumVars; ++i)
11175 Vars.push_back(Record.readSubExpr());
11176 C->setDestinationExprs(Vars);
11177 Vars.clear();
11178 for (unsigned i = 0; i != NumVars; ++i)
11179 Vars.push_back(Record.readSubExpr());
11180 C->setAssignmentOps(Vars);
11181}
11182
11183void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
11184 C->setLParenLoc(Record.readSourceLocation());
11185 unsigned NumVars = C->varlist_size();
11187 Vars.reserve(NumVars);
11188 for (unsigned i = 0; i != NumVars; ++i)
11189 Vars.push_back(Record.readSubExpr());
11190 C->setVarRefs(Vars);
11191}
11192
11193void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
11195 C->setLParenLoc(Record.readSourceLocation());
11196 C->setModifierLoc(Record.readSourceLocation());
11197 C->setColonLoc(Record.readSourceLocation());
11198 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11199 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11200 C->setQualifierLoc(NNSL);
11201 C->setNameInfo(DNI);
11202
11203 unsigned NumVars = C->varlist_size();
11205 Vars.reserve(NumVars);
11206 for (unsigned i = 0; i != NumVars; ++i)
11207 Vars.push_back(Record.readSubExpr());
11208 C->setVarRefs(Vars);
11209 Vars.clear();
11210 for (unsigned i = 0; i != NumVars; ++i)
11211 Vars.push_back(Record.readSubExpr());
11212 C->setPrivates(Vars);
11213 Vars.clear();
11214 for (unsigned i = 0; i != NumVars; ++i)
11215 Vars.push_back(Record.readSubExpr());
11216 C->setLHSExprs(Vars);
11217 Vars.clear();
11218 for (unsigned i = 0; i != NumVars; ++i)
11219 Vars.push_back(Record.readSubExpr());
11220 C->setRHSExprs(Vars);
11221 Vars.clear();
11222 for (unsigned i = 0; i != NumVars; ++i)
11223 Vars.push_back(Record.readSubExpr());
11224 C->setReductionOps(Vars);
11225 if (C->getModifier() == OMPC_REDUCTION_inscan) {
11226 Vars.clear();
11227 for (unsigned i = 0; i != NumVars; ++i)
11228 Vars.push_back(Record.readSubExpr());
11229 C->setInscanCopyOps(Vars);
11230 Vars.clear();
11231 for (unsigned i = 0; i != NumVars; ++i)
11232 Vars.push_back(Record.readSubExpr());
11233 C->setInscanCopyArrayTemps(Vars);
11234 Vars.clear();
11235 for (unsigned i = 0; i != NumVars; ++i)
11236 Vars.push_back(Record.readSubExpr());
11237 C->setInscanCopyArrayElems(Vars);
11238 }
11239}
11240
11241void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
11243 C->setLParenLoc(Record.readSourceLocation());
11244 C->setColonLoc(Record.readSourceLocation());
11245 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11246 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11247 C->setQualifierLoc(NNSL);
11248 C->setNameInfo(DNI);
11249
11250 unsigned NumVars = C->varlist_size();
11252 Vars.reserve(NumVars);
11253 for (unsigned I = 0; I != NumVars; ++I)
11254 Vars.push_back(Record.readSubExpr());
11255 C->setVarRefs(Vars);
11256 Vars.clear();
11257 for (unsigned I = 0; I != NumVars; ++I)
11258 Vars.push_back(Record.readSubExpr());
11259 C->setPrivates(Vars);
11260 Vars.clear();
11261 for (unsigned I = 0; I != NumVars; ++I)
11262 Vars.push_back(Record.readSubExpr());
11263 C->setLHSExprs(Vars);
11264 Vars.clear();
11265 for (unsigned I = 0; I != NumVars; ++I)
11266 Vars.push_back(Record.readSubExpr());
11267 C->setRHSExprs(Vars);
11268 Vars.clear();
11269 for (unsigned I = 0; I != NumVars; ++I)
11270 Vars.push_back(Record.readSubExpr());
11271 C->setReductionOps(Vars);
11272}
11273
11274void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
11276 C->setLParenLoc(Record.readSourceLocation());
11277 C->setColonLoc(Record.readSourceLocation());
11278 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11279 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11280 C->setQualifierLoc(NNSL);
11281 C->setNameInfo(DNI);
11282
11283 unsigned NumVars = C->varlist_size();
11285 Vars.reserve(NumVars);
11286 for (unsigned I = 0; I != NumVars; ++I)
11287 Vars.push_back(Record.readSubExpr());
11288 C->setVarRefs(Vars);
11289 Vars.clear();
11290 for (unsigned I = 0; I != NumVars; ++I)
11291 Vars.push_back(Record.readSubExpr());
11292 C->setPrivates(Vars);
11293 Vars.clear();
11294 for (unsigned I = 0; I != NumVars; ++I)
11295 Vars.push_back(Record.readSubExpr());
11296 C->setLHSExprs(Vars);
11297 Vars.clear();
11298 for (unsigned I = 0; I != NumVars; ++I)
11299 Vars.push_back(Record.readSubExpr());
11300 C->setRHSExprs(Vars);
11301 Vars.clear();
11302 for (unsigned I = 0; I != NumVars; ++I)
11303 Vars.push_back(Record.readSubExpr());
11304 C->setReductionOps(Vars);
11305 Vars.clear();
11306 for (unsigned I = 0; I != NumVars; ++I)
11307 Vars.push_back(Record.readSubExpr());
11308 C->setTaskgroupDescriptors(Vars);
11309}
11310
11311void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
11313 C->setLParenLoc(Record.readSourceLocation());
11314 C->setColonLoc(Record.readSourceLocation());
11315 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
11316 C->setModifierLoc(Record.readSourceLocation());
11317 unsigned NumVars = C->varlist_size();
11319 Vars.reserve(NumVars);
11320 for (unsigned i = 0; i != NumVars; ++i)
11321 Vars.push_back(Record.readSubExpr());
11322 C->setVarRefs(Vars);
11323 Vars.clear();
11324 for (unsigned i = 0; i != NumVars; ++i)
11325 Vars.push_back(Record.readSubExpr());
11326 C->setPrivates(Vars);
11327 Vars.clear();
11328 for (unsigned i = 0; i != NumVars; ++i)
11329 Vars.push_back(Record.readSubExpr());
11330 C->setInits(Vars);
11331 Vars.clear();
11332 for (unsigned i = 0; i != NumVars; ++i)
11333 Vars.push_back(Record.readSubExpr());
11334 C->setUpdates(Vars);
11335 Vars.clear();
11336 for (unsigned i = 0; i != NumVars; ++i)
11337 Vars.push_back(Record.readSubExpr());
11338 C->setFinals(Vars);
11339 C->setStep(Record.readSubExpr());
11340 C->setCalcStep(Record.readSubExpr());
11341 Vars.clear();
11342 for (unsigned I = 0; I != NumVars + 1; ++I)
11343 Vars.push_back(Record.readSubExpr());
11344 C->setUsedExprs(Vars);
11345}
11346
11347void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
11348 C->setLParenLoc(Record.readSourceLocation());
11349 C->setColonLoc(Record.readSourceLocation());
11350 unsigned NumVars = C->varlist_size();
11352 Vars.reserve(NumVars);
11353 for (unsigned i = 0; i != NumVars; ++i)
11354 Vars.push_back(Record.readSubExpr());
11355 C->setVarRefs(Vars);
11356 C->setAlignment(Record.readSubExpr());
11357}
11358
11359void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
11360 C->setLParenLoc(Record.readSourceLocation());
11361 unsigned NumVars = C->varlist_size();
11363 Exprs.reserve(NumVars);
11364 for (unsigned i = 0; i != NumVars; ++i)
11365 Exprs.push_back(Record.readSubExpr());
11366 C->setVarRefs(Exprs);
11367 Exprs.clear();
11368 for (unsigned i = 0; i != NumVars; ++i)
11369 Exprs.push_back(Record.readSubExpr());
11370 C->setSourceExprs(Exprs);
11371 Exprs.clear();
11372 for (unsigned i = 0; i != NumVars; ++i)
11373 Exprs.push_back(Record.readSubExpr());
11374 C->setDestinationExprs(Exprs);
11375 Exprs.clear();
11376 for (unsigned i = 0; i != NumVars; ++i)
11377 Exprs.push_back(Record.readSubExpr());
11378 C->setAssignmentOps(Exprs);
11379}
11380
11381void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
11382 C->setLParenLoc(Record.readSourceLocation());
11383 unsigned NumVars = C->varlist_size();
11385 Exprs.reserve(NumVars);
11386 for (unsigned i = 0; i != NumVars; ++i)
11387 Exprs.push_back(Record.readSubExpr());
11388 C->setVarRefs(Exprs);
11389 Exprs.clear();
11390 for (unsigned i = 0; i != NumVars; ++i)
11391 Exprs.push_back(Record.readSubExpr());
11392 C->setSourceExprs(Exprs);
11393 Exprs.clear();
11394 for (unsigned i = 0; i != NumVars; ++i)
11395 Exprs.push_back(Record.readSubExpr());
11396 C->setDestinationExprs(Exprs);
11397 Exprs.clear();
11398 for (unsigned i = 0; i != NumVars; ++i)
11399 Exprs.push_back(Record.readSubExpr());
11400 C->setAssignmentOps(Exprs);
11401}
11402
11403void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
11404 C->setLParenLoc(Record.readSourceLocation());
11405 unsigned NumVars = C->varlist_size();
11407 Vars.reserve(NumVars);
11408 for (unsigned i = 0; i != NumVars; ++i)
11409 Vars.push_back(Record.readSubExpr());
11410 C->setVarRefs(Vars);
11411}
11412
11413void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
11414 C->setDepobj(Record.readSubExpr());
11415 C->setLParenLoc(Record.readSourceLocation());
11416}
11417
11418void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
11419 C->setLParenLoc(Record.readSourceLocation());
11420 C->setModifier(Record.readSubExpr());
11421 C->setDependencyKind(
11422 static_cast<OpenMPDependClauseKind>(Record.readInt()));
11423 C->setDependencyLoc(Record.readSourceLocation());
11424 C->setColonLoc(Record.readSourceLocation());
11425 C->setOmpAllMemoryLoc(Record.readSourceLocation());
11426 unsigned NumVars = C->varlist_size();
11428 Vars.reserve(NumVars);
11429 for (unsigned I = 0; I != NumVars; ++I)
11430 Vars.push_back(Record.readSubExpr());
11431 C->setVarRefs(Vars);
11432 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11433 C->setLoopData(I, Record.readSubExpr());
11434}
11435
11436void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
11438 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
11439 C->setDevice(Record.readSubExpr());
11440 C->setModifierLoc(Record.readSourceLocation());
11441 C->setLParenLoc(Record.readSourceLocation());
11442}
11443
11444void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
11445 C->setLParenLoc(Record.readSourceLocation());
11446 bool HasIteratorModifier = false;
11447 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
11448 C->setMapTypeModifier(
11449 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
11450 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
11451 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
11452 HasIteratorModifier = true;
11453 }
11454 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11455 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11456 C->setMapType(
11457 static_cast<OpenMPMapClauseKind>(Record.readInt()));
11458 C->setMapLoc(Record.readSourceLocation());
11459 C->setColonLoc(Record.readSourceLocation());
11460 auto NumVars = C->varlist_size();
11461 auto UniqueDecls = C->getUniqueDeclarationsNum();
11462 auto TotalLists = C->getTotalComponentListNum();
11463 auto TotalComponents = C->getTotalComponentsNum();
11464
11466 Vars.reserve(NumVars);
11467 for (unsigned i = 0; i != NumVars; ++i)
11468 Vars.push_back(Record.readExpr());
11469 C->setVarRefs(Vars);
11470
11471 SmallVector<Expr *, 16> UDMappers;
11472 UDMappers.reserve(NumVars);
11473 for (unsigned I = 0; I < NumVars; ++I)
11474 UDMappers.push_back(Record.readExpr());
11475 C->setUDMapperRefs(UDMappers);
11476
11477 if (HasIteratorModifier)
11478 C->setIteratorModifier(Record.readExpr());
11479
11481 Decls.reserve(UniqueDecls);
11482 for (unsigned i = 0; i < UniqueDecls; ++i)
11483 Decls.push_back(Record.readDeclAs<ValueDecl>());
11484 C->setUniqueDecls(Decls);
11485
11486 SmallVector<unsigned, 16> ListsPerDecl;
11487 ListsPerDecl.reserve(UniqueDecls);
11488 for (unsigned i = 0; i < UniqueDecls; ++i)
11489 ListsPerDecl.push_back(Record.readInt());
11490 C->setDeclNumLists(ListsPerDecl);
11491
11492 SmallVector<unsigned, 32> ListSizes;
11493 ListSizes.reserve(TotalLists);
11494 for (unsigned i = 0; i < TotalLists; ++i)
11495 ListSizes.push_back(Record.readInt());
11496 C->setComponentListSizes(ListSizes);
11497
11499 Components.reserve(TotalComponents);
11500 for (unsigned i = 0; i < TotalComponents; ++i) {
11501 Expr *AssociatedExprPr = Record.readExpr();
11502 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11503 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11504 /*IsNonContiguous=*/false);
11505 }
11506 C->setComponents(Components, ListSizes);
11507}
11508
11509void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
11510 C->setLParenLoc(Record.readSourceLocation());
11511 C->setColonLoc(Record.readSourceLocation());
11512 C->setAllocator(Record.readSubExpr());
11513 unsigned NumVars = C->varlist_size();
11515 Vars.reserve(NumVars);
11516 for (unsigned i = 0; i != NumVars; ++i)
11517 Vars.push_back(Record.readSubExpr());
11518 C->setVarRefs(Vars);
11519}
11520
11521void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
11523 C->setLParenLoc(Record.readSourceLocation());
11524 unsigned NumVars = C->varlist_size();
11526 Vars.reserve(NumVars);
11527 for (unsigned I = 0; I != NumVars; ++I)
11528 Vars.push_back(Record.readSubExpr());
11529 C->setVarRefs(Vars);
11530}
11531
11532void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
11534 C->setLParenLoc(Record.readSourceLocation());
11535 unsigned NumVars = C->varlist_size();
11537 Vars.reserve(NumVars);
11538 for (unsigned I = 0; I != NumVars; ++I)
11539 Vars.push_back(Record.readSubExpr());
11540 C->setVarRefs(Vars);
11541}
11542
11543void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
11545 C->setPriority(Record.readSubExpr());
11546 C->setLParenLoc(Record.readSourceLocation());
11547}
11548
11549void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
11551 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
11552 C->setGrainsize(Record.readSubExpr());
11553 C->setModifierLoc(Record.readSourceLocation());
11554 C->setLParenLoc(Record.readSourceLocation());
11555}
11556
11557void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
11559 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
11560 C->setNumTasks(Record.readSubExpr());
11561 C->setModifierLoc(Record.readSourceLocation());
11562 C->setLParenLoc(Record.readSourceLocation());
11563}
11564
11565void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
11566 C->setHint(Record.readSubExpr());
11567 C->setLParenLoc(Record.readSourceLocation());
11568}
11569
11570void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
11572 C->setDistScheduleKind(
11573 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
11574 C->setChunkSize(Record.readSubExpr());
11575 C->setLParenLoc(Record.readSourceLocation());
11576 C->setDistScheduleKindLoc(Record.readSourceLocation());
11577 C->setCommaLoc(Record.readSourceLocation());
11578}
11579
11580void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
11581 C->setDefaultmapKind(
11582 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
11583 C->setDefaultmapModifier(
11584 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
11585 C->setLParenLoc(Record.readSourceLocation());
11586 C->setDefaultmapModifierLoc(Record.readSourceLocation());
11587 C->setDefaultmapKindLoc(Record.readSourceLocation());
11588}
11589
11590void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
11591 C->setLParenLoc(Record.readSourceLocation());
11592 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11593 C->setMotionModifier(
11594 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11595 C->setMotionModifierLoc(I, Record.readSourceLocation());
11596 }
11597 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11598 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11599 C->setColonLoc(Record.readSourceLocation());
11600 auto NumVars = C->varlist_size();
11601 auto UniqueDecls = C->getUniqueDeclarationsNum();
11602 auto TotalLists = C->getTotalComponentListNum();
11603 auto TotalComponents = C->getTotalComponentsNum();
11604
11606 Vars.reserve(NumVars);
11607 for (unsigned i = 0; i != NumVars; ++i)
11608 Vars.push_back(Record.readSubExpr());
11609 C->setVarRefs(Vars);
11610
11611 SmallVector<Expr *, 16> UDMappers;
11612 UDMappers.reserve(NumVars);
11613 for (unsigned I = 0; I < NumVars; ++I)
11614 UDMappers.push_back(Record.readSubExpr());
11615 C->setUDMapperRefs(UDMappers);
11616
11618 Decls.reserve(UniqueDecls);
11619 for (unsigned i = 0; i < UniqueDecls; ++i)
11620 Decls.push_back(Record.readDeclAs<ValueDecl>());
11621 C->setUniqueDecls(Decls);
11622
11623 SmallVector<unsigned, 16> ListsPerDecl;
11624 ListsPerDecl.reserve(UniqueDecls);
11625 for (unsigned i = 0; i < UniqueDecls; ++i)
11626 ListsPerDecl.push_back(Record.readInt());
11627 C->setDeclNumLists(ListsPerDecl);
11628
11629 SmallVector<unsigned, 32> ListSizes;
11630 ListSizes.reserve(TotalLists);
11631 for (unsigned i = 0; i < TotalLists; ++i)
11632 ListSizes.push_back(Record.readInt());
11633 C->setComponentListSizes(ListSizes);
11634
11636 Components.reserve(TotalComponents);
11637 for (unsigned i = 0; i < TotalComponents; ++i) {
11638 Expr *AssociatedExprPr = Record.readSubExpr();
11639 bool IsNonContiguous = Record.readBool();
11640 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11641 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11642 }
11643 C->setComponents(Components, ListSizes);
11644}
11645
11646void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
11647 C->setLParenLoc(Record.readSourceLocation());
11648 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11649 C->setMotionModifier(
11650 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11651 C->setMotionModifierLoc(I, Record.readSourceLocation());
11652 }
11653 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11654 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11655 C->setColonLoc(Record.readSourceLocation());
11656 auto NumVars = C->varlist_size();
11657 auto UniqueDecls = C->getUniqueDeclarationsNum();
11658 auto TotalLists = C->getTotalComponentListNum();
11659 auto TotalComponents = C->getTotalComponentsNum();
11660
11662 Vars.reserve(NumVars);
11663 for (unsigned i = 0; i != NumVars; ++i)
11664 Vars.push_back(Record.readSubExpr());
11665 C->setVarRefs(Vars);
11666
11667 SmallVector<Expr *, 16> UDMappers;
11668 UDMappers.reserve(NumVars);
11669 for (unsigned I = 0; I < NumVars; ++I)
11670 UDMappers.push_back(Record.readSubExpr());
11671 C->setUDMapperRefs(UDMappers);
11672
11674 Decls.reserve(UniqueDecls);
11675 for (unsigned i = 0; i < UniqueDecls; ++i)
11676 Decls.push_back(Record.readDeclAs<ValueDecl>());
11677 C->setUniqueDecls(Decls);
11678
11679 SmallVector<unsigned, 16> ListsPerDecl;
11680 ListsPerDecl.reserve(UniqueDecls);
11681 for (unsigned i = 0; i < UniqueDecls; ++i)
11682 ListsPerDecl.push_back(Record.readInt());
11683 C->setDeclNumLists(ListsPerDecl);
11684
11685 SmallVector<unsigned, 32> ListSizes;
11686 ListSizes.reserve(TotalLists);
11687 for (unsigned i = 0; i < TotalLists; ++i)
11688 ListSizes.push_back(Record.readInt());
11689 C->setComponentListSizes(ListSizes);
11690
11692 Components.reserve(TotalComponents);
11693 for (unsigned i = 0; i < TotalComponents; ++i) {
11694 Expr *AssociatedExprPr = Record.readSubExpr();
11695 bool IsNonContiguous = Record.readBool();
11696 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11697 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11698 }
11699 C->setComponents(Components, ListSizes);
11700}
11701
11702void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
11703 C->setLParenLoc(Record.readSourceLocation());
11704 auto NumVars = C->varlist_size();
11705 auto UniqueDecls = C->getUniqueDeclarationsNum();
11706 auto TotalLists = C->getTotalComponentListNum();
11707 auto TotalComponents = C->getTotalComponentsNum();
11708
11710 Vars.reserve(NumVars);
11711 for (unsigned i = 0; i != NumVars; ++i)
11712 Vars.push_back(Record.readSubExpr());
11713 C->setVarRefs(Vars);
11714 Vars.clear();
11715 for (unsigned i = 0; i != NumVars; ++i)
11716 Vars.push_back(Record.readSubExpr());
11717 C->setPrivateCopies(Vars);
11718 Vars.clear();
11719 for (unsigned i = 0; i != NumVars; ++i)
11720 Vars.push_back(Record.readSubExpr());
11721 C->setInits(Vars);
11722
11724 Decls.reserve(UniqueDecls);
11725 for (unsigned i = 0; i < UniqueDecls; ++i)
11726 Decls.push_back(Record.readDeclAs<ValueDecl>());
11727 C->setUniqueDecls(Decls);
11728
11729 SmallVector<unsigned, 16> ListsPerDecl;
11730 ListsPerDecl.reserve(UniqueDecls);
11731 for (unsigned i = 0; i < UniqueDecls; ++i)
11732 ListsPerDecl.push_back(Record.readInt());
11733 C->setDeclNumLists(ListsPerDecl);
11734
11735 SmallVector<unsigned, 32> ListSizes;
11736 ListSizes.reserve(TotalLists);
11737 for (unsigned i = 0; i < TotalLists; ++i)
11738 ListSizes.push_back(Record.readInt());
11739 C->setComponentListSizes(ListSizes);
11740
11742 Components.reserve(TotalComponents);
11743 for (unsigned i = 0; i < TotalComponents; ++i) {
11744 auto *AssociatedExprPr = Record.readSubExpr();
11745 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11746 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11747 /*IsNonContiguous=*/false);
11748 }
11749 C->setComponents(Components, ListSizes);
11750}
11751
11752void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
11753 C->setLParenLoc(Record.readSourceLocation());
11754 auto NumVars = C->varlist_size();
11755 auto UniqueDecls = C->getUniqueDeclarationsNum();
11756 auto TotalLists = C->getTotalComponentListNum();
11757 auto TotalComponents = C->getTotalComponentsNum();
11758
11760 Vars.reserve(NumVars);
11761 for (unsigned i = 0; i != NumVars; ++i)
11762 Vars.push_back(Record.readSubExpr());
11763 C->setVarRefs(Vars);
11764
11766 Decls.reserve(UniqueDecls);
11767 for (unsigned i = 0; i < UniqueDecls; ++i)
11768 Decls.push_back(Record.readDeclAs<ValueDecl>());
11769 C->setUniqueDecls(Decls);
11770
11771 SmallVector<unsigned, 16> ListsPerDecl;
11772 ListsPerDecl.reserve(UniqueDecls);
11773 for (unsigned i = 0; i < UniqueDecls; ++i)
11774 ListsPerDecl.push_back(Record.readInt());
11775 C->setDeclNumLists(ListsPerDecl);
11776
11777 SmallVector<unsigned, 32> ListSizes;
11778 ListSizes.reserve(TotalLists);
11779 for (unsigned i = 0; i < TotalLists; ++i)
11780 ListSizes.push_back(Record.readInt());
11781 C->setComponentListSizes(ListSizes);
11782
11784 Components.reserve(TotalComponents);
11785 for (unsigned i = 0; i < TotalComponents; ++i) {
11786 Expr *AssociatedExpr = Record.readSubExpr();
11787 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11788 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11789 /*IsNonContiguous*/ false);
11790 }
11791 C->setComponents(Components, ListSizes);
11792}
11793
11794void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
11795 C->setLParenLoc(Record.readSourceLocation());
11796 auto NumVars = C->varlist_size();
11797 auto UniqueDecls = C->getUniqueDeclarationsNum();
11798 auto TotalLists = C->getTotalComponentListNum();
11799 auto TotalComponents = C->getTotalComponentsNum();
11800
11802 Vars.reserve(NumVars);
11803 for (unsigned i = 0; i != NumVars; ++i)
11804 Vars.push_back(Record.readSubExpr());
11805 C->setVarRefs(Vars);
11806 Vars.clear();
11807
11809 Decls.reserve(UniqueDecls);
11810 for (unsigned i = 0; i < UniqueDecls; ++i)
11811 Decls.push_back(Record.readDeclAs<ValueDecl>());
11812 C->setUniqueDecls(Decls);
11813
11814 SmallVector<unsigned, 16> ListsPerDecl;
11815 ListsPerDecl.reserve(UniqueDecls);
11816 for (unsigned i = 0; i < UniqueDecls; ++i)
11817 ListsPerDecl.push_back(Record.readInt());
11818 C->setDeclNumLists(ListsPerDecl);
11819
11820 SmallVector<unsigned, 32> ListSizes;
11821 ListSizes.reserve(TotalLists);
11822 for (unsigned i = 0; i < TotalLists; ++i)
11823 ListSizes.push_back(Record.readInt());
11824 C->setComponentListSizes(ListSizes);
11825
11827 Components.reserve(TotalComponents);
11828 for (unsigned i = 0; i < TotalComponents; ++i) {
11829 Expr *AssociatedExpr = Record.readSubExpr();
11830 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11831 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11832 /*IsNonContiguous=*/false);
11833 }
11834 C->setComponents(Components, ListSizes);
11835}
11836
11837void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
11838 C->setLParenLoc(Record.readSourceLocation());
11839 auto NumVars = C->varlist_size();
11840 auto UniqueDecls = C->getUniqueDeclarationsNum();
11841 auto TotalLists = C->getTotalComponentListNum();
11842 auto TotalComponents = C->getTotalComponentsNum();
11843
11845 Vars.reserve(NumVars);
11846 for (unsigned I = 0; I != NumVars; ++I)
11847 Vars.push_back(Record.readSubExpr());
11848 C->setVarRefs(Vars);
11849 Vars.clear();
11850
11852 Decls.reserve(UniqueDecls);
11853 for (unsigned I = 0; I < UniqueDecls; ++I)
11854 Decls.push_back(Record.readDeclAs<ValueDecl>());
11855 C->setUniqueDecls(Decls);
11856
11857 SmallVector<unsigned, 16> ListsPerDecl;
11858 ListsPerDecl.reserve(UniqueDecls);
11859 for (unsigned I = 0; I < UniqueDecls; ++I)
11860 ListsPerDecl.push_back(Record.readInt());
11861 C->setDeclNumLists(ListsPerDecl);
11862
11863 SmallVector<unsigned, 32> ListSizes;
11864 ListSizes.reserve(TotalLists);
11865 for (unsigned i = 0; i < TotalLists; ++i)
11866 ListSizes.push_back(Record.readInt());
11867 C->setComponentListSizes(ListSizes);
11868
11870 Components.reserve(TotalComponents);
11871 for (unsigned I = 0; I < TotalComponents; ++I) {
11872 Expr *AssociatedExpr = Record.readSubExpr();
11873 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11874 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11875 /*IsNonContiguous=*/false);
11876 }
11877 C->setComponents(Components, ListSizes);
11878}
11879
11880void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
11881 C->setLParenLoc(Record.readSourceLocation());
11882 unsigned NumVars = C->varlist_size();
11884 Vars.reserve(NumVars);
11885 for (unsigned i = 0; i != NumVars; ++i)
11886 Vars.push_back(Record.readSubExpr());
11887 C->setVarRefs(Vars);
11888 Vars.clear();
11889 Vars.reserve(NumVars);
11890 for (unsigned i = 0; i != NumVars; ++i)
11891 Vars.push_back(Record.readSubExpr());
11892 C->setPrivateRefs(Vars);
11893}
11894
11895void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
11896 C->setLParenLoc(Record.readSourceLocation());
11897 unsigned NumVars = C->varlist_size();
11899 Vars.reserve(NumVars);
11900 for (unsigned i = 0; i != NumVars; ++i)
11901 Vars.push_back(Record.readSubExpr());
11902 C->setVarRefs(Vars);
11903}
11904
11905void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
11906 C->setLParenLoc(Record.readSourceLocation());
11907 unsigned NumVars = C->varlist_size();
11909 Vars.reserve(NumVars);
11910 for (unsigned i = 0; i != NumVars; ++i)
11911 Vars.push_back(Record.readSubExpr());
11912 C->setVarRefs(Vars);
11913}
11914
11915void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
11916 C->setLParenLoc(Record.readSourceLocation());
11917 unsigned NumOfAllocators = C->getNumberOfAllocators();
11919 Data.reserve(NumOfAllocators);
11920 for (unsigned I = 0; I != NumOfAllocators; ++I) {
11921 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
11922 D.Allocator = Record.readSubExpr();
11923 D.AllocatorTraits = Record.readSubExpr();
11924 D.LParenLoc = Record.readSourceLocation();
11925 D.RParenLoc = Record.readSourceLocation();
11926 }
11927 C->setAllocatorsData(Data);
11928}
11929
11930void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
11931 C->setLParenLoc(Record.readSourceLocation());
11932 C->setModifier(Record.readSubExpr());
11933 C->setColonLoc(Record.readSourceLocation());
11934 unsigned NumOfLocators = C->varlist_size();
11935 SmallVector<Expr *, 4> Locators;
11936 Locators.reserve(NumOfLocators);
11937 for (unsigned I = 0; I != NumOfLocators; ++I)
11938 Locators.push_back(Record.readSubExpr());
11939 C->setVarRefs(Locators);
11940}
11941
11942void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
11943 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
11944 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
11945 C->setLParenLoc(Record.readSourceLocation());
11946 C->setKindKwLoc(Record.readSourceLocation());
11947 C->setModifierKwLoc(Record.readSourceLocation());
11948}
11949
11950void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
11952 C->setThreadID(Record.readSubExpr());
11953 C->setLParenLoc(Record.readSourceLocation());
11954}
11955
11956void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
11957 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
11958 C->setLParenLoc(Record.readSourceLocation());
11959 C->setBindKindLoc(Record.readSourceLocation());
11960}
11961
11962void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
11963 C->setAlignment(Record.readExpr());
11964 C->setLParenLoc(Record.readSourceLocation());
11965}
11966
11967void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
11969 C->setSize(Record.readSubExpr());
11970 C->setLParenLoc(Record.readSourceLocation());
11971}
11972
11973void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
11974 C->setLParenLoc(Record.readSourceLocation());
11975 C->setDependenceType(
11976 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
11977 C->setDependenceLoc(Record.readSourceLocation());
11978 C->setColonLoc(Record.readSourceLocation());
11979 unsigned NumVars = C->varlist_size();
11981 Vars.reserve(NumVars);
11982 for (unsigned I = 0; I != NumVars; ++I)
11983 Vars.push_back(Record.readSubExpr());
11984 C->setVarRefs(Vars);
11985 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11986 C->setLoopData(I, Record.readSubExpr());
11987}
11988
11989void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
11990 AttrVec Attrs;
11991 Record.readAttributes(Attrs);
11992 C->setAttrs(Attrs);
11993 C->setLocStart(Record.readSourceLocation());
11994 C->setLParenLoc(Record.readSourceLocation());
11995 C->setLocEnd(Record.readSourceLocation());
11996}
11997
11998void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
11999
12002 TI.Sets.resize(readUInt32());
12003 for (auto &Set : TI.Sets) {
12004 Set.Kind = readEnum<llvm::omp::TraitSet>();
12005 Set.Selectors.resize(readUInt32());
12006 for (auto &Selector : Set.Selectors) {
12007 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
12008 Selector.ScoreOrCondition = nullptr;
12009 if (readBool())
12010 Selector.ScoreOrCondition = readExprRef();
12011 Selector.Properties.resize(readUInt32());
12012 for (auto &Property : Selector.Properties)
12013 Property.Kind = readEnum<llvm::omp::TraitProperty>();
12014 }
12015 }
12016 return &TI;
12017}
12018
12020 if (!Data)
12021 return;
12022 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
12023 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
12024 skipInts(3);
12025 }
12026 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
12027 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
12028 Clauses[I] = readOMPClause();
12029 Data->setClauses(Clauses);
12030 if (Data->hasAssociatedStmt())
12031 Data->setAssociatedStmt(readStmt());
12032 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
12033 Data->getChildren()[I] = readStmt();
12034}
12035
12037 unsigned NumVars = readInt();
12039 for (unsigned I = 0; I < NumVars; ++I)
12040 VarList.push_back(readSubExpr());
12041 return VarList;
12042}
12043
12045 unsigned NumExprs = readInt();
12047 for (unsigned I = 0; I < NumExprs; ++I)
12048 ExprList.push_back(readSubExpr());
12049 return ExprList;
12050}
12051
12053 OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>();
12056
12057 switch (ClauseKind) {
12059 SourceLocation LParenLoc = readSourceLocation();
12060 OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>();
12061 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
12062 EndLoc);
12063 }
12064 case OpenACCClauseKind::If: {
12065 SourceLocation LParenLoc = readSourceLocation();
12066 Expr *CondExpr = readSubExpr();
12067 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
12068 EndLoc);
12069 }
12071 SourceLocation LParenLoc = readSourceLocation();
12072 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
12073 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
12074 CondExpr, EndLoc);
12075 }
12077 SourceLocation LParenLoc = readSourceLocation();
12078 unsigned NumClauses = readInt();
12080 for (unsigned I = 0; I < NumClauses; ++I)
12081 IntExprs.push_back(readSubExpr());
12082 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
12083 IntExprs, EndLoc);
12084 }
12086 SourceLocation LParenLoc = readSourceLocation();
12087 Expr *IntExpr = readSubExpr();
12088 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
12089 IntExpr, EndLoc);
12090 }
12092 SourceLocation LParenLoc = readSourceLocation();
12093 Expr *IntExpr = readSubExpr();
12094 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
12095 IntExpr, EndLoc);
12096 }
12098 SourceLocation LParenLoc = readSourceLocation();
12100 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
12101 VarList, EndLoc);
12102 }
12104 SourceLocation LParenLoc = readSourceLocation();
12106 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
12107 VarList, EndLoc);
12108 }
12110 SourceLocation LParenLoc = readSourceLocation();
12112 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
12113 VarList, EndLoc);
12114 }
12116 SourceLocation LParenLoc = readSourceLocation();
12118 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
12119 VarList, EndLoc);
12120 }
12122 SourceLocation LParenLoc = readSourceLocation();
12124 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
12125 VarList, EndLoc);
12126 }
12128 SourceLocation LParenLoc = readSourceLocation();
12130 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
12131 VarList, EndLoc);
12132 }
12136 SourceLocation LParenLoc = readSourceLocation();
12138 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
12139 LParenLoc, VarList, EndLoc);
12140 }
12144 SourceLocation LParenLoc = readSourceLocation();
12145 bool IsReadOnly = readBool();
12147 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
12148 LParenLoc, IsReadOnly, VarList, EndLoc);
12149 }
12153 SourceLocation LParenLoc = readSourceLocation();
12154 bool IsZero = readBool();
12156 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
12157 LParenLoc, IsZero, VarList, EndLoc);
12158 }
12162 SourceLocation LParenLoc = readSourceLocation();
12163 bool IsZero = readBool();
12165 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
12166 LParenLoc, IsZero, VarList, EndLoc);
12167 }
12169 SourceLocation LParenLoc = readSourceLocation();
12170 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
12171 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
12172 AsyncExpr, EndLoc);
12173 }
12175 SourceLocation LParenLoc = readSourceLocation();
12176 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
12177 SourceLocation QueuesLoc = readSourceLocation();
12179 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
12180 DevNumExpr, QueuesLoc, QueueIdExprs,
12181 EndLoc);
12182 }
12185 SourceLocation LParenLoc = readSourceLocation();
12187 unsigned NumArchs = readInt();
12188
12189 for (unsigned I = 0; I < NumArchs; ++I) {
12190 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
12192 Archs.emplace_back(Ident, Loc);
12193 }
12194
12195 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
12196 LParenLoc, Archs, EndLoc);
12197 }
12199 SourceLocation LParenLoc = readSourceLocation();
12200 OpenACCReductionOperator Op = readEnum<OpenACCReductionOperator>();
12202 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
12203 VarList, EndLoc);
12204 }
12206 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
12208 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
12210 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
12211
12231 llvm_unreachable("Clause serialization not yet implemented");
12232 }
12233 llvm_unreachable("Invalid Clause Kind");
12234}
12235
12238 for (unsigned I = 0; I < Clauses.size(); ++I)
12239 Clauses[I] = readOpenACCClause();
12240}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
ASTImporterLookupTable & LT
StringRef P
static unsigned moduleKindForDiagnostic(ModuleKind Kind)
Definition: ASTReader.cpp:4726
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer)
Under non-PCH compilation the consumer receives the objc methods before receiving the implementation,...
Definition: ASTReader.cpp:8205
static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream)
Whether Stream doesn't start with the AST/PCH file magic number 'CPCH'.
Definition: ASTReader.cpp:4708
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
Definition: ASTReader.cpp:517
static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS, StringRef SpecificModuleCachePath, StringRef ExistingModuleCachePath, StringRef ModuleFilename, DiagnosticsEngine *Diags, const LangOptions &LangOpts, const PreprocessorOptions &PPOpts)
Check that the specified and the existing module cache paths are equivalent.
Definition: ASTReader.cpp:863
static void updateModuleTimestamp(ModuleFile &MF)
Definition: ASTReader.cpp:4407
static unsigned getModuleFileIndexForTypeID(serialization::TypeID ID)
Definition: ASTReader.cpp:7185
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:631
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II, bool IsModule)
Definition: ASTReader.cpp:1080
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
Definition: ASTReader.cpp:4271
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps)
Definition: ASTReader.cpp:2774
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
Definition: ASTReader.cpp:1054
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:5048
static Module * getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP)
Return the top import module if it is implicit, nullptr otherwise.
Definition: ASTReader.cpp:572
static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename, 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:682
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
Definition: ASTReader.cpp:8723
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
Definition: ASTReader.cpp:524
static bool isPredefinedType(serialization::TypeID ID)
Definition: ASTReader.cpp:7189
static bool readBit(unsigned &Bits)
Definition: ASTReader.cpp:1066
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool Complain)
Definition: ASTReader.cpp:483
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
Definition: ASTReader.cpp:6721
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
Definition: ASTReader.cpp:915
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
Definition: ASTReader.cpp:8326
OptionValidation
Definition: ASTReader.cpp:666
@ OptionValidateStrictMatches
Definition: ASTReader.cpp:669
@ OptionValidateNone
Definition: ASTReader.cpp:667
@ OptionValidateContradictions
Definition: ASTReader.cpp:668
static bool checkTargetOptions(const TargetOptions &TargetOpts, const TargetOptions &ExistingTargetOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of target options against an existing set of target options.
Definition: ASTReader.cpp:393
static bool checkLanguageOptions(const LangOptions &LangOpts, const LangOptions &ExistingLangOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of language options against an existing set of language options.
Definition: ASTReader.cpp:283
#define CHECK_TARGET_OPT(Field, Name)
static ASTFileSignature readASTFileSignature(StringRef PCH)
Reads and return the signature record from PCH's control block, or else returns 0.
Definition: ASTReader.cpp:5273
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:4423
static unsigned getIndexForTypeID(serialization::TypeID ID)
Definition: ASTReader.cpp:7181
static uint64_t readULEB(const unsigned char *&P)
Definition: ASTReader.cpp:902
Defines the clang::ASTSourceDescriptor class, which abstracts clang modules and precompiled header fi...
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:127
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:83
Defines the Diagnostic-related interfaces.
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1653::IndirectLocalPathEntry::EntryKind Kind
Expr * E
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 Diagnostic IDs-related interfaces.
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:3001
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:46
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.
uint32_t Id
Definition: SemaARM.cpp:1144
This file declares semantic analysis for CUDA constructs.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
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__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ __2f16 b
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:34
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:187
CanQualType AccumTy
Definition: ASTContext.h:1132
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1151
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1150
CanQualType LongTy
Definition: ASTContext.h:1128
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1128
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1141
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:1134
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:1137
CanQualType ShortAccumTy
Definition: ASTContext.h:1132
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1242
CanQualType FloatTy
Definition: ASTContext.h:1131
CanQualType DoubleTy
Definition: ASTContext.h:1131
CanQualType SatLongAccumTy
Definition: ASTContext.h:1137
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:2029
CanQualType LongDoubleTy
Definition: ASTContext.h:1131
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1160
CanQualType Char16Ty
Definition: ASTContext.h:1126
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2007
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1136
CanQualType DependentTy
Definition: ASTContext.h:1147
CanQualType NullPtrTy
Definition: ASTContext.h:1146
CanQualType OMPIteratorTy
Definition: ASTContext.h:1160
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:827
CanQualType SatShortFractTy
Definition: ASTContext.h:1140
CanQualType Ibm128Ty
Definition: ASTContext.h:1131
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1138
CanQualType ArraySectionTy
Definition: ASTContext.h:1159
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1151
CanQualType BoolTy
Definition: ASTContext.h:1120
RecordDecl * getCFConstantStringTagDecl() const
CanQualType UnsignedFractTy
Definition: ASTContext.h:1136
CanQualType Float128Ty
Definition: ASTContext.h:1131
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1151
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1147
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:2041
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1129
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1134
CanQualType ShortFractTy
Definition: ASTContext.h:1135
CanQualType BoundMemberTy
Definition: ASTContext.h:1147
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1141
CanQualType CharTy
Definition: ASTContext.h:1121
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
CanQualType IntTy
Definition: ASTContext.h:1128
CanQualType PseudoObjectTy
Definition: ASTContext.h:1150
CanQualType Float16Ty
Definition: ASTContext.h:1145
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2210
CanQualType SignedCharTy
Definition: ASTContext.h:1128
CanQualType OverloadTy
Definition: ASTContext.h:1147
CanQualType OCLClkEventTy
Definition: ASTContext.h:1156
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:1138
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:1130
CanQualType BuiltinFnTy
Definition: ASTContext.h:1149
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1156
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1119
CanQualType UnsignedCharTy
Definition: ASTContext.h:1129
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1136
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:734
CanQualType UnsignedIntTy
Definition: ASTContext.h:1129
TagDecl * getMSGuidTagDecl() const
Retrieve the implicitly-predeclared 'struct _GUID' declaration.
Definition: ASTContext.h:2191
CanQualType UnknownAnyTy
Definition: ASTContext.h:1148
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1130
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1157
CanQualType UnsignedShortTy
Definition: ASTContext.h:1129
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1142
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1467
CanQualType ShortTy
Definition: ASTContext.h:1128
CanQualType FractTy
Definition: ASTContext.h:1135
DiagnosticsEngine & getDiagnostics() const
CanQualType LongAccumTy
Definition: ASTContext.h:1133
CanQualType Char32Ty
Definition: ASTContext.h:1127
CanQualType SatFractTy
Definition: ASTContext.h:1140
CanQualType SatLongFractTy
Definition: ASTContext.h:1140
CanQualType OCLQueueTy
Definition: ASTContext.h:1157
CanQualType LongFractTy
Definition: ASTContext.h:1135
CanQualType SatShortAccumTy
Definition: ASTContext.h:1137
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1144
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1158
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:2017
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1139
CanQualType LongLongTy
Definition: ASTContext.h:1128
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
CanQualType WCharTy
Definition: ASTContext.h:1122
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:1061
CanQualType Char8Ty
Definition: ASTContext.h:1125
CanQualType HalfTy
Definition: ASTContext.h:1143
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1134
void setCFConstantStringType(QualType T)
CanQualType OCLEventTy
Definition: ASTContext.h:1156
virtual void MacroRead(serialization::MacroID ID, MacroInfo *MI)
A macro was read from the AST file.
virtual void SelectorRead(serialization::SelectorID iD, Selector Sel)
A selector was read from the AST file.
virtual void IdentifierRead(serialization::IdentifierID ID, IdentifierInfo *II)
An identifier was deserialized from the AST file.
An identifier-lookup iterator that enumerates all of the identifiers stored within a set of AST files...
Definition: ASTReader.cpp:8544
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
Definition: ASTReader.cpp:8572
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Definition: ASTReader.cpp:8577
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:114
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:221
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, 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:233
virtual bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, StringRef ModuleFilename, bool Complain)
Receives the diagnostic options.
Definition: ASTReader.h:153
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition: ASTReader.h:191
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition: ASTReader.h:162
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition: ASTReader.h:204
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain)
Receives the header search options.
Definition: ASTReader.h:175
virtual void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata)
Indicates that a particular module file extension has been read.
Definition: ASTReader.h:247
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, 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:244
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition: ASTReader.h:216
virtual bool needsImportVisitation() const
Returns true if this ASTReaderListener wants to receive the imports of the AST file via visitImport,...
Definition: ASTReader.h:240
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:212
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:225
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:378
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:6518
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
Definition: ASTReader.cpp:6299
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
Definition: ASTReader.cpp:2321
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:9740
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
Definition: ASTReader.cpp:927
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
Definition: ASTReader.cpp:9151
ExtKind hasExternalDefinitions(const Decl *D) override
Definition: ASTReader.cpp:9232
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
Definition: ASTReader.cpp:9615
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1795
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
Definition: ASTReader.cpp:7752
friend class ASTIdentifierIterator
Definition: ASTReader.h:383
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
Definition: ASTReader.cpp:1603
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
Definition: ASTReader.cpp:9621
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
Definition: ASTReader.cpp:9591
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition: ASTReader.h:2403
Decl * ReadDecl(ModuleFile &F, const RecordDataImpl &R, unsigned &I)
Reads a declaration from the given position in a record in the given module.
Definition: ASTReader.h:1982
static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx)
Definition: ASTReader.cpp:9550
void ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector< Decl *, 4 > &Decls) override
Read the set of decls to be checked for deferred diags.
Definition: ASTReader.cpp:8866
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
Definition: ASTReader.cpp:8374
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition: ASTReader.h:1637
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1650
@ 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:1641
@ 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:1645
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &Exprs) override
Definition: ASTReader.cpp:8796
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:8100
SourceRange ReadSkippedRange(unsigned Index) override
Read a preallocated skipped range from the external source.
Definition: ASTReader.cpp:6285
serialization::TypeID getGlobalTypeID(ModuleFile &F, serialization::LocalTypeID LocalID) const
Map a local type ID within a given AST file into a global type ID.
Definition: ASTReader.cpp:7517
void dump()
Dump information about the AST reader to standard error.
Definition: ASTReader.cpp:8341
void AssignedLambdaNumbering(const CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
Definition: ASTReader.cpp:8966
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
Definition: ASTReader.cpp:1903
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition: ASTReader.h:2437
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
Definition: ASTReader.cpp:9239
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:8022
ModuleFile * getOwningModuleFile(const Decl *D) const
Retrieve the module file that owns the given declaration, or NULL if the declaration is not from a mo...
Definition: ASTReader.cpp:7772
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
Definition: ASTReader.cpp:9214
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
Definition: ASTReader.cpp:8196
QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID)
Resolve a local type ID within a given AST file into a type.
Definition: ASTReader.cpp:7513
void ClearSwitchCaseIDs()
Definition: ASTReader.cpp:9633
SourceLocation ReadSourceLocation(ModuleFile &MF, RawLocEncoding Raw, LocSeq *Seq=nullptr) const
Read a source location from raw form.
Definition: ASTReader.h:2268
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< GlobalDeclID > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
Definition: ASTReader.cpp:9007
bool loadGlobalIndex()
Attempts to load the global index.
Definition: ASTReader.cpp:4377
void ReadComments() override
Loads comments ranges.
Definition: ASTReader.cpp:9637
SourceManager & getSourceManager() const
Definition: ASTReader.h:1622
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
Definition: ASTReader.cpp:7779
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:4313
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:5267
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition: ASTReader.h:2415
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
Definition: ASTReader.cpp:7655
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:9709
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:8226
LocalDeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, GlobalDeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
Definition: ASTReader.cpp:7962
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
Definition: ASTReader.cpp:2332
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override
Finds all the visible declarations with a given name.
Definition: ASTReader.cpp:8144
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Definition: ASTReader.cpp:8812
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7596
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
Definition: ASTReader.cpp:7991
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:1531
~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:7598
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:1823
void SetIdentifierInfo(serialization::IdentifierID ID, IdentifierInfo *II)
Definition: ASTReader.cpp:8982
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:2034
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:6505
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
Definition: ASTReader.cpp:8505
IdentifierInfo * getLocalIdentifier(ModuleFile &M, uint64_t LocalID)
Definition: ASTReader.cpp:9086
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:9725
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
Definition: ASTReader.cpp:9180
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Definition: ASTReader.cpp:6278
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Definition: ASTReader.cpp:8006
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
Definition: ASTReader.cpp:9268
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:1896
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
Definition: ASTReader.cpp:9109
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:8785
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
Definition: ASTReader.cpp:8833
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
Definition: ASTReader.cpp:7210
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint32_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
Definition: ASTReader.cpp:2172
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx, LocSeq *Seq=nullptr)
Read a source range.
Definition: ASTReader.cpp:9525
GlobalDeclID getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const
Map from a local declaration ID within a given module to a global declaration ID.
Definition: ASTReader.cpp:7729
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:8894
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
Definition: ASTReader.cpp:8172
void warnStackExhausted(SourceLocation Loc)
Definition: ASTReader.cpp:9599
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
Definition: ASTReader.cpp:8854
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:5440
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
Definition: ASTReader.cpp:8844
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:2758
SmallVector< GlobalDeclID, 16 > PreloadedDeclIDs
Definition: ASTReader.h:2410
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:1786
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
Definition: ASTReader.cpp:8822
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Definition: ASTReader.cpp:8876
Selector DecodeSelector(serialization::SelectorID Idx)
Definition: ASTReader.cpp:9243
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:4468
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition: ASTReader.h:1803
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9557
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Definition: ASTReader.cpp:9197
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
Definition: ASTReader.cpp:9055
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition: ASTReader.h:398
@ Success
The control block was read successfully.
Definition: ASTReader.h:401
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition: ASTReader.h:418
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition: ASTReader.h:411
@ Failure
The AST file itself appears corrupted.
Definition: ASTReader.h:404
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition: ASTReader.h:414
@ HadErrors
The AST file has errors.
Definition: ASTReader.h:421
@ Missing
The AST file was missing.
Definition: ASTReader.h:407
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Definition: ASTReader.cpp:9572
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
Definition: ASTReader.cpp:1850
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
Definition: ASTReader.cpp:9628
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID)
Definition: ASTReader.cpp:9090
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:8937
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
Definition: ASTReader.cpp:8630
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
Definition: ASTReader.cpp:8912
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:4402
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
Definition: ASTReader.cpp:9272
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Definition: ASTReader.cpp:8769
Decl * GetExistingDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration.
Definition: ASTReader.cpp:7915
static llvm::BitVector ReadBitVector(const RecordData &Record, const StringRef Blob)
Definition: ASTReader.cpp:9532
ModuleFile * getLocalModuleFile(ModuleFile &M, unsigned ID) const
Retrieve the module file with a given local ID within the specified ModuleFile.
Definition: ASTReader.cpp:9184
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
Definition: ASTReader.cpp:8977
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
Definition: ASTReader.cpp:6577
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
Definition: ASTReader.cpp:4299
void UpdateSema()
Update the state of Sema after loading some additional modules.
Definition: ASTReader.cpp:8400
Decl * GetDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7941
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:1566
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending) override
Read the set of pending instantiations known to the external Sema source.
Definition: ASTReader.cpp:8925
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition: ASTReader.h:1799
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9584
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:8774
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
Definition: ASTReader.cpp:9166
void PrintStats() override
Print some statistics about AST usage.
Definition: ASTReader.cpp:8236
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:4362
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:9278
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:8729
void InitializeContext()
Initializes the ASTContext.
Definition: ASTReader.cpp:5124
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:7687
FileManager & getFileManager() const
Definition: ASTReader.h:1623
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:5734
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:2296
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
Definition: ASTReader.cpp:2178
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
Definition: ASTReader.cpp:6568
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:9136
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:9545
TemplateArgumentLoc readTemplateArgumentLoc()
Reads a TemplateArgumentLoc, advancing Idx.
Definition: ASTReader.cpp:7570
void readTypeLoc(TypeLoc TL, LocSeq *Seq=nullptr)
Reads the location information for a type.
Definition: ASTReader.cpp:7164
void readUnresolvedSet(LazyASTUnresolvedSet &Set)
Read a UnresolvedSet structure, advancing Idx.
Definition: ASTReader.cpp:9373
void readTemplateArgumentList(SmallVectorImpl< TemplateArgument > &TemplArgs, bool Canonicalize=false)
Read a template argument array, advancing Idx.
Definition: ASTReader.cpp:9363
void readQualifierInfo(QualifierInfo &Info)
Definition: ASTReader.cpp:9331
DeclarationNameLoc readDeclarationNameLoc(DeclarationName Name)
Read a declaration name, advancing Idx.
Definition: ASTReader.cpp:9294
CXXBaseSpecifier readCXXBaseSpecifier()
Read a C++ base specifier, advancing Idx.
Definition: ASTReader.cpp:9384
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:9319
IdentifierInfo * readIdentifier()
TemplateArgumentLocInfo readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind, advancing Idx.
Definition: ASTReader.cpp:7538
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:7171
void readTemplateArgumentListInfo(TemplateArgumentListInfo &Result)
Definition: ASTReader.cpp:7580
TypeCoupledDeclRefInfo readTypeCoupledDeclRefInfo()
Definition: ASTReader.cpp:9327
void skipInts(unsigned N)
Skips the specified number of values.
GlobalDeclID readDeclID()
Reads a declaration ID from the given position in this record.
SourceRange readSourceRange(LocSeq *Seq=nullptr)
Read a source range, advancing Idx.
NestedNameSpecifierLoc readNestedNameSpecifierLoc()
Return a nested name specifier, advancing Idx.
Definition: ASTReader.cpp:9464
ConceptReference * readConceptReference()
Definition: ASTReader.cpp:7007
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:9344
OpenACCClause * readOpenACCClause()
Read an OpenACC clause, advancing Idx.
llvm::SmallVector< Expr * > readOpenACCVarList()
Read a list of Exprs used for a var-list.
CXXCtorInitializer ** readCXXCtorInitializers()
Read a CXXCtorInitializer array, advancing Idx.
Definition: ASTReader.cpp:9399
Stmt * readStmt()
Reads a statement.
const ASTTemplateArgumentListInfo * readASTTemplateArgumentListInfo()
Definition: ASTReader.cpp:7590
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.
llvm::SmallVector< Expr * > readOpenACCIntExprList()
Read a list of Exprs used for a int-expr-list.
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...
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:2539
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2304
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition: DeclCXX.h:2491
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
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:1724
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition: DeclCXX.h:1796
base_class_iterator bases_begin()
Definition: DeclCXX.h:627
base_class_iterator vbases_begin()
Definition: DeclCXX.h:644
Represents a C++ temporary.
Definition: ExprCXX.h:1457
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1093
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:247
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
Definition: ASTReader.cpp:160
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:207
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
Definition: ASTReader.cpp:201
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:225
void ReadModuleMapFile(StringRef ModuleMapPath) override
Definition: ASTReader.cpp:170
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:175
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:184
void ReadModuleName(StringRef ModuleName) override
Definition: ASTReader.cpp:165
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.cpp:231
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:216
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
Definition: ASTReader.cpp:263
void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
Definition: ASTReader.cpp:241
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:193
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.cpp:236
A reference to a concept and its template args, as it appears in the code.
Definition: ASTConcept.h:124
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:88
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
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1262
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition: DeclBase.h:2677
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
void setMustBuildLookupTable()
Mark that there are external lexical declarations that we need to include in our lookup table (and th...
Definition: DeclBase.h:2650
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2665
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1423
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2350
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition: DeclBase.h:2671
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:2691
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1622
unsigned getModuleFileIndex() const
Definition: DeclID.h:130
DeclID getRawValue() const
Definition: DeclID.h:120
unsigned getLocalDeclIndex() const
Definition: DeclBase.cpp:2217
uint64_t DeclID
An ID number that refers to a declaration in an AST file.
Definition: DeclID.h:113
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition: DeclBase.h:849
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:806
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:787
SourceLocation getLocation() const
Definition: DeclBase.h:446
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1039
DeclContext * getDeclContext()
Definition: DeclBase.h:455
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:449
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition: DeclBase.cpp:113
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:860
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
static DeclarationNameLoc makeCXXLiteralOperatorNameLoc(SourceLocation Loc)
Construct location information for a literal C++ operator.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
NameKind
The kind of the name stored in this DeclarationName.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:731
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:6914
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.
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-headers-in-module=... options used to override whether -Wsystem-headers is enabl...
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:3844
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:947
static FPOptionsOverride getFromOpaqueInt(storage_type I)
Definition: LangOptions.h:1010
FPOptions applyOverrides(FPOptions Base)
Definition: LangOptions.h:1017
static FPOptions getFromOpaqueInt(storage_type Value)
Definition: LangOptions.h:911
Represents a member of a struct/union/class.
Definition: Decl.h:3030
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
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:251
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:240
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt)
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:1932
void setLazyBody(uint64_t Offset)
Definition: Decl.h:2264
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5266
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:446
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:3318
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:476
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:511
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:482
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:540
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
Definition: LangOptions.h:554
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:550
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:531
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:537
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...
static LocalDeclID get(ASTReader &Reader, serialization::ModuleFile &MF, DeclID ID)
Definition: ASTReader.cpp:937
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
llvm::DenseSet< FileEntryRef > AdditionalModMapsSet
Definition: ModuleMap.h:197
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:676
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:350
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition: Module.h:472
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition: Module.h:305
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition: Module.h:395
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Module.h:387
@ Hidden
All of the names in this module are hidden.
Definition: Module.h:389
@ AllVisible
All of the names in this module are visible.
Definition: Module.h:391
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:716
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition: Module.h:506
void setASTFile(OptionalFileEntryRef File)
Set the serialized AST file for the top-level module of this module.
Definition: Module.h:686
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition: Module.h:333
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:339
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition: Module.h:378
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:464
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition: Module.h:433
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition: Module.h:700
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition: Module.h:296
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:383
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition: Module.h:368
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:360
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:485
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition: Module.h:320
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition: Module.h:412
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition: Module.h:692
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:316
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition: Module.h:355
OptionalFileEntryRef getASTFile() const
The serialized AST file for this module, if one was created.
Definition: Module.h:681
std::vector< Conflict > Conflicts
The list of conflicts.
Definition: Module.h:497
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:3124
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 the 'absent' clause in the '#pragma omp assume' directive.
static OMPAbsentClause * CreateEmpty(const ASTContext &C, unsigned NumKinds)
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:448
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:492
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:414
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 'schedule',...
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.
This represents 'compare' clause in the '#pragma omp atomic' directive.
This represents the 'contains' clause in the '#pragma omp assume' directive.
static OMPContainsClause * CreateEmpty(const ASTContext &C, unsigned NumKinds)
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:690
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:939
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 the 'holds' clause in the '#pragma omp assume' directive.
This represents 'if' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:587
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 the 'no_openmp' clause in the '#pragma omp assume' directive.
This represents the 'no_openmp_routines' clause in the '#pragma omp assume' directive.
This represents the 'no_parallelism' clause in the '#pragma omp assume' 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.
static OMPNumTeamsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'num_threads' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:736
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:967
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:781
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:816
This represents the 'sizes' clause in the '#pragma omp tile' directive.
Definition: OpenMPClause.h:848
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.
static OMPThreadLimitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'threads' clause in the '#pragma omp ...' directive.
This represents clause 'to' in the '#pragma omp ...' directives.
static OMPToClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
This represents 'unified_address' clause in the '#pragma omp requires' directive.
This represents 'unified_shared_memory' clause in the '#pragma omp requires' directive.
This represents 'untied' clause in the '#pragma omp ...' directive.
This represents 'update' clause in the '#pragma omp atomic' directive.
static OMPUpdateClause * CreateEmpty(const ASTContext &C, bool IsExtended)
Creates an empty clause with the place for N variables.
This represents the 'use' clause in '#pragma omp ...' directives.
This represents clause 'use_device_addr' in the '#pragma omp ...' directives.
static OMPUseDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'use_device_ptr' in the '#pragma omp ...' directives.
static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'uses_allocators' in the '#pragma omp target'-based directives.
static OMPUsesAllocatorsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N allocators.
This represents 'weak' clause in the '#pragma omp atomic' directives.
This represents 'write' clause in the '#pragma omp atomic' directive.
This represents 'ompx_attribute' clause in a directive that might generate an outlined function.
This represents 'ompx_bare' clause in the '#pragma omp target teams ...' directive.
This represents 'ompx_dyn_cgroup_mem' clause in the '#pragma omp target ...' directive.
method_range methods() const
Definition: DeclObjC.h:1015
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:1091
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1101
void setNameEndLoc(SourceLocation Loc)
Definition: TypeLoc.h:1113
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7343
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
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:2083
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
static OpenACCAsyncClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCAttachClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCAutoClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
This is the base type for all OpenACC Clauses.
Definition: OpenACCClause.h:24
static OpenACCCopyClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyInClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, bool IsReadOnly, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyOutClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, bool IsZero, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCreateClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, bool IsZero, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDefaultClause * Create(const ASTContext &C, OpenACCDefaultClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
static OpenACCDevicePtrClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceTypeClause * Create(const ASTContext &C, OpenACCClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< DeviceTypeArgument > Archs, SourceLocation EndLoc)
static OpenACCFirstPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCIfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCIndependentClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCNoCreateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, 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 OpenACCPresentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCReductionClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCReductionOperator Operator, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCSelfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCSeqClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCVectorLengthClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCWaitClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *DevNumExpr, SourceLocation QueuesLoc, ArrayRef< Expr * > QueueIdExprs, 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:301
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:457
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:883
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:596
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:894
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:838
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:466
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:1722
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:137
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:941
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
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:319
@ FastWidth
The width of the "fast" qualifier mask.
Definition: Type.h:363
@ FastMask
The fast qualifier mask.
Definition: Type.h:366
void setAmpAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1412
Represents a struct/union/class.
Definition: Decl.h:4145
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:5965
void AddDecl(Decl *D)
Definition: Scope.h:345
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.
std::pair< iterator, bool > insert(std::pair< Selector, Lists > &&Val)
Definition: SemaObjC.h:218
iterator find(Selector Sel)
Definition: SemaObjC.h:217
llvm::DenseMap< Selector, Lists >::iterator iterator
Definition: SemaObjC.h:214
std::pair< ObjCMethodList, ObjCMethodList > Lists
Definition: SemaObjC.h:213
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method)
Add the given method to the list of globally-known methods.
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition: SemaObjC.h:234
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
SemaObjC & ObjC()
Definition: Sema.h:1164
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:923
void addExternalSource(ExternalSemaSource *E)
Registers an external source.
Definition: Sema.cpp:604
void warnStackExhausted(SourceLocation Loc)
Warn that the stack is nearly exhausted.
Definition: Sema.cpp:566
IdentifierResolver IdResolver
Definition: Sema.h:3016
PragmaMsStackAction
Definition: Sema.h:1482
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition: ASTReader.h:332
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:850
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.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
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:3561
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3659
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:312
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:6548
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:3215
void VisitArrayTypeLoc(ArrayTypeLoc)
Definition: ASTReader.cpp:6880
void VisitFunctionTypeLoc(FunctionTypeLoc)
Definition: ASTReader.cpp:6947
TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
Definition: ASTReader.cpp:6808
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:7721
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:1829
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3409
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:667
Represents a variable declaration or definition.
Definition: Decl.h:879
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1841
Captures information about a #pragma weak directive.
Definition: Weak.h:25
Source location and bit offset of a declaration.
Definition: ASTBitCodes.h:252
A key used when looking up entities by DeclarationName.
Definition: ASTBitCodes.h:2074
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
Definition: ASTReader.cpp:1205
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:372
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition: ModuleFile.h:321
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition: ModuleFile.h:435
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:463
ContinuousRangeMap< uint32_t, int, 2 > PreprocessedEntityRemap
Remapping table for preprocessed entity IDs in this module.
Definition: ModuleFile.h:370
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition: ModuleFile.h:285
serialization::IdentifierID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition: ModuleFile.h:311
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition: ModuleFile.h:367
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition: ModuleFile.h:483
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition: ModuleFile.h:466
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition: ModuleFile.h:338
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:325
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition: ModuleFile.h:301
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition: ModuleFile.h:442
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition: ModuleFile.h:317
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:420
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition: ModuleFile.h:491
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition: ModuleFile.h:391
SourceLocation ImportLoc
The source location where this module was first imported.
Definition: ModuleFile.h:233
const serialization::unaligned_decl_id_t * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition: ModuleFile.h:458
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:331
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
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition: ModuleFile.h:363
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:400
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:509
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:417
unsigned BaseDeclIndex
Base declaration index in ASTReader for declarations local to this module.
Definition: ModuleFile.h:455
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:395
unsigned Index
The index of this module in the list of modules.
Definition: ModuleFile.h:133
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:403
uint64_t SizeInBits
The size of this file, in bits.
Definition: ModuleFile.h:207
const UnalignedUInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition: ModuleFile.h:479
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:475
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition: ModuleFile.h:244
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition: ModuleFile.h:378
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:360
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition: ModuleFile.h:288
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition: ModuleFile.h:452
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:354
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:334
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition: ModuleFile.h:428
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:448
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition: ModuleFile.h:384
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition: ModuleFile.h:190
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:308
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition: ModuleFile.h:423
ContinuousRangeMap< uint32_t, int, 2 > MacroRemap
Remapping table for macro IDs in this module.
Definition: ModuleFile.h:351
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition: ModuleFile.h:345
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:406
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:445
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition: ModuleFile.h:488
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition: ModuleFile.h:376
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition: ModuleFile.h:413
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:348
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition: ModuleFile.h:470
std::string BaseDirectory
The base directory of the module.
Definition: ModuleFile.h:145
llvm::SmallVector< ModuleFile *, 16 > TransitiveImports
List of modules which this modules dependent on.
Definition: ModuleFile.h:502
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:46
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.
Source range/offset of a preprocessed entity.
Definition: ASTBitCodes.h:211
RawLocEncoding getBegin() const
Definition: ASTBitCodes.h:227
RawLocEncoding getEnd() const
Definition: ASTBitCodes.h:228
Source range of a skipped preprocessor region.
Definition: ASTBitCodes.h:234
RawLocEncoding getBegin() const
Definition: ASTBitCodes.h:246
RawLocEncoding getEnd() const
Definition: ASTBitCodes.h:247
ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration)
Definition: ASTReader.cpp:8658
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8700
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8705
static TypeIdx fromTypeID(TypeID ID)
Definition: ASTBitCodes.h:121
32 aligned uint64_t in the AST file.
Definition: ASTBitCodes.h:194
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:1043
static hash_value_type ComputeHash(const internal_key_type &a)
Definition: ASTReader.cpp:1038
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Definition: ASTReader.cpp:1048
Class that performs lookup for an identifier stored in an AST file.
IdentifierID ReadIdentifierID(const unsigned char *d)
Definition: ASTReader.cpp:1072
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:1089
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:976
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:998
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:971
static hash_value_type ComputeHash(Selector Sel)
Definition: ASTReader.cpp:933
Trait class used to search the on-disk hash table containing all of the header search information.
PredefinedTypeIDs
Predefined type IDs.
Definition: ASTBitCodes.h:879
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
Definition: ASTBitCodes.h:2019
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:1142
const unsigned NumSpecialTypeIDs
The number of special type IDs.
Definition: ASTBitCodes.h:1197
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:1156
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
Definition: ASTBitCodes.h:1025
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
Definition: ASTBitCodes.h:998
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
Definition: ASTBitCodes.h:947
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
Definition: ASTBitCodes.h:956
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
Definition: ASTBitCodes.h:1055
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
Definition: ASTBitCodes.h:1103
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
Definition: ASTBitCodes.h:1037
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
Definition: ASTBitCodes.h:977
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
Definition: ASTBitCodes.h:971
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
Definition: ASTBitCodes.h:926
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
Definition: ASTBitCodes.h:1040
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
Definition: ASTBitCodes.h:983
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
Definition: ASTBitCodes.h:1046
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
Definition: ASTBitCodes.h:1088
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
Definition: ASTBitCodes.h:887
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
Definition: ASTBitCodes.h:1061
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
Definition: ASTBitCodes.h:1079
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
Definition: ASTBitCodes.h:1073
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
Definition: ASTBitCodes.h:890
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
Definition: ASTBitCodes.h:1004
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
Definition: ASTBitCodes.h:1058
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
Definition: ASTBitCodes.h:989
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
Definition: ASTBitCodes.h:1019
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
Definition: ASTBitCodes.h:929
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
Definition: ASTBitCodes.h:1001
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
Definition: ASTBitCodes.h:920
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
Definition: ASTBitCodes.h:965
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
Definition: ASTBitCodes.h:1100
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
Definition: ASTBitCodes.h:914
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
Definition: ASTBitCodes.h:893
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
Definition: ASTBitCodes.h:1031
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
Definition: ASTBitCodes.h:911
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
Definition: ASTBitCodes.h:908
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
Definition: ASTBitCodes.h:950
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
Definition: ASTBitCodes.h:1052
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
Definition: ASTBitCodes.h:1013
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
Definition: ASTBitCodes.h:899
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
Definition: ASTBitCodes.h:1010
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
Definition: ASTBitCodes.h:959
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
Definition: ASTBitCodes.h:953
@ PREDEF_TYPE_ARRAY_SECTION
The placeholder type for an array section.
Definition: ASTBitCodes.h:1007
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
Definition: ASTBitCodes.h:905
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
Definition: ASTBitCodes.h:1085
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
Definition: ASTBitCodes.h:896
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
Definition: ASTBitCodes.h:917
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
Definition: ASTBitCodes.h:1091
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
Definition: ASTBitCodes.h:941
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
Definition: ASTBitCodes.h:935
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
Definition: ASTBitCodes.h:932
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
Definition: ASTBitCodes.h:944
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
Definition: ASTBitCodes.h:980
@ PREDEF_TYPE_VOID_ID
The void type.
Definition: ASTBitCodes.h:884
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
Definition: ASTBitCodes.h:1082
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
Definition: ASTBitCodes.h:1022
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
Definition: ASTBitCodes.h:1076
@ PREDEF_TYPE_NULL_ID
The NULL type.
Definition: ASTBitCodes.h:881
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
Definition: ASTBitCodes.h:1028
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
Definition: ASTBitCodes.h:1016
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
Definition: ASTBitCodes.h:1049
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
Definition: ASTBitCodes.h:938
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
Definition: ASTBitCodes.h:1097
@ PREDEF_TYPE_UNRESOLVED_TEMPLATE
The placeholder type for unresolved templates.
Definition: ASTBitCodes.h:1132
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
Definition: ASTBitCodes.h:1064
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
Definition: ASTBitCodes.h:923
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
Definition: ASTBitCodes.h:1070
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
Definition: ASTBitCodes.h:1043
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
Definition: ASTBitCodes.h:968
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
Definition: ASTBitCodes.h:1094
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
Definition: ASTBitCodes.h:986
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
Definition: ASTBitCodes.h:962
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
Definition: ASTBitCodes.h:902
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
Definition: ASTBitCodes.h:1067
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
Definition: ASTBitCodes.h:995
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
Definition: ASTBitCodes.h:992
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
Definition: ASTBitCodes.h:1034
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
Definition: ASTBitCodes.h:974
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1432
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
Definition: ASTBitCodes.h:1312
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1435
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1321
@ TYPE_EXT_QUAL
An ExtQualType record.
Definition: ASTBitCodes.h:1162
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
Definition: ASTBitCodes.h:1190
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
Definition: ASTBitCodes.h:1193
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
Definition: ASTBitCodes.h:1178
@ SPECIAL_TYPE_FILE
C FILE typedef type.
Definition: ASTBitCodes.h:1175
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
Definition: ASTBitCodes.h:1181
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
Definition: ASTBitCodes.h:1187
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
Definition: ASTBitCodes.h:1172
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Definition: ASTBitCodes.h:1184
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.
uint64_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:88
@ EXTENSION_METADATA
Metadata describing this particular extension.
Definition: ASTBitCodes.h:432
llvm::support::detail::packed_endian_specific_integral< serialization::DeclID, llvm::endianness::native, llvm::support::unaligned > unaligned_decl_id_t
Definition: ASTBitCodes.h:286
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
Definition: ASTBitCodes.h:828
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:810
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:848
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:807
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
Definition: ASTBitCodes.h:856
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
Definition: ASTBitCodes.h:813
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:804
@ SUBMODULE_METADATA
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:796
@ SUBMODULE_REQUIRES
Specifies a required feature.
Definition: ASTBitCodes.h:824
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:840
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:817
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
Definition: ASTBitCodes.h:837
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
Definition: ASTBitCodes.h:852
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:800
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:831
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:834
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:821
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:844
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
Definition: ASTBitCodes.h:859
TypeID LocalTypeID
Same with TypeID except that the LocalTypeID is only meaningful with the corresponding ModuleFile.
Definition: ASTBitCodes.h:94
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition: ASTBitCodes.h:66
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:185
OptionsRecordTypes
Record types that occur within the options block inside the control block.
Definition: ASTBitCodes.h:383
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
Definition: ASTBitCodes.h:396
@ TARGET_OPTIONS
Record code for the target options table.
Definition: ASTBitCodes.h:393
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
Definition: ASTBitCodes.h:402
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
Definition: ASTBitCodes.h:399
@ LANGUAGE_OPTIONS
Record code for the language options table.
Definition: ASTBitCodes.h:390
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:167
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
Definition: ASTBitCodes.h:289
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:182
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
Definition: ASTBitCodes.h:188
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
Definition: ASTBitCodes.h:314
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
Definition: ASTBitCodes.h:311
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
Definition: ASTBitCodes.h:296
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
Definition: ASTBitCodes.h:300
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
Definition: ASTBitCodes.h:322
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
Definition: ASTBitCodes.h:308
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
Definition: ASTBitCodes.h:304
@ COMMENTS_BLOCK_ID
The block containing comments.
Definition: ASTBitCodes.h:317
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
Definition: ASTBitCodes.h:344
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
Definition: ASTBitCodes.h:338
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
Definition: ASTBitCodes.h:335
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
Definition: ASTBitCodes.h:328
CommentRecordTypes
Record types used within a comments block.
Definition: ASTBitCodes.h:863
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:733
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:747
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:737
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:743
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:751
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
Definition: ASTBitCodes.h:170
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
Definition: ASTCommon.cpp:469
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:47
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:70
PreprocessorRecordTypes
Record types used within a preprocessor block.
Definition: ASTBitCodes.h:755
@ PP_TOKEN
Describes one token.
Definition: ASTBitCodes.h:770
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
Definition: ASTBitCodes.h:766
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
Definition: ASTBitCodes.h:761
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:773
@ PP_MODULE_MACRO
A macro directive exported by a module.
Definition: ASTBitCodes.h:777
ControlRecordTypes
Record types that occur within the control block.
Definition: ASTBitCodes.h:348
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
Definition: ASTBitCodes.h:375
@ MODULE_DIRECTORY
Record code for the module build directory.
Definition: ASTBitCodes.h:378
@ IMPORTS
Record code for the list of other AST files imported by this AST file.
Definition: ASTBitCodes.h:355
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
Definition: ASTBitCodes.h:364
@ MODULE_NAME
Record code for the module name.
Definition: ASTBitCodes.h:371
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
Definition: ASTBitCodes.h:360
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
Definition: ASTBitCodes.h:368
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
Definition: ASTBitCodes.h:351
UnhashedControlBlockRecordTypes
Record codes for the unhashed control block.
Definition: ASTBitCodes.h:406
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:414
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
Definition: ASTBitCodes.h:423
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
Definition: ASTBitCodes.h:411
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:420
@ SIGNATURE
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:408
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
Definition: ASTBitCodes.h:417
@ VFS_USAGE
Record code for the indices of used VFSs.
Definition: ASTBitCodes.h:426
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
Definition: ASTBitCodes.h:440
@ INPUT_FILE_HASH
The input file content hash.
Definition: ASTBitCodes.h:445
@ INPUT_FILE
An input file.
Definition: ASTBitCodes.h:442
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
Definition: ASTBitCodes.h:781
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:790
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:783
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:786
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
uint64_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:63
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
Definition: ASTBitCodes.h:164
ASTRecordTypes
Record types that occur within the AST block itself.
Definition: ASTBitCodes.h:449
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:590
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:524
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
Definition: ASTBitCodes.h:710
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:616
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:520
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:579
@ TYPE_OFFSET
Record code for the offsets of each type.
Definition: ASTBitCodes.h:462
@ DELEGATING_CTORS
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:612
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
Definition: ASTBitCodes.h:716
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:549
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:609
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:606
@ PP_UNSAFE_BUFFER_USAGE
Record code for #pragma clang unsafe_buffer_usage begin/end.
Definition: ASTBitCodes.h:723
@ VTABLE_USES
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:559
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
Definition: ASTBitCodes.h:666
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
Definition: ASTBitCodes.h:707
@ DECL_OFFSET
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:474
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:626
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
Definition: ASTBitCodes.h:540
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:677
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:586
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched #pragma clang cuda_force_host_device begin directives we've seen.
Definition: ASTBitCodes.h:687
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:654
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:556
@ VTABLES_TO_EMIT
Record code for vtables to emit.
Definition: ASTBitCodes.h:726
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:482
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:647
@ METHOD_POOL
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:536
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
Definition: ASTBitCodes.h:720
@ PP_CONDITIONAL_STACK
The stack of open #ifs/#ifdefs recorded in a preamble.
Definition: ASTBitCodes.h:701
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
Definition: ASTBitCodes.h:564
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:544
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:576
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
Definition: ASTBitCodes.h:663
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:633
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:680
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:527
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:552
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
Definition: ASTBitCodes.h:698
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
Definition: ASTBitCodes.h:637
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:533
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:672
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:511
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
Definition: ASTBitCodes.h:659
@ HEADER_SEARCH_TABLE
Record code for header search information.
Definition: ASTBitCodes.h:603
@ 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:630
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:600
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:568
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
Definition: ASTBitCodes.h:704
@ IDENTIFIER_TABLE
Record code for the identifier table.
Definition: ASTBitCodes.h:501
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:573
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:669
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:622
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:683
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:154
unsigned ComputeHash(Selector Sel)
Definition: ASTCommon.cpp:294
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'.
@ PCopyOut
'copyout' clause alias 'pcopyout'. Preserved for diagnostic purposes.
@ 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.
@ PresentOrCreate
'create' clause alias 'present_or_create'.
@ Collapse
'collapse' clause, allowed on 'loop' and Combined constructs.
@ NoHost
'nohost' clause, allowed on 'routine' directives.
@ PresentOrCopy
'copy' clause alias 'present_or_copy'. Preserved for diagnostic purposes.
@ 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
'create' 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'.
@ PresentOrCopyOut
'copyout' clause alias 'present_or_copyout'.
@ 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.
@ PCopy
'copy' clause alias 'pcopy'. Preserved for diagnostic purposes.
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
@ PCopyIn
'copyin' clause alias 'pcopyin'. Preserved for diagnostic purposes.
@ DeviceResident
'device_resident' clause, allowed on the 'declare' construct.
@ PCreate
'create' clause alias 'pcreate'. Preserved for diagnostic purposes.
@ 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.
@ PresentOrCopyIn
'copyin' clause alias 'present_or_copyin'.
@ 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:56
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition: OpenMPKinds.h:24
OpenMPDefaultmapClauseModifier
OpenMP modifiers for 'defaultmap' clause.
Definition: OpenMPKinds.h:118
OpenMPOrderClauseModifier
OpenMP modifiers for 'order' clause.
Definition: OpenMPKinds.h:171
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition: Warnings.cpp:44
OpenMPAtClauseKind
OpenMP attributes for 'at' clause.
Definition: OpenMPKinds.h:135
OpenMPReductionClauseModifier
OpenMP modifiers for 'reduction' clause.
Definition: OpenMPKinds.h:186
OpenMPScheduleClauseModifier
OpenMP modifiers for 'schedule' clause.
Definition: OpenMPKinds.h:38
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
Definition: OpenMPKinds.h:103
OpenMPDoacrossClauseModifier
OpenMP dependence types for 'doacross' clause.
Definition: OpenMPKinds.h:219
static constexpr unsigned NumberOfOMPMapClauseModifiers
Number of allowed map-type-modifiers.
Definition: OpenMPKinds.h:87
const unsigned int NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition: DeclID.h:93
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
PredefinedDeclIDs
Predefined declaration IDs.
Definition: DeclID.h:33
@ PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID
The internal '__NSConstantString' tag type.
Definition: DeclID.h:83
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition: DeclID.h:38
@ PREDEF_DECL_TYPE_PACK_ELEMENT_ID
The internal '__type_pack_element' template.
Definition: DeclID.h:86
@ PREDEF_DECL_OBJC_CLASS_ID
The Objective-C 'Class' type.
Definition: DeclID.h:47
@ PREDEF_DECL_BUILTIN_MS_GUID_ID
The predeclared '_GUID' struct.
Definition: DeclID.h:71
@ PREDEF_DECL_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition: DeclID.h:59
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition: DeclID.h:50
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition: DeclID.h:56
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition: DeclID.h:44
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition: DeclID.h:53
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition: DeclID.h:65
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition: DeclID.h:68
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition: DeclID.h:80
@ PREDEF_DECL_NULL_ID
The NULL declaration.
Definition: DeclID.h:35
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition: DeclID.h:62
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition: DeclID.h:74
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition: DeclID.h:41
@ PREDEF_DECL_MAKE_INTEGER_SEQ_ID
The internal '__make_integer_seq' template.
Definition: DeclID.h:77
@ 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:462
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
const FunctionProtoType * T
OpenACCReductionOperator
Definition: OpenACCKinds.h:495
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:2507
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:325
@ 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:123
OpenMPMapClauseKind
OpenMP mapping kind for 'map' clause.
Definition: OpenMPKinds.h:70
unsigned long uint64_t
unsigned int uint32_t
#define true
Definition: stdbool.h:25
#define bool
Definition: stdbool.h:24
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:5094
The preprocessor keeps track of this information for each file that is #included.
Definition: HeaderSearch.h:59
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:119
LazyIdentifierInfoPtr LazyControllingMacro
If this file has a #ifndef XXX (or equivalent) guard that protects the entire contents of the file,...
Definition: HeaderSearch.h:133
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
Definition: HeaderSearch.h:81
unsigned isPragmaOnce
True if this is a #pragma once file.
Definition: HeaderSearch.h:74
unsigned IsValid
Whether this file has been looked up as a header.
Definition: HeaderSearch.h:123
unsigned isImport
True if this is a #import'd file.
Definition: HeaderSearch.h:70
StringRef Framework
If this header came from a framework include, this is the name of the framework.
Definition: HeaderSearch.h:137
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
Definition: HeaderSearch.h:86
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:488
Module * Other
The module that this module conflicts with.
Definition: Module.h:490
std::string Message
The message provided to the user when there is a conflict.
Definition: Module.h:493
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:447
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.
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:704
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition: Decl.h:718
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:705
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition: Decl.h:711
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:1493
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
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:2030