clang 24.0.0git
ASTWriter.cpp
Go to the documentation of this file.
1//===- ASTWriter.cpp - AST File Writer ------------------------------------===//
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 ASTWriter class, which writes AST files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ASTCommon.h"
14#include "ASTReaderInternals.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclObjC.h"
30#include "clang/AST/Expr.h"
31#include "clang/AST/ExprCXX.h"
38#include "clang/AST/Type.h"
39#include "clang/AST/TypeLoc.h"
47#include "clang/Basic/LLVM.h"
48#include "clang/Basic/Lambda.h"
50#include "clang/Basic/Module.h"
60#include "clang/Basic/Version.h"
63#include "clang/Lex/MacroInfo.h"
64#include "clang/Lex/ModuleMap.h"
68#include "clang/Lex/Token.h"
71#include "clang/Sema/Sema.h"
72#include "clang/Sema/SemaCUDA.h"
73#include "clang/Sema/SemaObjC.h"
76#include "clang/Sema/Weak.h"
86#include "llvm/ADT/APFloat.h"
87#include "llvm/ADT/APInt.h"
88#include "llvm/ADT/ArrayRef.h"
89#include "llvm/ADT/DenseMap.h"
90#include "llvm/ADT/DenseSet.h"
91#include "llvm/ADT/PointerIntPair.h"
92#include "llvm/ADT/STLExtras.h"
93#include "llvm/ADT/ScopeExit.h"
94#include "llvm/ADT/SmallPtrSet.h"
95#include "llvm/ADT/SmallString.h"
96#include "llvm/ADT/SmallVector.h"
97#include "llvm/ADT/StringRef.h"
98#include "llvm/Bitstream/BitCodes.h"
99#include "llvm/Bitstream/BitstreamWriter.h"
100#include "llvm/Support/Compression.h"
101#include "llvm/Support/DJB.h"
102#include "llvm/Support/EndianStream.h"
103#include "llvm/Support/ErrorHandling.h"
104#include "llvm/Support/LEB128.h"
105#include "llvm/Support/MemoryBuffer.h"
106#include "llvm/Support/OnDiskHashTable.h"
107#include "llvm/Support/Path.h"
108#include "llvm/Support/SHA1.h"
109#include "llvm/Support/TimeProfiler.h"
110#include "llvm/Support/VersionTuple.h"
111#include "llvm/Support/VirtualFileSystem.h"
112#include "llvm/Support/raw_ostream.h"
113#include <algorithm>
114#include <cassert>
115#include <cstdint>
116#include <cstdlib>
117#include <cstring>
118#include <ctime>
119#include <limits>
120#include <memory>
121#include <optional>
122#include <queue>
123#include <tuple>
124#include <utility>
125#include <vector>
126
127using namespace clang;
128using namespace clang::serialization;
129
130template <typename T, typename Allocator>
131static StringRef bytes(const std::vector<T, Allocator> &v) {
132 if (v.empty()) return StringRef();
133 return StringRef(reinterpret_cast<const char*>(&v[0]),
134 sizeof(T) * v.size());
135}
136
137template <typename T>
138static StringRef bytes(const SmallVectorImpl<T> &v) {
139 return StringRef(reinterpret_cast<const char*>(v.data()),
140 sizeof(T) * v.size());
141}
142
143static std::string bytes(const std::vector<bool> &V) {
144 std::string Str;
145 Str.reserve(V.size() / 8);
146 for (unsigned I = 0, E = V.size(); I < E;) {
147 char Byte = 0;
148 for (unsigned Bit = 0; Bit < 8 && I < E; ++Bit, ++I)
149 Byte |= V[I] << Bit;
150 Str += Byte;
151 }
152 return Str;
153}
154
155//===----------------------------------------------------------------------===//
156// Type serialization
157//===----------------------------------------------------------------------===//
158
160 switch (id) {
161#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
162 case Type::CLASS_ID: return TYPE_##CODE_ID;
163#include "clang/Serialization/TypeBitCodes.def"
164 case Type::LateParsedAttr:
165 llvm_unreachable(
166 "should be replaced with a concrete type before serialization");
167 case Type::Builtin:
168 llvm_unreachable("shouldn't be serializing a builtin type this way");
169 }
170 llvm_unreachable("bad type kind");
171}
172
173namespace {
174
175struct AffectingModuleMaps {
176 llvm::DenseSet<FileID> DefinitionFileIDs;
177 llvm::DenseSet<const FileEntry *> DefinitionFiles;
178};
179
180std::optional<AffectingModuleMaps>
181GetAffectingModuleMaps(const Preprocessor &PP, Module *RootModule) {
182 if (!PP.getHeaderSearchInfo()
185 return std::nullopt;
186
187 const HeaderSearch &HS = PP.getHeaderSearchInfo();
188 const SourceManager &SM = PP.getSourceManager();
189 const ModuleMap &MM = HS.getModuleMap();
190
191 // Module maps used only by textual headers are special. Their FileID is
192 // non-affecting, but their FileEntry is (i.e. must be written as InputFile).
193 enum AffectedReason : bool {
194 AR_TextualHeader = 0,
195 AR_ImportOrTextualHeader = 1,
196 };
197 auto AssignMostImportant = [](AffectedReason &LHS, AffectedReason RHS) {
198 LHS = std::max(LHS, RHS);
199 };
200 llvm::DenseMap<FileID, AffectedReason> ModuleMaps;
201 llvm::DenseMap<const Module *, AffectedReason> ProcessedModules;
202 auto CollectModuleMapsForHierarchy = [&](const Module *M,
203 AffectedReason Reason) {
204 M = M->getTopLevelModule();
205
206 // We need to process the header either when it was not present or when we
207 // previously flagged module map as textual headers and now we found a
208 // proper import.
209 if (auto [It, Inserted] = ProcessedModules.insert({M, Reason});
210 !Inserted && Reason <= It->second) {
211 return;
212 } else {
213 It->second = Reason;
214 }
215
216 std::queue<const Module *> Q;
217 Q.push(M);
218 while (!Q.empty()) {
219 const Module *Mod = Q.front();
220 Q.pop();
221
222 // The containing module map is affecting, because it's being pointed
223 // into by Module::DefinitionLoc.
224 if (auto F = MM.getContainingModuleMapFileID(Mod); F.isValid())
225 AssignMostImportant(ModuleMaps[F], Reason);
226 // For inferred modules, the module map that allowed inferring is not
227 // related to the virtual containing module map file. It did affect the
228 // compilation, though.
229 if (auto UniqF = MM.getModuleMapFileIDForUniquing(Mod); UniqF.isValid())
230 AssignMostImportant(ModuleMaps[UniqF], Reason);
231
232 for (Module *SubM : Mod->submodules())
233 Q.push(SubM);
234 }
235 };
236
237 // Handle all the affecting modules referenced from the root module.
238
239 CollectModuleMapsForHierarchy(RootModule, AR_ImportOrTextualHeader);
240
241 std::queue<const Module *> Q;
242 Q.push(RootModule);
243 while (!Q.empty()) {
244 const Module *CurrentModule = Q.front();
245 Q.pop();
246
247 for (const Module *ImportedModule : CurrentModule->Imports)
248 CollectModuleMapsForHierarchy(ImportedModule, AR_ImportOrTextualHeader);
249 for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses)
250 CollectModuleMapsForHierarchy(UndeclaredModule, AR_ImportOrTextualHeader);
251
252 for (Module *M : CurrentModule->submodules())
253 Q.push(M);
254 }
255
256 // Handle textually-included headers that belong to other modules.
258 [&](FileEntryRef File, const HeaderFileInfo &HFI) {
260 return; // Modular header, handled in the above module-based loop.
262 return; // Non-modular header not included locally is not affecting.
263
264 for (const auto &KH : HS.findResolvedModulesForHeader(File))
265 if (const Module *M = KH.getModule())
266 CollectModuleMapsForHierarchy(M, AR_TextualHeader);
267 });
268
269 // FIXME: This algorithm is not correct for module map hierarchies where
270 // module map file defining a (sub)module of a top-level module X includes
271 // a module map file that defines a (sub)module of another top-level module Y.
272 // Whenever X is affecting and Y is not, "replaying" this PCM file will fail
273 // when parsing module map files for X due to not knowing about the `extern`
274 // module map for Y.
275 //
276 // We don't have a good way to fix it here. We could mark all children of
277 // affecting module map files as being affecting as well, but that's
278 // expensive. SourceManager does not model the edge from parent to child
279 // SLocEntries, so instead, we would need to iterate over leaf module map
280 // files, walk up their include hierarchy and check whether we arrive at an
281 // affecting module map.
282 //
283 // Instead of complicating and slowing down this function, we should probably
284 // just ban module map hierarchies where module map defining a (sub)module X
285 // includes a module map defining a module that's not a submodule of X.
286
287 llvm::DenseSet<const FileEntry *> ModuleFileEntries;
288 llvm::DenseSet<FileID> ModuleFileIDs;
289 for (auto [FID, Reason] : ModuleMaps) {
290 if (Reason == AR_ImportOrTextualHeader)
291 ModuleFileIDs.insert(FID);
292 if (auto *FE = SM.getFileEntryForID(FID))
293 ModuleFileEntries.insert(FE);
294 }
295
296 AffectingModuleMaps R;
297 R.DefinitionFileIDs = std::move(ModuleFileIDs);
298 R.DefinitionFiles = std::move(ModuleFileEntries);
299 return std::move(R);
300}
301
302class ASTTypeWriter {
303 ASTWriter &Writer;
305 ASTRecordWriter BasicWriter;
306
307public:
308 ASTTypeWriter(ASTContext &Context, ASTWriter &Writer)
309 : Writer(Writer), BasicWriter(Context, Writer, Record) {}
310
311 uint64_t write(QualType T) {
312 if (T.hasLocalNonFastQualifiers()) {
313 Qualifiers Qs = T.getLocalQualifiers();
314 BasicWriter.writeQualType(T.getLocalUnqualifiedType());
315 BasicWriter.writeQualifiers(Qs);
316 return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
317 }
318
319 const Type *typePtr = T.getTypePtr();
320 serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
321 atw.write(typePtr);
322 return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
323 /*abbrev*/ 0);
324 }
325};
326
327class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
328 ASTRecordWriter &Record;
329
330 void addSourceLocation(SourceLocation Loc) { Record.AddSourceLocation(Loc); }
331 void addSourceRange(SourceRange Range) { Record.AddSourceRange(Range); }
332
333public:
334 TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
335
336#define ABSTRACT_TYPELOC(CLASS, PARENT)
337#define TYPELOC(CLASS, PARENT) \
338 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
339#include "clang/AST/TypeLocNodes.def"
340
341 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
342 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
343 void VisitTagTypeLoc(TagTypeLoc TL);
344};
345
346} // namespace
347
348void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
349 // nothing to do
350}
351
352void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
353 addSourceLocation(TL.getBuiltinLoc());
354 if (TL.needsExtraLocalData()) {
355 Record.push_back(TL.getWrittenTypeSpec());
356 Record.push_back(static_cast<uint64_t>(TL.getWrittenSignSpec()));
357 Record.push_back(static_cast<uint64_t>(TL.getWrittenWidthSpec()));
358 Record.push_back(TL.hasModeAttr());
359 }
360}
361
362void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
363 addSourceLocation(TL.getNameLoc());
364}
365
366void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
367 addSourceLocation(TL.getStarLoc());
368}
369
370void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
371 // nothing to do
372}
373
374void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
375 // nothing to do
376}
377
378void TypeLocWriter::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
379 // nothing to do
380}
381
382void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
383 addSourceLocation(TL.getCaretLoc());
384}
385
386void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
387 addSourceLocation(TL.getAmpLoc());
388}
389
390void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
391 addSourceLocation(TL.getAmpAmpLoc());
392}
393
394void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
395 addSourceLocation(TL.getStarLoc());
396 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
397}
398
399void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
400 addSourceLocation(TL.getLBracketLoc());
401 addSourceLocation(TL.getRBracketLoc());
402 Record.push_back(TL.getSizeExpr() ? 1 : 0);
403 if (TL.getSizeExpr())
404 Record.AddStmt(TL.getSizeExpr());
405}
406
407void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
408 VisitArrayTypeLoc(TL);
409}
410
411void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
412 VisitArrayTypeLoc(TL);
413}
414
415void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
416 VisitArrayTypeLoc(TL);
417}
418
419void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
420 DependentSizedArrayTypeLoc TL) {
421 VisitArrayTypeLoc(TL);
422}
423
424void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
425 DependentAddressSpaceTypeLoc TL) {
426 addSourceLocation(TL.getAttrNameLoc());
427 SourceRange range = TL.getAttrOperandParensRange();
428 addSourceLocation(range.getBegin());
429 addSourceLocation(range.getEnd());
430 Record.AddStmt(TL.getAttrExprOperand());
431}
432
433void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
434 DependentSizedExtVectorTypeLoc TL) {
435 addSourceLocation(TL.getNameLoc());
436 addSourceLocation(TL.getAttrNameLoc());
437 Record.AddStmt(TL.getSizeExpr());
438}
439
440void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
441 addSourceLocation(TL.getNameLoc());
442 addSourceLocation(TL.getAttrNameLoc());
443 Record.AddStmt(TL.getSizeExpr());
444}
445
446void TypeLocWriter::VisitDependentVectorTypeLoc(
447 DependentVectorTypeLoc TL) {
448 addSourceLocation(TL.getNameLoc());
449 addSourceLocation(TL.getAttrNameLoc());
450 Record.AddStmt(TL.getSizeExpr());
451}
452
453void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
454 VisitVectorTypeLoc(TL);
455}
456
457void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
458 addSourceLocation(TL.getAttrNameLoc());
459 SourceRange range = TL.getAttrOperandParensRange();
460 addSourceLocation(range.getBegin());
461 addSourceLocation(range.getEnd());
462 Record.AddStmt(TL.getAttrRowOperand());
463 Record.AddStmt(TL.getAttrColumnOperand());
464}
465
466void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
467 DependentSizedMatrixTypeLoc TL) {
468 addSourceLocation(TL.getAttrNameLoc());
469 SourceRange range = TL.getAttrOperandParensRange();
470 addSourceLocation(range.getBegin());
471 addSourceLocation(range.getEnd());
472 Record.AddStmt(TL.getAttrRowOperand());
473 Record.AddStmt(TL.getAttrColumnOperand());
474}
475
476void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
477 addSourceLocation(TL.getLocalRangeBegin());
478 addSourceLocation(TL.getLParenLoc());
479 addSourceLocation(TL.getRParenLoc());
480 addSourceRange(TL.getExceptionSpecRange());
481 addSourceLocation(TL.getLocalRangeEnd());
482 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
483 Record.AddDeclRef(TL.getParam(i));
484}
485
486void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
487 VisitFunctionTypeLoc(TL);
488}
489
490void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
491 VisitFunctionTypeLoc(TL);
492}
493
494void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
495 addSourceLocation(TL.getElaboratedKeywordLoc());
496 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
497 addSourceLocation(TL.getNameLoc());
498}
499
500void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) {
501 addSourceLocation(TL.getElaboratedKeywordLoc());
502 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
503 addSourceLocation(TL.getNameLoc());
504}
505
506void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
507 addSourceLocation(TL.getElaboratedKeywordLoc());
508 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
509 addSourceLocation(TL.getNameLoc());
510}
511
512void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
513 if (TL.getNumProtocols()) {
514 addSourceLocation(TL.getProtocolLAngleLoc());
515 addSourceLocation(TL.getProtocolRAngleLoc());
516 }
517 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
518 addSourceLocation(TL.getProtocolLoc(i));
519}
520
521void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
522 addSourceLocation(TL.getTypeofLoc());
523 addSourceLocation(TL.getLParenLoc());
524 addSourceLocation(TL.getRParenLoc());
525}
526
527void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
528 addSourceLocation(TL.getTypeofLoc());
529 addSourceLocation(TL.getLParenLoc());
530 addSourceLocation(TL.getRParenLoc());
531 Record.AddTypeSourceInfo(TL.getUnmodifiedTInfo());
532}
533
534void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
535 addSourceLocation(TL.getDecltypeLoc());
536 addSourceLocation(TL.getRParenLoc());
537}
538
539void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
540 addSourceLocation(TL.getKWLoc());
541 addSourceLocation(TL.getLParenLoc());
542 addSourceLocation(TL.getRParenLoc());
543 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
544}
545
557
558void TypeLocWriter::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
559 addSourceLocation(TL.getEllipsisLoc());
560}
561
562void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
563 addSourceLocation(TL.getNameLoc());
564 auto *CR = TL.getConceptReference();
565 Record.push_back(TL.isConstrained() && CR);
566 if (TL.isConstrained() && CR)
567 Record.AddConceptReference(CR);
568 Record.push_back(TL.isDecltypeAuto());
569 if (TL.isDecltypeAuto())
570 addSourceLocation(TL.getRParenLoc());
571}
572
573void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
574 DeducedTemplateSpecializationTypeLoc TL) {
575 addSourceLocation(TL.getElaboratedKeywordLoc());
576 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
577 addSourceLocation(TL.getTemplateNameLoc());
578}
579
580void TypeLocWriter::VisitTagTypeLoc(TagTypeLoc TL) {
581 addSourceLocation(TL.getElaboratedKeywordLoc());
582 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
583 addSourceLocation(TL.getNameLoc());
584}
585
586void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
587 VisitTagTypeLoc(TL);
588}
589
590void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
591 VisitTagTypeLoc(TL);
592}
593
594void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) { VisitTagTypeLoc(TL); }
595
596void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
597 Record.AddAttr(TL.getAttr());
598}
599
600void TypeLocWriter::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
601 // Nothing to do
602}
603
604void TypeLocWriter::VisitLateParsedAttrTypeLoc(LateParsedAttrTypeLoc TL) {
605 llvm_unreachable(
606 "should be replaced with a concrete type before serialization");
607}
608
609void TypeLocWriter::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
610 // Nothing to do.
611}
612
613void TypeLocWriter::VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
614 addSourceLocation(TL.getAttrLoc());
615}
616
617void TypeLocWriter::VisitHLSLAttributedResourceTypeLoc(
618 HLSLAttributedResourceTypeLoc TL) {
619 // Nothing to do.
620}
621
622void TypeLocWriter::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
623 // Nothing to do.
624}
625
626void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
627 addSourceLocation(TL.getNameLoc());
628}
629
630void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
631 SubstTemplateTypeParmTypeLoc TL) {
632 addSourceLocation(TL.getNameLoc());
633}
634
635void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
636 SubstTemplateTypeParmPackTypeLoc TL) {
637 addSourceLocation(TL.getNameLoc());
638}
639
640void TypeLocWriter::VisitSubstBuiltinTemplatePackTypeLoc(
641 SubstBuiltinTemplatePackTypeLoc TL) {
642 addSourceLocation(TL.getNameLoc());
643}
644
645void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
646 TemplateSpecializationTypeLoc TL) {
647 addSourceLocation(TL.getElaboratedKeywordLoc());
648 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
649 addSourceLocation(TL.getTemplateKeywordLoc());
650 addSourceLocation(TL.getTemplateNameLoc());
651 addSourceLocation(TL.getLAngleLoc());
652 addSourceLocation(TL.getRAngleLoc());
653 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
654 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i));
655}
656
657void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
658 addSourceLocation(TL.getLParenLoc());
659 addSourceLocation(TL.getRParenLoc());
660}
661
662void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
663 addSourceLocation(TL.getExpansionLoc());
664}
665
666void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
667 addSourceLocation(TL.getElaboratedKeywordLoc());
668 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
669 addSourceLocation(TL.getNameLoc());
670}
671
672void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
673 addSourceLocation(TL.getEllipsisLoc());
674}
675
676void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
677 addSourceLocation(TL.getNameLoc());
678 addSourceLocation(TL.getNameEndLoc());
679}
680
681void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
682 Record.push_back(TL.hasBaseTypeAsWritten());
683 addSourceLocation(TL.getTypeArgsLAngleLoc());
684 addSourceLocation(TL.getTypeArgsRAngleLoc());
685 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
686 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
687 addSourceLocation(TL.getProtocolLAngleLoc());
688 addSourceLocation(TL.getProtocolRAngleLoc());
689 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
690 addSourceLocation(TL.getProtocolLoc(i));
691}
692
693void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
694 addSourceLocation(TL.getStarLoc());
695}
696
697void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
698 addSourceLocation(TL.getKWLoc());
699 addSourceLocation(TL.getLParenLoc());
700 addSourceLocation(TL.getRParenLoc());
701}
702
703void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
704 addSourceLocation(TL.getKWLoc());
705}
706void TypeLocWriter::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
707 addSourceLocation(TL.getNameLoc());
708}
709void TypeLocWriter::VisitDependentBitIntTypeLoc(
710 clang::DependentBitIntTypeLoc TL) {
711 addSourceLocation(TL.getNameLoc());
712}
713
714void TypeLocWriter::VisitPredefinedSugarTypeLoc(
715 clang::PredefinedSugarTypeLoc TL) {
716 // Nothing to do.
717}
718
719void ASTWriter::WriteTypeAbbrevs() {
720 using namespace llvm;
721
722 std::shared_ptr<BitCodeAbbrev> Abv;
723
724 // Abbreviation for TYPE_EXT_QUAL
725 Abv = std::make_shared<BitCodeAbbrev>();
726 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
727 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
728 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
729 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
730}
731
732//===----------------------------------------------------------------------===//
733// ASTWriter Implementation
734//===----------------------------------------------------------------------===//
735
736static void EmitBlockID(unsigned ID, const char *Name,
737 llvm::BitstreamWriter &Stream,
739 Record.clear();
740 Record.push_back(ID);
741 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
742
743 // Emit the block name if present.
744 if (!Name || Name[0] == 0)
745 return;
746 Record.clear();
747 while (*Name)
748 Record.push_back(*Name++);
749 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
750}
751
752static void EmitRecordID(unsigned ID, const char *Name,
753 llvm::BitstreamWriter &Stream,
755 Record.clear();
756 Record.push_back(ID);
757 while (*Name)
758 Record.push_back(*Name++);
759 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
760}
761
762static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
764#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
894#undef RECORD
895}
896
897void ASTWriter::WriteBlockInfoBlock() {
898 RecordData Record;
899 Stream.EnterBlockInfoBlock();
900
901#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
902#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
903
904 // Control Block.
905 BLOCK(CONTROL_BLOCK);
911 RECORD(IMPORT);
915
916 BLOCK(OPTIONS_BLOCK);
923
924 BLOCK(INPUT_FILES_BLOCK);
927
928 // AST Top-Level Block.
929 BLOCK(AST_BLOCK);
990
991 // SourceManager Block.
992 BLOCK(SOURCE_MANAGER_BLOCK);
998
999 // Preprocessor Block.
1000 BLOCK(PREPROCESSOR_BLOCK);
1006
1007 // Submodule Block.
1008 BLOCK(SUBMODULE_BLOCK);
1029
1030 // Comments Block.
1031 BLOCK(COMMENTS_BLOCK);
1033
1034 // Decls and Types block.
1035 BLOCK(DECLTYPES_BLOCK);
1037 RECORD(TYPE_COMPLEX);
1038 RECORD(TYPE_POINTER);
1039 RECORD(TYPE_BLOCK_POINTER);
1040 RECORD(TYPE_LVALUE_REFERENCE);
1041 RECORD(TYPE_RVALUE_REFERENCE);
1042 RECORD(TYPE_MEMBER_POINTER);
1043 RECORD(TYPE_CONSTANT_ARRAY);
1044 RECORD(TYPE_INCOMPLETE_ARRAY);
1045 RECORD(TYPE_VARIABLE_ARRAY);
1046 RECORD(TYPE_VECTOR);
1047 RECORD(TYPE_EXT_VECTOR);
1048 RECORD(TYPE_FUNCTION_NO_PROTO);
1049 RECORD(TYPE_FUNCTION_PROTO);
1050 RECORD(TYPE_TYPEDEF);
1051 RECORD(TYPE_TYPEOF_EXPR);
1052 RECORD(TYPE_TYPEOF);
1053 RECORD(TYPE_RECORD);
1054 RECORD(TYPE_ENUM);
1055 RECORD(TYPE_OBJC_INTERFACE);
1056 RECORD(TYPE_OBJC_OBJECT_POINTER);
1057 RECORD(TYPE_DECLTYPE);
1058 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1059 RECORD(TYPE_UNRESOLVED_USING);
1060 RECORD(TYPE_INJECTED_CLASS_NAME);
1061 RECORD(TYPE_OBJC_OBJECT);
1062 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1063 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1064 RECORD(TYPE_DEPENDENT_NAME);
1065 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1066 RECORD(TYPE_PAREN);
1067 RECORD(TYPE_MACRO_QUALIFIED);
1068 RECORD(TYPE_PACK_EXPANSION);
1069 RECORD(TYPE_ATTRIBUTED);
1070 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
1071 RECORD(TYPE_SUBST_BUILTIN_TEMPLATE_PACK);
1072 RECORD(TYPE_AUTO);
1073 RECORD(TYPE_UNARY_TRANSFORM);
1074 RECORD(TYPE_ATOMIC);
1075 RECORD(TYPE_DECAYED);
1076 RECORD(TYPE_ADJUSTED);
1077 RECORD(TYPE_OBJC_TYPE_PARAM);
1154
1155 // Statements and Exprs can occur in the Decls and Types block.
1156 AddStmtsExprs(Stream, Record);
1157
1158 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1162
1163 // Decls and Types block.
1164 BLOCK(EXTENSION_BLOCK);
1166
1167 BLOCK(UNHASHED_CONTROL_BLOCK);
1175
1176#undef RECORD
1177#undef BLOCK
1178 Stream.ExitBlock();
1179}
1180
1181/// Adjusts the given filename to only write out the portion of the
1182/// filename that is not part of the system root directory.
1183///
1184/// \param Filename the file name to adjust.
1185///
1186/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1187/// the filename will be adjusted by this root directory.
1188///
1189/// \returns true if \p Filename was adjusted.
1191 StringRef BaseDir) {
1192 if (BaseDir.empty())
1193 return false;
1194
1195 // Verify that the filename and the system root have the same prefix.
1196 unsigned Pos = 0;
1197 for (; Pos < Filename.size() && Pos < BaseDir.size(); ++Pos)
1198 if (Filename[Pos] != BaseDir[Pos])
1199 return false; // Prefixes don't match.
1200
1201 // We hit the end of the filename before we hit the end of the system root.
1202 if (Pos == Filename.size()) {
1203 if (Pos != BaseDir.size())
1204 return false;
1205 // The filename is the system root itself.
1206 Filename.assign(1, '.');
1207 return true;
1208 }
1209
1210 // If there's not a path separator at the end of the base directory nor
1211 // immediately after it, then this isn't within the base directory.
1212 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1213 if (!llvm::sys::path::is_separator(BaseDir.back()))
1214 return false;
1215 } else {
1216 // If the file name has a '/' at the current position, skip over the '/'.
1217 // We distinguish relative paths from absolute paths by the
1218 // absence of '/' at the beginning of relative paths.
1219 //
1220 // FIXME: This is wrong. We distinguish them by asking if the path is
1221 // absolute, which isn't the same thing. And there might be multiple '/'s
1222 // in a row. Use a better mechanism to indicate whether we have emitted an
1223 // absolute or relative path.
1224 ++Pos;
1225 }
1226
1227 Filename.erase(Filename.begin(), Filename.begin() + Pos);
1228 return true;
1229}
1230
1231std::pair<ASTFileSignature, ASTFileSignature>
1232ASTWriter::createSignature() const {
1233 StringRef AllBytes(Buffer.data(), Buffer.size());
1234
1235 llvm::SHA1 Hasher;
1236 Hasher.update(AllBytes.slice(ASTBlockRange.first, ASTBlockRange.second));
1237 ASTFileSignature ASTBlockHash = ASTFileSignature::create(Hasher.result());
1238
1239 // Add the remaining bytes:
1240 // 1. Before the unhashed control block.
1241 Hasher.update(AllBytes.slice(0, UnhashedControlBlockRange.first));
1242 // 2. Between the unhashed control block and the AST block.
1243 Hasher.update(
1244 AllBytes.slice(UnhashedControlBlockRange.second, ASTBlockRange.first));
1245 // 3. After the AST block.
1246 Hasher.update(AllBytes.substr(ASTBlockRange.second));
1247 ASTFileSignature Signature = ASTFileSignature::create(Hasher.result());
1248
1249 return std::make_pair(ASTBlockHash, Signature);
1250}
1251
1252ASTFileSignature ASTWriter::createSignatureForNamedModule() const {
1253 llvm::SHA1 Hasher;
1254 Hasher.update(StringRef(Buffer.data(), Buffer.size()));
1255
1256 assert(WritingModule);
1257 assert(WritingModule->isNamedModule());
1258
1259 // We need to combine all the export imported modules no matter
1260 // we used it or not.
1261 for (auto [ExportImported, _] : WritingModule->Exports)
1262 Hasher.update(ExportImported->Signature);
1263
1264 // We combine all the used modules to make sure the signature is precise.
1265 // Consider the case like:
1266 //
1267 // // a.cppm
1268 // export module a;
1269 // export inline int a() { ... }
1270 //
1271 // // b.cppm
1272 // export module b;
1273 // import a;
1274 // export inline int b() { return a(); }
1275 //
1276 // Since both `a()` and `b()` are inline, we need to make sure the BMI of
1277 // `b.pcm` will change after the implementation of `a()` changes. We can't
1278 // get that naturally since we won't record the body of `a()` during the
1279 // writing process. We can't reuse ODRHash here since ODRHash won't calculate
1280 // the called function recursively. So ODRHash will be problematic if `a()`
1281 // calls other inline functions.
1282 //
1283 // Probably we can solve this by a new hash mechanism. But the safety and
1284 // efficiency may a problem too. Here we just combine the hash value of the
1285 // used modules conservatively.
1286 for (Module *M : TouchedTopLevelModules)
1287 Hasher.update(M->Signature);
1288
1289 return ASTFileSignature::create(Hasher.result());
1290}
1291
1292static void BackpatchSignatureAt(llvm::BitstreamWriter &Stream,
1293 const ASTFileSignature &S, uint64_t BitNo) {
1294 for (uint8_t Byte : S) {
1295 Stream.BackpatchByte(BitNo, Byte);
1296 BitNo += 8;
1297 }
1298}
1299
1300ASTFileSignature ASTWriter::backpatchSignature() {
1301 if (isWritingStdCXXNamedModules()) {
1302 ASTFileSignature Signature = createSignatureForNamedModule();
1303 BackpatchSignatureAt(Stream, Signature, SignatureOffset);
1304 return Signature;
1305 }
1306
1307 if (!WritingModule ||
1309 return {};
1310
1311 // For implicit modules, write the hash of the PCM as its signature.
1312 ASTFileSignature ASTBlockHash;
1313 ASTFileSignature Signature;
1314 std::tie(ASTBlockHash, Signature) = createSignature();
1315
1316 BackpatchSignatureAt(Stream, ASTBlockHash, ASTBlockHashOffset);
1317 BackpatchSignatureAt(Stream, Signature, SignatureOffset);
1318
1319 return Signature;
1320}
1321
1322void ASTWriter::writeUnhashedControlBlock(Preprocessor &PP) {
1323 using namespace llvm;
1324
1325 // Flush first to prepare the PCM hash (signature).
1326 Stream.FlushToWord();
1327 UnhashedControlBlockRange.first = Stream.GetCurrentBitNo() >> 3;
1328
1329 // Enter the block and prepare to write records.
1330 RecordData Record;
1331 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1332
1333 // For implicit modules and C++20 named modules, write the hash of the PCM as
1334 // its signature.
1335 if (isWritingStdCXXNamedModules() ||
1336 (WritingModule &&
1338 // At this point, we don't know the actual signature of the file or the AST
1339 // block - we're only able to compute those at the end of the serialization
1340 // process. Let's store dummy signatures for now, and replace them with the
1341 // real ones later on.
1342 // The bitstream VBR-encodes record elements, which makes backpatching them
1343 // really difficult. Let's store the signatures as blobs instead - they are
1344 // guaranteed to be word-aligned, and we control their format/encoding.
1345 auto Dummy = ASTFileSignature::createDummy();
1346 SmallString<128> Blob{Dummy.begin(), Dummy.end()};
1347
1348 // We don't need AST Block hash in named modules.
1349 if (!isWritingStdCXXNamedModules()) {
1350 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1351 Abbrev->Add(BitCodeAbbrevOp(AST_BLOCK_HASH));
1352 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1353 unsigned ASTBlockHashAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1354
1355 Record.push_back(AST_BLOCK_HASH);
1356 Stream.EmitRecordWithBlob(ASTBlockHashAbbrev, Record, Blob);
1357 ASTBlockHashOffset = Stream.GetCurrentBitNo() - Blob.size() * 8;
1358 Record.clear();
1359 }
1360
1361 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1362 Abbrev->Add(BitCodeAbbrevOp(SIGNATURE));
1363 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1364 unsigned SignatureAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1365
1366 Record.push_back(SIGNATURE);
1367 Stream.EmitRecordWithBlob(SignatureAbbrev, Record, Blob);
1368 SignatureOffset = Stream.GetCurrentBitNo() - Blob.size() * 8;
1369 Record.clear();
1370 }
1371
1372 const auto &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1373
1374 // Diagnostic options.
1375 const auto &Diags = PP.getDiagnostics();
1376 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1377 if (!HSOpts.ModulesSkipDiagnosticOptions) {
1378#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1379#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1380 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1381#include "clang/Basic/DiagnosticOptions.def"
1382 Record.push_back(DiagOpts.Warnings.size());
1383 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1384 AddString(DiagOpts.Warnings[I], Record);
1385 Record.push_back(DiagOpts.Remarks.size());
1386 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1387 AddString(DiagOpts.Remarks[I], Record);
1388 // Note: we don't serialize the log or serialization file names, because
1389 // they are generally transient files and will almost always be overridden.
1390 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1391 Record.clear();
1392 }
1393
1394 // Header search paths.
1395 if (!HSOpts.ModulesSkipHeaderSearchPaths) {
1396 // Include entries.
1397 Record.push_back(HSOpts.UserEntries.size());
1398 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1399 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1400 AddString(Entry.Path, Record);
1401 Record.push_back(static_cast<unsigned>(Entry.Group));
1402 Record.push_back(Entry.IsFramework);
1403 Record.push_back(Entry.IgnoreSysRoot);
1404 }
1405
1406 // System header prefixes.
1407 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1408 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1409 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1410 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1411 }
1412
1413 // VFS overlay files.
1414 Record.push_back(HSOpts.VFSOverlayFiles.size());
1415 for (StringRef VFSOverlayFile : HSOpts.VFSOverlayFiles)
1416 AddString(VFSOverlayFile, Record);
1417
1418 Stream.EmitRecord(HEADER_SEARCH_PATHS, Record);
1419 }
1420
1421 if (!HSOpts.ModulesSkipPragmaDiagnosticMappings)
1422 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
1423
1424 // Header search entry usage.
1425 {
1426 auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage();
1427 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1428 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_ENTRY_USAGE));
1429 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1430 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Bit vector.
1431 unsigned HSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1432 RecordData::value_type Record[] = {HEADER_SEARCH_ENTRY_USAGE,
1433 HSEntryUsage.size()};
1434 Stream.EmitRecordWithBlob(HSUsageAbbrevCode, Record, bytes(HSEntryUsage));
1435 }
1436
1437 // VFS usage.
1438 {
1439 auto VFSUsage = PP.getHeaderSearchInfo().collectVFSUsageAndClear();
1440 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1441 Abbrev->Add(BitCodeAbbrevOp(VFS_USAGE));
1442 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1443 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Bit vector.
1444 unsigned VFSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1445 RecordData::value_type Record[] = {VFS_USAGE, VFSUsage.size()};
1446 Stream.EmitRecordWithBlob(VFSUsageAbbrevCode, Record, bytes(VFSUsage));
1447 }
1448
1449 // Leave the options block.
1450 Stream.ExitBlock();
1451 UnhashedControlBlockRange.second = Stream.GetCurrentBitNo() >> 3;
1452}
1453
1454/// Write the control block.
1455void ASTWriter::WriteControlBlock(Preprocessor &PP, StringRef isysroot) {
1456 using namespace llvm;
1457
1458 SourceManager &SourceMgr = PP.getSourceManager();
1459 FileManager &FileMgr = PP.getFileManager();
1460
1461 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1462 RecordData Record;
1463
1464 // Metadata
1465 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1466 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1467 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1468 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1469 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1470 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1471 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1472 // Standard C++ module
1473 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1474 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1475 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1476 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1477 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1478 assert((!WritingModule || isysroot.empty()) &&
1479 "writing module as a relocatable PCH?");
1480 {
1481 RecordData::value_type Record[] = {METADATA,
1484 CLANG_VERSION_MAJOR,
1485 CLANG_VERSION_MINOR,
1486 !isysroot.empty(),
1487 isWritingStdCXXNamedModules(),
1488 IncludeTimestamps,
1489 ASTHasCompilerErrors};
1490 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1492 }
1493
1494 if (WritingModule) {
1495 // Module name
1496 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1497 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1498 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1499 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1500 RecordData::value_type Record[] = {MODULE_NAME};
1501 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1502
1503 auto BaseDir = [&]() -> std::optional<SmallString<128>> {
1505 // Use the current working directory as the base path for all inputs.
1506 auto CWD = FileMgr.getOptionalDirectoryRef(".");
1507 return CWD->getName();
1508 }
1509 if (WritingModule->Directory) {
1510 return WritingModule->Directory->getName();
1511 }
1512 return std::nullopt;
1513 }();
1514 if (BaseDir) {
1515 FileMgr.makeAbsolutePath(*BaseDir, /*Canonicalize=*/true);
1516
1517 // If the home of the module is the current working directory, then we
1518 // want to pick up the cwd of the build process loading the module, not
1519 // our cwd, when we load this module.
1521 (!PP.getHeaderSearchInfo()
1524 WritingModule->Directory->getName() != ".")) {
1525 // Module directory.
1526 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1527 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1528 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1529 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1530
1531 RecordData::value_type Record[] = {MODULE_DIRECTORY};
1532 Stream.EmitRecordWithBlob(AbbrevCode, Record, *BaseDir);
1533 }
1534
1535 // Write out all other paths relative to the base directory if possible.
1536 BaseDirectory.assign(BaseDir->begin(), BaseDir->end());
1537 }
1538 } else if (!isysroot.empty()) {
1539 // Write out paths relative to the sysroot if possible.
1540 SmallString<128> CleanedSysroot(isysroot);
1541 PP.getFileManager().makeAbsolutePath(CleanedSysroot, /*Canonicalize=*/true);
1542 BaseDirectory.assign(CleanedSysroot.begin(), CleanedSysroot.end());
1544 // Reuse relocatable PCH prefix stripping, but leave the reader's base
1545 // directory empty so relative paths resolve against the consumer's cwd.
1546 // GeneratePCHAction rejects combining this with -relocatable-pch.
1547 SmallString<128> BaseDir(".");
1548 FileMgr.makeAbsolutePath(BaseDir, /*Canonicalize=*/true);
1549 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1550 }
1551
1552 // Module map file
1553 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1554 Record.clear();
1555
1556 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1557 AddPath(WritingModule->PresumedModuleMapFile.empty()
1558 ? Map.getModuleMapFileForUniquing(WritingModule)
1559 ->getNameAsRequested()
1560 : StringRef(WritingModule->PresumedModuleMapFile),
1561 Record);
1562
1563 // Additional module map files.
1564 if (auto *AdditionalModMaps =
1565 Map.getAdditionalModuleMapFiles(WritingModule)) {
1566 Record.push_back(AdditionalModMaps->size());
1567 SmallVector<FileEntryRef, 1> ModMaps(AdditionalModMaps->begin(),
1568 AdditionalModMaps->end());
1569 llvm::sort(ModMaps, [](FileEntryRef A, FileEntryRef B) {
1570 return A.getName() < B.getName();
1571 });
1572 for (FileEntryRef F : ModMaps)
1573 AddPath(F.getName(), Record);
1574 } else {
1575 Record.push_back(0);
1576 }
1577
1578 Stream.EmitRecord(MODULE_MAP_FILE, Record);
1579 }
1580
1581 if (WritingModule && !WritingModule->getDirectoryDependencies().empty()) {
1582 Record.clear();
1583 // Sort so that dependencies are reported in a stable order.
1584 SmallVector<StringRef> Dirs(WritingModule->getDirectoryDependencies());
1585 llvm::sort(Dirs);
1586 Record.push_back(Dirs.size());
1587 for (StringRef Dir : Dirs)
1588 AddPath(Dir, Record);
1589 Stream.EmitRecord(MODULE_DIRECTORY_DEPENDENCIES, Record);
1590 }
1591
1592 // Imports
1593 if (Chain) {
1594 const auto &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1595 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1596 Abbrev->Add(BitCodeAbbrevOp(IMPORT));
1597 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Kind
1598 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ImportLoc
1599 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Module name len
1600 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Standard C++ mod
1601 Abbrev->Add(
1602 BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // C++20/prebuilt HU
1603 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File size
1604 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File timestamp
1605 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File name raw kind
1606 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File name len
1607 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Strings
1608 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1609
1610 SmallString<128> Blob;
1611
1612 for (ModuleFile &M : Chain->getModuleManager()) {
1613 // Skip modules that weren't directly imported.
1614 if (!M.isDirectlyImported())
1615 continue;
1616
1617 Record.clear();
1618 Blob.clear();
1619
1620 Record.push_back(IMPORT);
1621 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1622 AddSourceLocation(M.ImportLoc, Record);
1623 AddStringBlob(M.ModuleName, Record, Blob);
1624 Record.push_back(M.StandardCXXModule);
1625
1626 // We don't want to hard code file information for C++20 Modules
1627 // (including explicitly mapped header units).
1628 const Module *ImportedModule =
1629 PP.getHeaderSearchInfo().getModuleMap().findModule(M.ModuleName);
1630 bool IsPrebuiltHeaderUnit =
1631 ImportedModule && ImportedModule->isHeaderUnit() &&
1632 M.Kind == MK_PrebuiltModule &&
1633 HSOpts.PrebuiltModuleFiles.count(M.ModuleName);
1634
1635 bool IsCXX20ModuleOrPrebuiltHeaderUnit =
1636 M.StandardCXXModule || IsPrebuiltHeaderUnit;
1637 Record.push_back(IsCXX20ModuleOrPrebuiltHeaderUnit);
1638
1639 if (IsCXX20ModuleOrPrebuiltHeaderUnit) {
1640 Record.push_back(0);
1641 Record.push_back(0);
1642 Record.push_back(0);
1643 Record.push_back(0);
1644 } else {
1645 // If we have calculated signature, there is no need to store
1646 // the size or timestamp.
1647 Record.push_back(M.Signature ? 0 : M.Size);
1648 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.ModTime));
1649
1650 Record.push_back(M.FileName.getRawKind());
1651
1652 llvm::append_range(Blob, M.Signature);
1653
1654 AddPathBlob(M.FileName, Record, Blob);
1655 }
1656
1657 Stream.EmitRecordWithBlob(AbbrevCode, Record, Blob);
1658 }
1659 }
1660
1661 // Write the options block.
1662 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1663
1664 // Language options.
1665 Record.clear();
1666 const LangOptions &LangOpts = PP.getLangOpts();
1667 Record.push_back(static_cast<unsigned>(LangOpts.LangStd));
1668 const uint64_t LanguageOptionValues[] = {
1669#define LANGOPT(Name, Bits, Default, Compatibility, Description) LangOpts.Name,
1670#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
1671 static_cast<unsigned>(LangOpts.get##Name()),
1672#include "clang/Basic/LangOptions.def"
1673#define SANITIZER(NAME, ID) LangOpts.Sanitize.has(SanitizerKind::ID),
1674#include "clang/Basic/Sanitizers.def"
1675 };
1676 llvm::append_range(Record, LanguageOptionValues);
1677
1678 Record.push_back(LangOpts.ModuleFeatures.size());
1679 for (StringRef Feature : LangOpts.ModuleFeatures)
1680 AddString(Feature, Record);
1681
1682 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1683 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1684
1685 AddString(LangOpts.CurrentModule, Record);
1686
1687 // Comment options.
1688 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1689 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1690 AddString(I, Record);
1691 }
1692 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1693
1694 // OpenMP offloading options.
1695 Record.push_back(LangOpts.OMPTargetTriples.size());
1696 for (auto &T : LangOpts.OMPTargetTriples)
1697 AddString(T.getTriple(), Record);
1698
1699 AddString(LangOpts.OMPHostIRFile, Record);
1700
1701 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1702
1703 // Codegen options.
1704 // FIXME: Replace with C++20 `using enum CodeGenOptions::CompatibilityKind`.
1705 using CK = CodeGenOptions::CompatibilityKind;
1706 Record.clear();
1707 const CodeGenOptions &CGOpts = getCodeGenOpts();
1708#define CODEGENOPT(Name, Bits, Default, Compatibility) \
1709 if constexpr (CK::Compatibility != CK::Benign) \
1710 Record.push_back(static_cast<unsigned>(CGOpts.Name));
1711#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
1712 if constexpr (CK::Compatibility != CK::Benign) \
1713 Record.push_back(static_cast<unsigned>(CGOpts.get##Name()));
1714#define DEBUGOPT(Name, Bits, Default, Compatibility)
1715#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
1716#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
1717#include "clang/Basic/CodeGenOptions.def"
1718 Stream.EmitRecord(CODEGEN_OPTIONS, Record);
1719
1720 // Target options.
1721 Record.clear();
1722 const TargetInfo &Target = PP.getTargetInfo();
1723 const TargetOptions &TargetOpts = Target.getTargetOpts();
1724 AddString(TargetOpts.Triple, Record);
1725 AddString(TargetOpts.CPU, Record);
1726 AddString(TargetOpts.TuneCPU, Record);
1727 AddString(TargetOpts.ABI, Record);
1728 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1729 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1730 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1731 }
1732 Record.push_back(TargetOpts.Features.size());
1733 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1734 AddString(TargetOpts.Features[I], Record);
1735 }
1736 Stream.EmitRecord(TARGET_OPTIONS, Record);
1737
1738 // File system options.
1739 Record.clear();
1740 const FileSystemOptions &FSOpts = FileMgr.getFileSystemOpts();
1741 AddString(FSOpts.WorkingDir, Record);
1742 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1743
1744 // Header search options.
1745 Record.clear();
1746 const HeaderSearchOptions &HSOpts =
1748
1749 StringRef HSOpts_ModuleCachePath =
1751
1752 AddString(HSOpts.Sysroot, Record);
1753 AddString(HSOpts.ResourceDir, Record);
1754 AddString(HSOpts_ModuleCachePath, Record);
1755 AddString(HSOpts.ModuleUserBuildPath, Record);
1756 Record.push_back(HSOpts.DisableModuleHash);
1757 Record.push_back(HSOpts.ImplicitModuleMaps);
1758 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1759 Record.push_back(HSOpts.EnablePrebuiltImplicitModules);
1760 Record.push_back(HSOpts.UseBuiltinIncludes);
1761 Record.push_back(HSOpts.UseStandardSystemIncludes);
1762 Record.push_back(HSOpts.UseStandardCXXIncludes);
1763 Record.push_back(HSOpts.UseLibcxx);
1764 AddString(PP.getHeaderSearchInfo().getContextHash(), Record);
1765 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1766
1767 // Preprocessor options.
1768 Record.clear();
1769 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1770
1771 // If we're building an implicit module with a context hash, the importer is
1772 // guaranteed to have the same macros defined on the command line. Skip
1773 // writing them.
1774 bool SkipMacros = BuildingImplicitModule && !HSOpts.DisableModuleHash;
1775 bool WriteMacros = !SkipMacros;
1776 Record.push_back(WriteMacros);
1777 if (WriteMacros) {
1778 // Macro definitions.
1779 Record.push_back(PPOpts.Macros.size());
1780 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1781 AddString(PPOpts.Macros[I].first, Record);
1782 Record.push_back(PPOpts.Macros[I].second);
1783 }
1784 }
1785
1786 // Includes
1787 Record.push_back(PPOpts.Includes.size());
1788 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1789 AddString(PPOpts.Includes[I], Record);
1790
1791 // Macro includes
1792 Record.push_back(PPOpts.MacroIncludes.size());
1793 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1794 AddString(PPOpts.MacroIncludes[I], Record);
1795
1796 Record.push_back(PPOpts.UsePredefines);
1797 // Detailed record is important since it is used for the module cache hash.
1798 Record.push_back(PPOpts.DetailedRecord);
1799
1800 // FIXME: Using `AddString` to record `ImplicitPCHInclude` does not handle
1801 // relocatable files. We probably should call
1802 // `AddPath(PPOpts.ImplicitPCHInclude, Record)` to properly support chained
1803 // relocatable PCHs.
1804 AddString(PPOpts.ImplicitPCHInclude, Record);
1805 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1806 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1807
1808 // Leave the options block.
1809 Stream.ExitBlock();
1810
1811 // Original file name and file ID
1812 if (auto MainFile =
1813 SourceMgr.getFileEntryRefForID(SourceMgr.getMainFileID())) {
1814 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1815 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1816 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1817 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1818 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1819
1820 Record.clear();
1821 Record.push_back(ORIGINAL_FILE);
1822 AddFileID(SourceMgr.getMainFileID(), Record);
1823 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1824 }
1825
1826 Record.clear();
1827 AddFileID(SourceMgr.getMainFileID(), Record);
1828 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1829
1830 WriteInputFiles(SourceMgr);
1831 Stream.ExitBlock();
1832}
1833
1834namespace {
1835
1836/// An input file.
1837struct InputFileEntry {
1838 FileEntryRef File;
1839 bool IsSystemFile;
1840 bool IsTransient;
1841 bool BufferOverridden;
1842 bool IsTopLevel;
1843 bool IsModuleMap;
1844 uint32_t ContentHash[2];
1845
1846 InputFileEntry(FileEntryRef File) : File(File) {}
1847
1848 void trySetContentHash(
1849 Preprocessor &PP,
1850 llvm::function_ref<std::optional<llvm::MemoryBufferRef>()> GetMemBuff) {
1851 ContentHash[0] = 0;
1852 ContentHash[1] = 0;
1853
1854 if (!PP.getHeaderSearchInfo()
1857 return;
1858
1859 auto MemBuff = GetMemBuff();
1860 if (!MemBuff) {
1861 PP.Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1862 << File.getName();
1863 return;
1864 }
1865
1866 uint64_t Hash = xxh3_64bits(MemBuff->getBuffer());
1867 ContentHash[0] = uint32_t(Hash);
1868 ContentHash[1] = uint32_t(Hash >> 32);
1869 }
1870};
1871
1872} // namespace
1873
1874SourceLocation ASTWriter::getAffectingIncludeLoc(const SourceManager &SourceMgr,
1875 const SrcMgr::FileInfo &File) {
1876 SourceLocation IncludeLoc = File.getIncludeLoc();
1877 if (IncludeLoc.isValid()) {
1878 FileID IncludeFID = SourceMgr.getFileID(IncludeLoc);
1879 assert(IncludeFID.isValid() && "IncludeLoc in invalid file");
1880 if (!IsSLocAffecting[IncludeFID.ID])
1881 IncludeLoc = SourceLocation();
1882 }
1883 return IncludeLoc;
1884}
1885
1886void ASTWriter::WriteInputFiles(SourceManager &SourceMgr) {
1887 using namespace llvm;
1888
1889 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1890
1891 // Create input-file abbreviation.
1892 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1893 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1894 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1895 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1896 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1897 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1898 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1899 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Top-level
1900 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1901 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Name as req. len
1902 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name as req. + name
1903 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1904
1905 // Create input file hash abbreviation.
1906 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1907 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1908 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1909 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1910 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1911
1912 uint64_t InputFilesOffsetBase = Stream.GetCurrentBitNo();
1913
1914 // Get all ContentCache objects for files.
1915 std::vector<InputFileEntry> UserFiles;
1916 std::vector<InputFileEntry> SystemFiles;
1917 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1918 // Get this source location entry.
1919 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1920 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1921
1922 // We only care about file entries that were not overridden.
1923 if (!SLoc->isFile())
1924 continue;
1925 const SrcMgr::FileInfo &File = SLoc->getFile();
1926 const SrcMgr::ContentCache *Cache = &File.getContentCache();
1927 // Named pipes, including stdin, are serialized as buffers rather than
1928 // files, since their contents can differ between AST files.
1929 if (!Cache->OrigEntry || Cache->OrigEntry->isNamedPipe())
1930 continue;
1931
1932 // Do not emit input files that do not affect current module.
1933 if (!IsSLocFileEntryAffecting[I])
1934 continue;
1935
1936 InputFileEntry Entry(*Cache->OrigEntry);
1937 Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
1938 Entry.IsTransient = Cache->IsTransient;
1939 Entry.BufferOverridden = Cache->BufferOverridden;
1940
1941 FileID IncludeFileID = SourceMgr.getFileID(File.getIncludeLoc());
1942 Entry.IsTopLevel = IncludeFileID.isInvalid() || IncludeFileID.ID < 0 ||
1943 !IsSLocFileEntryAffecting[IncludeFileID.ID];
1944 Entry.IsModuleMap = isModuleMap(File.getFileCharacteristic());
1945
1946 Entry.trySetContentHash(*PP, [&] { return Cache->getBufferIfLoaded(); });
1947
1948 if (Entry.IsSystemFile)
1949 SystemFiles.push_back(Entry);
1950 else
1951 UserFiles.push_back(Entry);
1952 }
1953
1954 // FIXME: Make providing input files not in the SourceManager more flexible.
1955 // The SDKSettings.json file is necessary for correct evaluation of
1956 // availability annotations.
1957 StringRef Sysroot = PP->getHeaderSearchInfo().getHeaderSearchOpts().Sysroot;
1958 if (!Sysroot.empty()) {
1959 SmallString<128> SDKSettingsJSON = Sysroot;
1960 llvm::sys::path::append(SDKSettingsJSON, "SDKSettings.json");
1961 FileManager &FM = PP->getFileManager();
1962 if (auto FE = FM.getOptionalFileRef(SDKSettingsJSON)) {
1963 InputFileEntry Entry(*FE);
1964 Entry.IsSystemFile = true;
1965 Entry.IsTransient = false;
1966 Entry.BufferOverridden = false;
1967 Entry.IsTopLevel = true;
1968 Entry.IsModuleMap = false;
1969 std::unique_ptr<MemoryBuffer> MB;
1970 Entry.trySetContentHash(*PP, [&]() -> std::optional<MemoryBufferRef> {
1971 if (auto MBOrErr = FM.getBufferForFile(Entry.File)) {
1972 MB = std::move(*MBOrErr);
1973 return MB->getMemBufferRef();
1974 }
1975 return std::nullopt;
1976 });
1977 SystemFiles.push_back(Entry);
1978 }
1979 }
1980
1981 // User files go at the front, system files at the back.
1982 auto SortedFiles = llvm::concat<InputFileEntry>(std::move(UserFiles),
1983 std::move(SystemFiles));
1984
1985 unsigned UserFilesNum = 0;
1986 // Write out all of the input files.
1987 std::vector<uint64_t> InputFileOffsets;
1988 for (const auto &Entry : SortedFiles) {
1989 uint32_t &InputFileID = InputFileIDs[Entry.File];
1990 if (InputFileID != 0)
1991 continue; // already recorded this file.
1992
1993 // Record this entry's offset.
1994 InputFileOffsets.push_back(Stream.GetCurrentBitNo() - InputFilesOffsetBase);
1995
1996 InputFileID = InputFileOffsets.size();
1997
1998 if (!Entry.IsSystemFile)
1999 ++UserFilesNum;
2000
2001 // Emit size/modification time for this file.
2002 // And whether this file was overridden.
2003 {
2004 SmallString<128> NameAsRequested = Entry.File.getNameAsRequested();
2005 SmallString<128> Name = Entry.File.getName();
2006
2007 PreparePathForOutput(NameAsRequested);
2008 PreparePathForOutput(Name);
2009
2010 if (Name == NameAsRequested)
2011 Name.clear();
2012
2013 RecordData::value_type Record[] = {
2014 INPUT_FILE,
2015 InputFileOffsets.size(),
2016 (uint64_t)Entry.File.getSize(),
2017 (uint64_t)getTimestampForOutput(Entry.File.getModificationTime()),
2018 Entry.BufferOverridden,
2019 Entry.IsTransient,
2020 Entry.IsTopLevel,
2021 Entry.IsModuleMap,
2022 NameAsRequested.size()};
2023
2024 Stream.EmitRecordWithBlob(IFAbbrevCode, Record,
2025 (NameAsRequested + Name).str());
2026 }
2027
2028 // Emit content hash for this file.
2029 {
2030 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
2031 Entry.ContentHash[1]};
2032 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
2033 }
2034 }
2035
2036 Stream.ExitBlock();
2037
2038 // Create input file offsets abbreviation.
2039 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
2040 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
2041 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
2042 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
2043 // input files
2044 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
2045 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
2046
2047 // Write input file offsets.
2048 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
2049 InputFileOffsets.size(), UserFilesNum};
2050 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
2051}
2052
2053//===----------------------------------------------------------------------===//
2054// Source Manager Serialization
2055//===----------------------------------------------------------------------===//
2056
2057/// Create an abbreviation for the SLocEntry that refers to a
2058/// file.
2059static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
2060 using namespace llvm;
2061
2062 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2063 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
2064 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
2065 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
2066 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
2067 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
2068 // FileEntry fields.
2069 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
2070 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
2071 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
2072 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
2073 return Stream.EmitAbbrev(std::move(Abbrev));
2074}
2075
2076/// Create an abbreviation for the SLocEntry that refers to a
2077/// buffer.
2078static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
2079 using namespace llvm;
2080
2081 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2082 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
2083 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
2084 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
2085 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
2086 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
2087 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
2088 return Stream.EmitAbbrev(std::move(Abbrev));
2089}
2090
2091/// Create an abbreviation for the SLocEntry that refers to a
2092/// buffer's blob.
2093static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
2094 bool Compressed) {
2095 using namespace llvm;
2096
2097 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2098 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
2100 if (Compressed)
2101 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
2102 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
2103 return Stream.EmitAbbrev(std::move(Abbrev));
2104}
2105
2106/// Create an abbreviation for the SLocEntry that refers to a macro
2107/// expansion.
2108static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
2109 using namespace llvm;
2110
2111 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2112 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
2113 // The static ordering of the four fields below is critical to getting good
2114 // compression from the delta encoding. Specifically:
2115 // Offset -> End location -> Start location -> Spelling location.
2116 // Ordered this way, the delta between Offset and End location is usually
2117 // small, and so is the delta between End location and Start location.
2118 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
2119 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // End location
2120 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Start location
2121 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Spelling location
2122 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
2123 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
2124 return Stream.EmitAbbrev(std::move(Abbrev));
2125}
2126
2127/// Emit key length and data length as ULEB-encoded data, and return them as a
2128/// pair.
2129static std::pair<unsigned, unsigned>
2130emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out) {
2131 llvm::encodeULEB128(KeyLen, Out);
2132 llvm::encodeULEB128(DataLen, Out);
2133 return std::make_pair(KeyLen, DataLen);
2134}
2135
2136namespace {
2137
2138 // Trait used for the on-disk hash table of header search information.
2139 class HeaderFileInfoTrait {
2140 ASTWriter &Writer;
2141
2142 public:
2143 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
2144
2145 struct key_type {
2146 StringRef Filename;
2147 off_t Size;
2148 time_t ModTime;
2149 };
2150 using key_type_ref = const key_type &;
2151
2152 using UnresolvedModule =
2153 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
2154
2155 struct data_type {
2156 data_type(const HeaderFileInfo &HFI, bool AlreadyIncluded,
2157 ArrayRef<ModuleMap::KnownHeader> KnownHeaders,
2158 UnresolvedModule Unresolved)
2159 : HFI(HFI), AlreadyIncluded(AlreadyIncluded),
2160 KnownHeaders(KnownHeaders), Unresolved(Unresolved) {}
2161
2162 HeaderFileInfo HFI;
2163 bool AlreadyIncluded;
2164 SmallVector<ModuleMap::KnownHeader, 1> KnownHeaders;
2165 UnresolvedModule Unresolved;
2166 };
2167 using data_type_ref = const data_type &;
2168
2169 using hash_value_type = unsigned;
2170 using offset_type = unsigned;
2171
2172 hash_value_type ComputeHash(key_type_ref key) {
2173 // The hash is based only on size/time of the file, so that the reader can
2174 // match even when symlinking or excess path elements ("foo/../", "../")
2175 // change the form of the name. However, complete path is still the key.
2176 uint8_t buf[sizeof(key.Size) + sizeof(key.ModTime)];
2177 memcpy(buf, &key.Size, sizeof(key.Size));
2178 memcpy(buf + sizeof(key.Size), &key.ModTime, sizeof(key.ModTime));
2179 return llvm::xxh3_64bits(buf);
2180 }
2181
2182 std::pair<unsigned, unsigned>
2183 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
2184 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
2185 unsigned DataLen = 1 + sizeof(IdentifierID);
2186 for (auto ModInfo : Data.KnownHeaders)
2187 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
2188 DataLen += 4;
2189 if (Data.Unresolved.getPointer())
2190 DataLen += 4;
2191 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
2192 }
2193
2194 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
2195 using namespace llvm::support;
2196
2197 endian::Writer LE(Out, llvm::endianness::little);
2198 LE.write<uint64_t>(key.Size);
2199 KeyLen -= 8;
2200 LE.write<uint64_t>(key.ModTime);
2201 KeyLen -= 8;
2202 Out.write(key.Filename.data(), KeyLen);
2203 }
2204
2205 void EmitData(raw_ostream &Out, key_type_ref key,
2206 data_type_ref Data, unsigned DataLen) {
2207 using namespace llvm::support;
2208
2209 endian::Writer LE(Out, llvm::endianness::little);
2210 uint64_t Start = Out.tell(); (void)Start;
2211
2212 unsigned char Flags = (Data.AlreadyIncluded << 6)
2213 | (Data.HFI.isImport << 5)
2214 | (Writer.isWritingStdCXXNamedModules() ? 0 :
2215 Data.HFI.isPragmaOnce << 4)
2216 | (Data.HFI.DirInfo << 1);
2217 LE.write<uint8_t>(Flags);
2218
2219 if (Data.HFI.LazyControllingMacro.isID())
2220 LE.write<IdentifierID>(Data.HFI.LazyControllingMacro.getID());
2221 else
2222 LE.write<IdentifierID>(
2223 Writer.getIdentifierRef(Data.HFI.LazyControllingMacro.getPtr()));
2224
2225 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
2226 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
2227 uint32_t Value = (ModID << 3) | (unsigned)Role;
2228 assert((Value >> 3) == ModID && "overflow in header module info");
2229 LE.write<uint32_t>(Value);
2230 }
2231 };
2232
2233 for (auto ModInfo : Data.KnownHeaders)
2234 EmitModule(ModInfo.getModule(), ModInfo.getRole());
2235 if (Data.Unresolved.getPointer())
2236 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
2237
2238 assert(Out.tell() - Start == DataLen && "Wrong data length");
2239 }
2240 };
2241
2242} // namespace
2243
2244/// Write the header search block for the list of files that
2245///
2246/// \param HS The header search structure to save.
2247void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
2248 HeaderFileInfoTrait GeneratorTrait(*this);
2249 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
2250 SmallVector<const char *, 4> SavedStrings;
2251 unsigned NumHeaderSearchEntries = 0;
2252
2253 // Find all unresolved headers for the current module. We generally will
2254 // have resolved them before we get here, but not necessarily: we might be
2255 // compiling a preprocessed module, where there is no requirement for the
2256 // original files to exist any more.
2257 const HeaderFileInfo Empty; // So we can take a reference.
2258 if (WritingModule) {
2259 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2260 while (!Worklist.empty()) {
2261 Module *M = Worklist.pop_back_val();
2262 // We don't care about headers in unimportable submodules.
2263 if (M->isUnimportable())
2264 continue;
2265
2266 // Map to disk files where possible, to pick up any missing stat
2267 // information. This also means we don't need to check the unresolved
2268 // headers list when emitting resolved headers in the first loop below.
2269 // FIXME: It'd be preferable to avoid doing this if we were given
2270 // sufficient stat information in the module map.
2271 HS.getModuleMap().resolveHeaderDirectives(M, /*File=*/std::nullopt);
2272
2273 // If the file didn't exist, we can still create a module if we were given
2274 // enough information in the module map.
2275 for (const auto &U : M->MissingHeaders) {
2276 // Check that we were given enough information to build a module
2277 // without this file existing on disk.
2278 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
2279 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2280 << WritingModule->getFullModuleName() << U.Size.has_value()
2281 << U.FileName;
2282 continue;
2283 }
2284
2285 // Form the effective relative pathname for the file.
2286 SmallString<128> Filename(M->Directory->getName());
2287 llvm::sys::path::append(Filename, U.FileName);
2288 PreparePathForOutput(Filename);
2289
2290 StringRef FilenameDup = strdup(Filename.c_str());
2291 SavedStrings.push_back(FilenameDup.data());
2292
2293 HeaderFileInfoTrait::key_type Key = {
2294 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0};
2295 HeaderFileInfoTrait::data_type Data = {
2296 Empty, false, {}, {M, ModuleMap::headerKindToRole(U.Kind)}};
2297 // FIXME: Deal with cases where there are multiple unresolved header
2298 // directives in different submodules for the same header.
2299 Generator.insert(Key, Data, GeneratorTrait);
2300 ++NumHeaderSearchEntries;
2301 }
2302 auto SubmodulesRange = M->submodules();
2303 Worklist.append(SubmodulesRange.begin(), SubmodulesRange.end());
2304 }
2305 }
2306
2308 [&](FileEntryRef File, const HeaderFileInfo &HFI) {
2310 return; // Header file info is tracked by the owning module file.
2312 return; // Header file info is tracked by the including module file.
2313
2314 // Massage the file path into an appropriate form.
2315 StringRef Filename = File.getName();
2316 SmallString<128> FilenameTmp(Filename);
2317 if (PreparePathForOutput(FilenameTmp)) {
2318 // If we performed any translation on the file name at all, we need to
2319 // save this string, since the generator will refer to it later.
2320 Filename = StringRef(strdup(FilenameTmp.c_str()));
2321 SavedStrings.push_back(Filename.data());
2322 }
2323
2324 bool Included = HFI.IsLocallyIncluded || PP->alreadyIncluded(File);
2325
2326 HeaderFileInfoTrait::key_type Key = {
2327 Filename, File.getSize(),
2328 getTimestampForOutput(File.getModificationTime())};
2329 HeaderFileInfoTrait::data_type Data = {
2330 HFI,
2331 Included,
2333 {}};
2334 Generator.insert(Key, Data, GeneratorTrait);
2335 ++NumHeaderSearchEntries;
2336 });
2337
2338 // Create the on-disk hash table in a buffer.
2339 SmallString<4096> TableData;
2340 uint32_t BucketOffset;
2341 {
2342 using namespace llvm::support;
2343
2344 llvm::raw_svector_ostream Out(TableData);
2345 // Make sure that no bucket is at offset 0
2346 endian::write<uint32_t>(Out, 0, llvm::endianness::little);
2347 BucketOffset = Generator.Emit(Out, GeneratorTrait);
2348 }
2349
2350 // Create a blob abbreviation
2351 using namespace llvm;
2352
2353 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2354 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2355 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2356 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2357 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2358 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2359 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2360
2361 // Write the header search table
2362 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2363 NumHeaderSearchEntries, TableData.size()};
2364 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
2365
2366 // Free all of the strings we had to duplicate.
2367 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
2368 free(const_cast<char *>(SavedStrings[I]));
2369}
2370
2371static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2372 unsigned SLocBufferBlobCompressedAbbrv,
2373 unsigned SLocBufferBlobAbbrv) {
2374 using RecordDataType = ASTWriter::RecordData::value_type;
2375
2376 // Compress the buffer if possible. We expect that almost all PCM
2377 // consumers will not want its contents.
2378 SmallVector<uint8_t, 0> CompressedBuffer;
2379 if (llvm::compression::zstd::isAvailable()) {
2380 llvm::compression::zstd::compress(
2381 llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer, 9);
2382 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2383 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2384 llvm::toStringRef(CompressedBuffer));
2385 return;
2386 }
2387 if (llvm::compression::zlib::isAvailable()) {
2388 llvm::compression::zlib::compress(
2389 llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer);
2390 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2391 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2392 llvm::toStringRef(CompressedBuffer));
2393 return;
2394 }
2395
2396 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2397 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2398}
2399
2400/// Writes the block containing the serialized form of the
2401/// source manager.
2402///
2403/// TODO: We should probably use an on-disk hash table (stored in a
2404/// blob), indexed based on the file name, so that we only create
2405/// entries for files that we actually need. In the common case (no
2406/// errors), we probably won't have to create file entries for any of
2407/// the files in the AST.
2408void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr) {
2409 RecordData Record;
2410
2411 // Enter the source manager block.
2412 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2413 const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo();
2414
2415 // Abbreviations for the various kinds of source-location entries.
2416 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2417 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2418 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2419 unsigned SLocBufferBlobCompressedAbbrv =
2420 CreateSLocBufferBlobAbbrev(Stream, true);
2421 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2422
2423 // Write out the source location entry table. We skip the first
2424 // entry, which is always the same dummy entry.
2425 std::vector<uint32_t> SLocEntryOffsets;
2426 uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
2427 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2428 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2429 I != N; ++I) {
2430 // Get this source location entry.
2431 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2432 FileID FID = FileID::get(I);
2433 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2434
2435 // Record the offset of this source-location entry.
2436 uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
2437 assert((Offset >> 32) == 0 && "SLocEntry offset too large");
2438
2439 // Figure out which record code to use.
2440 unsigned Code;
2441 if (SLoc->isFile()) {
2442 const SrcMgr::ContentCache *Cache = &SLoc->getFile().getContentCache();
2443 if (Cache->OrigEntry && !Cache->OrigEntry->isNamedPipe()) {
2444 Code = SM_SLOC_FILE_ENTRY;
2445 } else
2446 Code = SM_SLOC_BUFFER_ENTRY;
2447 } else
2449 Record.clear();
2450 Record.push_back(Code);
2451
2452 if (SLoc->isFile()) {
2453 const SrcMgr::FileInfo &File = SLoc->getFile();
2454 const SrcMgr::ContentCache *Content = &File.getContentCache();
2455 // Do not emit files that were not listed as inputs.
2456 if (!IsSLocAffecting[I])
2457 continue;
2458 SLocEntryOffsets.push_back(Offset);
2459 Record.push_back(getEntryOffset(*SLoc));
2460 AddSourceLocation(getAffectingIncludeLoc(SourceMgr, File), Record);
2461 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2462 Record.push_back(File.hasLineDirectives());
2463
2464 bool EmitBlob = false;
2465 if (Code == SM_SLOC_FILE_ENTRY) {
2466 assert(Content->OrigEntry == Content->ContentsEntry &&
2467 "Writing to AST an overridden file is not supported");
2468
2469 // The source location entry is a file. Emit input file ID.
2470 assert(InputFileIDs[*Content->OrigEntry] != 0 && "Missed file entry");
2471 Record.push_back(InputFileIDs[*Content->OrigEntry]);
2472
2473 Record.push_back(getAdjustedNumCreatedFIDs(FID));
2474
2475 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2476 if (FDI != FileDeclIDs.end()) {
2477 Record.push_back(FDI->second->FirstDeclIndex);
2478 Record.push_back(FDI->second->DeclIDs.size());
2479 } else {
2480 Record.push_back(0);
2481 Record.push_back(0);
2482 }
2483
2484 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2485
2486 if (Content->BufferOverridden || Content->IsTransient)
2487 EmitBlob = true;
2488 } else {
2489 // The source location entry is a buffer. The blob associated
2490 // with this entry contains the contents of the buffer.
2491
2492 // We add one to the size so that we capture the trailing NULL
2493 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2494 // the reader side).
2495 std::optional<llvm::MemoryBufferRef> Buffer = Content->getBufferOrNone(
2496 SourceMgr.getDiagnostics(), SourceMgr.getFileManager());
2497 StringRef Name = Buffer ? Buffer->getBufferIdentifier() : "";
2498 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2499 StringRef(Name.data(), Name.size() + 1));
2500 EmitBlob = true;
2501 }
2502
2503 if (EmitBlob) {
2504 // Include the implicit terminating null character in the on-disk buffer
2505 // if we're writing it uncompressed.
2506 std::optional<llvm::MemoryBufferRef> Buffer = Content->getBufferOrNone(
2507 SourceMgr.getDiagnostics(), SourceMgr.getFileManager());
2508 if (!Buffer)
2509 Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", "");
2510 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2511 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2512 SLocBufferBlobAbbrv);
2513 }
2514 } else {
2515 // The source location entry is a macro expansion.
2516 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2517 SLocEntryOffsets.push_back(Offset);
2518 auto Chain = EmitEntryOffset(*SLoc, Record);
2519
2520 // The chain is stateful. Encode happens in the order specified in
2521 // CreateSLocExpansionAbbrev.
2522 AddSourceLocation(Expansion.isMacroArgExpansion()
2523 ? SourceLocation()
2524 : Expansion.getExpansionLocEnd(),
2525 Record, Chain);
2526 AddSourceLocation(Expansion.getExpansionLocStart(), Record, Chain);
2527 AddSourceLocation(Expansion.getSpellingLoc(), Record, Chain);
2528
2529 Record.push_back(Expansion.isExpansionTokenRange());
2530
2531 // Compute the token length for this macro expansion.
2532 SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset();
2533 if (I + 1 != N)
2534 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2535 Record.push_back(getAdjustedOffset(NextOffset - SLoc->getOffset()) - 1);
2536 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2537 }
2538 }
2539
2540 Stream.ExitBlock();
2541
2542 if (SLocEntryOffsets.empty())
2543 return;
2544
2545 // Write the source-location offsets table into the AST block. This
2546 // table is used for lazily loading source-location information.
2547 using namespace llvm;
2548
2549 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2550 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2551 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2552 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2553 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2555 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2556 {
2557 RecordData::value_type Record[] = {
2558 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2559 getAdjustedOffset(SourceMgr.getNextLocalOffset()) - 1 /* skip dummy */,
2560 SLocEntryOffsetsBase - SourceManagerBlockOffset};
2561 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2562 bytes(SLocEntryOffsets));
2563 }
2564
2565 // Write the line table. It depends on remapping working, so it must come
2566 // after the source location offsets.
2567 if (SourceMgr.hasLineTable()) {
2568 LineTableInfo &LineTable = SourceMgr.getLineTable();
2569
2570 Record.clear();
2571
2572 // Emit the needed file names.
2573 llvm::DenseMap<int, int> FilenameMap;
2574 FilenameMap[-1] = -1; // For unspecified filenames.
2575 for (const auto &L : LineTable) {
2576 if (L.first.ID < 0)
2577 continue;
2578 for (auto &LE : L.second) {
2579 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2580 FilenameMap.size() - 1)).second)
2581 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2582 }
2583 }
2584 Record.push_back(0);
2585
2586 // Emit the line entries
2587 for (const auto &L : LineTable) {
2588 // Only emit entries for local files.
2589 if (L.first.ID < 0)
2590 continue;
2591
2592 AddFileID(L.first, Record);
2593
2594 // Emit the line entries
2595 Record.push_back(L.second.size());
2596 for (const auto &LE : L.second) {
2597 Record.push_back(LE.FileOffset);
2598 Record.push_back(LE.LineNo);
2599 Record.push_back(FilenameMap[LE.FilenameID]);
2600 Record.push_back((unsigned)LE.FileKind);
2601 Record.push_back(LE.IncludeOffset);
2602 }
2603 }
2604
2605 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2606 }
2607}
2608
2609//===----------------------------------------------------------------------===//
2610// Preprocessor Serialization
2611//===----------------------------------------------------------------------===//
2612
2613static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2614 const Preprocessor &PP) {
2615 if (MacroInfo *MI = MD->getMacroInfo())
2616 if (MI->isBuiltinMacro())
2617 return true;
2618
2619 if (IsModule) {
2620 SourceLocation Loc = MD->getLocation();
2621 if (Loc.isInvalid())
2622 return true;
2623 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2624 return true;
2625 }
2626
2627 return false;
2628}
2629
2630/// Writes the block containing the serialized form of the
2631/// preprocessor.
2632void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2633 uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2634
2635 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2636 if (PPRec)
2637 WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
2638
2639 RecordData Record;
2640 RecordData ModuleMacroRecord;
2641
2642 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2643 if (PP.getCounterValue() != 0) {
2644 RecordData::value_type Record[] = {PP.getCounterValue()};
2645 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2646 }
2647
2648 // If we have a recorded #pragma assume_nonnull, remember it so it can be
2649 // replayed when the preamble terminates into the main file.
2650 SourceLocation AssumeNonNullLoc =
2652 if (AssumeNonNullLoc.isValid()) {
2653 assert(PP.isRecordingPreamble());
2654 AddSourceLocation(AssumeNonNullLoc, Record);
2655 Stream.EmitRecord(PP_ASSUME_NONNULL_LOC, Record);
2656 Record.clear();
2657 }
2658
2659 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2660 assert(!IsModule);
2661 auto SkipInfo = PP.getPreambleSkipInfo();
2662 if (SkipInfo) {
2663 Record.push_back(true);
2664 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2665 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2666 Record.push_back(SkipInfo->FoundNonSkipPortion);
2667 Record.push_back(SkipInfo->FoundElse);
2668 AddSourceLocation(SkipInfo->ElseLoc, Record);
2669 } else {
2670 Record.push_back(false);
2671 }
2672 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2673 AddSourceLocation(Cond.IfLoc, Record);
2674 Record.push_back(Cond.WasSkipping);
2675 Record.push_back(Cond.FoundNonSkip);
2676 Record.push_back(Cond.FoundElse);
2677 }
2678 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2679 Record.clear();
2680 }
2681
2682 // Write the safe buffer opt-out region map in PP
2683 for (SourceLocation &S : PP.serializeSafeBufferOptOutMap())
2684 AddSourceLocation(S, Record);
2685 Stream.EmitRecord(PP_UNSAFE_BUFFER_USAGE, Record);
2686 Record.clear();
2687
2688 // Enter the preprocessor block.
2689 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2690
2691 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2692 // FIXME: Include a location for the use, and say which one was used.
2693 if (PP.SawDateOrTime())
2694 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2695
2696 // Loop over all the macro directives that are live at the end of the file,
2697 // emitting each to the PP section.
2698
2699 // Construct the list of identifiers with macro directives that need to be
2700 // serialized.
2701 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2702 // It is meaningless to emit macros for named modules. It only wastes times
2703 // and spaces.
2704 if (!isWritingStdCXXNamedModules())
2705 for (auto &Id : PP.getIdentifierTable())
2706 if (Id.second->hadMacroDefinition() &&
2707 (!Id.second->isFromAST() ||
2708 Id.second->hasChangedSinceDeserialization()))
2709 MacroIdentifiers.push_back(Id.second);
2710 // Sort the set of macro definitions that need to be serialized by the
2711 // name of the macro, to provide a stable ordering.
2712 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
2713
2714 // Emit the macro directives as a list and associate the offset with the
2715 // identifier they belong to.
2716 for (const IdentifierInfo *Name : MacroIdentifiers) {
2717 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2718 uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2719 assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
2720
2721 // Write out any exported module macros.
2722 bool EmittedModuleMacros = false;
2723 // C+=20 Header Units are compiled module interfaces, but they preserve
2724 // macros that are live (i.e. have a defined value) at the end of the
2725 // compilation. So when writing a header unit, we preserve only the final
2726 // value of each macro (and discard any that are undefined). Header units
2727 // do not have sub-modules (although they might import other header units).
2728 // PCH files, conversely, retain the history of each macro's define/undef
2729 // and of leaf macros in sub modules.
2730 if (IsModule && WritingModule->isHeaderUnit()) {
2731 // This is for the main TU when it is a C++20 header unit.
2732 // We preserve the final state of defined macros, and we do not emit ones
2733 // that are undefined.
2734 if (!MD || shouldIgnoreMacro(MD, IsModule, PP) ||
2736 continue;
2737 AddSourceLocation(MD->getLocation(), Record);
2738 Record.push_back(MD->getKind());
2739 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2740 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2741 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2742 Record.push_back(VisMD->isPublic());
2743 }
2744 ModuleMacroRecord.push_back(getSubmoduleID(WritingModule));
2745 AddMacroRef(MD->getMacroInfo(), Name, ModuleMacroRecord);
2746 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2747 ModuleMacroRecord.clear();
2748 EmittedModuleMacros = true;
2749 } else {
2750 // Emit the macro directives in reverse source order.
2751 for (; MD; MD = MD->getPrevious()) {
2752 // Once we hit an ignored macro, we're done: the rest of the chain
2753 // will all be ignored macros.
2754 if (shouldIgnoreMacro(MD, IsModule, PP))
2755 break;
2756 AddSourceLocation(MD->getLocation(), Record);
2757 Record.push_back(MD->getKind());
2758 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2759 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2760 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2761 Record.push_back(VisMD->isPublic());
2762 }
2763 }
2764
2765 // We write out exported module macros for PCH as well.
2766 auto Leafs = PP.getLeafModuleMacros(Name);
2767 SmallVector<ModuleMacro *, 8> Worklist(Leafs);
2768 llvm::DenseMap<ModuleMacro *, unsigned> Visits;
2769 while (!Worklist.empty()) {
2770 auto *Macro = Worklist.pop_back_val();
2771
2772 // Emit a record indicating this submodule exports this macro.
2773 ModuleMacroRecord.push_back(getSubmoduleID(Macro->getOwningModule()));
2774 AddMacroRef(Macro->getMacroInfo(), Name, ModuleMacroRecord);
2775 for (auto *M : Macro->overrides())
2776 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2777
2778 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2779 ModuleMacroRecord.clear();
2780
2781 // Enqueue overridden macros once we've visited all their ancestors.
2782 for (auto *M : Macro->overrides())
2783 if (++Visits[M] == M->getNumOverridingMacros())
2784 Worklist.push_back(M);
2785
2786 EmittedModuleMacros = true;
2787 }
2788 }
2789 if (Record.empty() && !EmittedModuleMacros)
2790 continue;
2791
2792 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2793 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2794 Record.clear();
2795 }
2796
2797 /// Offsets of each of the macros into the bitstream, indexed by
2798 /// the local macro ID
2799 ///
2800 /// For each identifier that is associated with a macro, this map
2801 /// provides the offset into the bitstream where that macro is
2802 /// defined.
2803 std::vector<uint32_t> MacroOffsets;
2804
2805 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2806 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2807 MacroInfo *MI = MacroInfosToEmit[I].MI;
2808 MacroID ID = MacroInfosToEmit[I].ID;
2809
2810 if (ID < FirstMacroID) {
2811 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2812 continue;
2813 }
2814
2815 // Record the local offset of this macro.
2816 unsigned Index = ID - FirstMacroID;
2817 if (Index >= MacroOffsets.size())
2818 MacroOffsets.resize(Index + 1);
2819
2820 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2821 assert((Offset >> 32) == 0 && "Macro offset too large");
2822 MacroOffsets[Index] = Offset;
2823
2824 AddIdentifierRef(Name, Record);
2825 AddSourceLocation(MI->getDefinitionLoc(), Record);
2826 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2827 Record.push_back(MI->isUsed());
2828 Record.push_back(MI->isUsedForHeaderGuard());
2829 Record.push_back(MI->getNumTokens());
2830 unsigned Code;
2831 if (MI->isObjectLike()) {
2832 Code = PP_MACRO_OBJECT_LIKE;
2833 } else {
2835
2836 Record.push_back(MI->isC99Varargs());
2837 Record.push_back(MI->isGNUVarargs());
2838 Record.push_back(MI->hasCommaPasting());
2839 Record.push_back(MI->getNumParams());
2840 for (const IdentifierInfo *Param : MI->params())
2841 AddIdentifierRef(Param, Record);
2842 }
2843
2844 // If we have a detailed preprocessing record, record the macro definition
2845 // ID that corresponds to this macro.
2846 if (PPRec)
2847 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2848
2849 Stream.EmitRecord(Code, Record);
2850 Record.clear();
2851
2852 // Emit the tokens array.
2853 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2854 // Note that we know that the preprocessor does not have any annotation
2855 // tokens in it because they are created by the parser, and thus can't
2856 // be in a macro definition.
2857 const Token &Tok = MI->getReplacementToken(TokNo);
2858 AddToken(Tok, Record);
2859 Stream.EmitRecord(PP_TOKEN, Record);
2860 Record.clear();
2861 }
2862 ++NumMacros;
2863 }
2864
2865 Stream.ExitBlock();
2866
2867 // Write the offsets table for macro IDs.
2868 using namespace llvm;
2869
2870 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2871 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2872 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2873 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2874 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2875
2876 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2877 {
2878 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2879 MacroOffsetsBase - ASTBlockStartOffset};
2880 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2881 }
2882}
2883
2884void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2885 uint64_t MacroOffsetsBase) {
2886 if (PPRec.local_begin() == PPRec.local_end())
2887 return;
2888
2889 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2890
2891 // Enter the preprocessor block.
2892 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2893
2894 // If the preprocessor has a preprocessing record, emit it.
2895 unsigned NumPreprocessingRecords = 0;
2896 using namespace llvm;
2897
2898 // Set up the abbreviation for
2899 unsigned InclusionAbbrev = 0;
2900 {
2901 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2902 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2903 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2904 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2905 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2906 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2907 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2908 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2909 }
2910
2911 unsigned FirstPreprocessorEntityID = NUM_PREDEF_PP_ENTITY_IDS;
2912 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2913 RecordData Record;
2914 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2915 EEnd = PPRec.local_end();
2916 E != EEnd;
2917 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2918 Record.clear();
2919
2920 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2921 assert((Offset >> 32) == 0 && "Preprocessed entity offset too large");
2922 SourceRange R = getAdjustedRange((*E)->getSourceRange());
2923 PreprocessedEntityOffsets.emplace_back(
2924 getRawSourceLocationEncoding(R.getBegin()),
2925 getRawSourceLocationEncoding(R.getEnd()), Offset);
2926
2927 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2928 // Record this macro definition's ID.
2929 MacroDefinitions[MD] = NextPreprocessorEntityID;
2930
2931 AddIdentifierRef(MD->getName(), Record);
2932 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2933 continue;
2934 }
2935
2936 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2937 Record.push_back(ME->isBuiltinMacro());
2938 if (ME->isBuiltinMacro())
2939 AddIdentifierRef(ME->getName(), Record);
2940 else
2941 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2942 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2943 continue;
2944 }
2945
2946 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2948 Record.push_back(ID->getFileName().size());
2949 Record.push_back(ID->wasInQuotes());
2950 Record.push_back(static_cast<unsigned>(ID->getKind()));
2951 Record.push_back(ID->importedModule());
2952 SmallString<64> Buffer;
2953 Buffer += ID->getFileName();
2954 // Check that the FileEntry is not null because it was not resolved and
2955 // we create a PCH even with compiler errors.
2956 if (ID->getFile())
2957 Buffer += ID->getFile()->getName();
2958 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2959 continue;
2960 }
2961
2962 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2963 }
2964 Stream.ExitBlock();
2965
2966 // Write the offsets table for the preprocessing record.
2967 if (NumPreprocessingRecords > 0) {
2968 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2969
2970 // Write the offsets table for identifier IDs.
2971 using namespace llvm;
2972
2973 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2974 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2975 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2976 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2977
2978 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS};
2979 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2980 bytes(PreprocessedEntityOffsets));
2981 }
2982
2983 // Write the skipped region table for the preprocessing record.
2984 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2985 if (SkippedRanges.size() > 0) {
2986 std::vector<PPSkippedRange> SerializedSkippedRanges;
2987 SerializedSkippedRanges.reserve(SkippedRanges.size());
2988 for (auto const &Range : SkippedRanges) {
2989 SourceRange R = getAdjustedRange(Range);
2990 SerializedSkippedRanges.emplace_back(
2991 getRawSourceLocationEncoding(R.getBegin()),
2992 getRawSourceLocationEncoding(R.getEnd()));
2993 }
2994
2995 using namespace llvm;
2996 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2997 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2998 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2999 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3000
3001 Record.clear();
3002 Record.push_back(PPD_SKIPPED_RANGES);
3003 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
3004 bytes(SerializedSkippedRanges));
3005 }
3006}
3007
3009 if (!Mod)
3010 return 0;
3011
3012 auto Known = SubmoduleIDs.find(Mod);
3013 if (Known != SubmoduleIDs.end())
3014 return Known->second;
3015
3016 auto *Top = Mod->getTopLevelModule();
3017 if (Top != WritingModule &&
3018 (getLangOpts().CompilingPCH ||
3019 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
3020 return 0;
3021
3022 return SubmoduleIDs[Mod] = NextSubmoduleID++;
3023}
3024
3025unsigned ASTWriter::getSubmoduleID(Module *Mod) {
3026 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
3027 // FIXME: This can easily happen, if we have a reference to a submodule that
3028 // did not result in us loading a module file for that submodule. For
3029 // instance, a cross-top-level-module 'conflict' declaration will hit this.
3030 // assert((ID || !Mod) &&
3031 // "asked for module ID for non-local, non-imported module");
3032 return ID;
3033}
3034
3035void ASTWriter::WriteSubmodules(Module *WritingModule, ASTContext *Context) {
3036 // Enter the submodule description block.
3037 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
3038
3039 // Write the abbreviations needed for the submodules block.
3040 using namespace llvm;
3041
3042 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3043 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
3044 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
3045 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
3046 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Kind
3047 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Definition location
3048 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Inferred allowed by
3049 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
3050 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
3051 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
3052 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
3053 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
3054 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
3055 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
3056 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
3057 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
3058 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NamedModuleHasN...
3059 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3060 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3061
3062 Abbrev = std::make_shared<BitCodeAbbrev>();
3063 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
3064 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3065 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3066
3067 Abbrev = std::make_shared<BitCodeAbbrev>();
3068 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
3069 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3070 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3071
3072 Abbrev = std::make_shared<BitCodeAbbrev>();
3073 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
3074 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3075 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3076
3077 Abbrev = std::make_shared<BitCodeAbbrev>();
3078 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
3079 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3080 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3081
3082 Abbrev = std::make_shared<BitCodeAbbrev>();
3083 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
3084 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
3085 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
3086 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3087
3088 Abbrev = std::make_shared<BitCodeAbbrev>();
3089 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
3090 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3091 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3092
3093 Abbrev = std::make_shared<BitCodeAbbrev>();
3094 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
3095 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3096 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3097
3098 Abbrev = std::make_shared<BitCodeAbbrev>();
3099 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
3100 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3101 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3102
3103 Abbrev = std::make_shared<BitCodeAbbrev>();
3104 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
3105 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3106 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3107
3108 Abbrev = std::make_shared<BitCodeAbbrev>();
3109 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
3110 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
3111 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3112 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3113
3114 Abbrev = std::make_shared<BitCodeAbbrev>();
3115 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
3116 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
3117 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3118
3119 Abbrev = std::make_shared<BitCodeAbbrev>();
3120 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
3121 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
3122 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
3123 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3124
3125 Abbrev = std::make_shared<BitCodeAbbrev>();
3126 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
3127 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
3128 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3129
3130 Abbrev = std::make_shared<BitCodeAbbrev>();
3131 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CHILD));
3132 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Child submodule ID
3133 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Child name
3134 unsigned ChildAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3135
3136 SmallVector<uint64_t> SubmoduleOffsets;
3137 uint64_t SubmoduleOffsetBase = Stream.GetCurrentBitNo();
3138
3139 unsigned TopLevelID = getSubmoduleID(WritingModule);
3140
3141 // Write all of the submodules.
3142 std::queue<Module *> Q;
3143 Q.push(WritingModule);
3144 while (!Q.empty()) {
3145 Module *Mod = Q.front();
3146 Q.pop();
3147 unsigned ID = getSubmoduleID(Mod);
3148 if (ID < FirstSubmoduleID) {
3149 assert(0 && "Loaded submodule entered WritingModule ?");
3150 continue;
3151 }
3152
3153 // Record the local offset of this submodule.
3154 unsigned Index = ID - FirstSubmoduleID;
3155 if (Index >= SubmoduleOffsets.size())
3156 SubmoduleOffsets.resize(Index + 1);
3157
3158 uint64_t Offset = Stream.GetCurrentBitNo() - SubmoduleOffsetBase;
3159 assert((Offset >> 32) == 0 && "Submodule offset too large");
3160 SubmoduleOffsets[Index] = Offset;
3161
3162 uint64_t ParentID = 0;
3163 if (Mod->Parent) {
3164 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
3165 ParentID = SubmoduleIDs[Mod->Parent];
3166 }
3167
3169 getRawSourceLocationEncoding(getAdjustedLocation(Mod->DefinitionLoc));
3170
3171 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
3172 FileID UnadjustedInferredFID;
3173 if (Mod->IsInferred)
3174 UnadjustedInferredFID = ModMap.getModuleMapFileIDForUniquing(Mod);
3175 int InferredFID = getAdjustedFileID(UnadjustedInferredFID).getOpaqueValue();
3176
3177 // Emit the definition of the block.
3178 {
3179 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
3180 ID,
3181 ParentID,
3182 (RecordData::value_type)Mod->Kind,
3183 DefinitionLoc,
3184 (RecordData::value_type)InferredFID,
3185 Mod->IsFramework,
3186 Mod->IsExplicit,
3187 Mod->IsSystem,
3188 Mod->IsExternC,
3189 Mod->InferSubmodules,
3193 Mod->ModuleMapIsPrivate,
3194 Mod->NamedModuleHasInit};
3195 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
3196 }
3197
3198 // Emit the requirements.
3199 for (const auto &R : Mod->Requirements) {
3200 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.RequiredState};
3201 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.FeatureName);
3202 }
3203
3204 // Emit the umbrella header, if there is one.
3205 if (std::optional<Module::Header> UmbrellaHeader =
3207 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
3208 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
3209 UmbrellaHeader->NameAsWritten);
3210 } else if (std::optional<Module::DirectoryName> UmbrellaDir =
3211 Mod->getUmbrellaDirAsWritten()) {
3212 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
3213 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
3214 UmbrellaDir->NameAsWritten);
3215 }
3216
3217 // Emit the headers.
3218 struct {
3219 unsigned RecordKind;
3220 unsigned Abbrev;
3221 Module::HeaderKind HeaderKind;
3222 } HeaderLists[] = {
3223 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
3224 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
3225 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
3226 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
3227 Module::HK_PrivateTextual},
3228 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
3229 };
3230 for (const auto &HL : HeaderLists) {
3231 RecordData::value_type Record[] = {HL.RecordKind};
3232 for (const auto &H : Mod->getHeaders(HL.HeaderKind))
3233 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
3234 }
3235
3236 // Emit the top headers.
3237 {
3238 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
3239 for (FileEntryRef H : Mod->getTopHeaders(PP->getFileManager())) {
3240 SmallString<128> HeaderName(H.getName());
3241 PreparePathForOutput(HeaderName);
3242 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, HeaderName);
3243 }
3244 }
3245
3246 // Emit the imports.
3247 if (!Mod->Imports.empty()) {
3248 RecordData Record;
3249 for (Module *I : Mod->Imports)
3250 Record.push_back(getSubmoduleID(I));
3251 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
3252 }
3253
3254 // Emit the modules affecting compilation that were not imported.
3255 if (!Mod->AffectingClangModules.empty()) {
3256 RecordData Record;
3257 for (Module *I : Mod->AffectingClangModules)
3258 Record.push_back(getSubmoduleID(I));
3259 Stream.EmitRecord(SUBMODULE_AFFECTING_MODULES, Record);
3260 }
3261
3262 // Emit the exports.
3263 if (!Mod->Exports.empty()) {
3264 RecordData Record;
3265 for (const auto &E : Mod->Exports) {
3266 // FIXME: This may fail; we don't require that all exported modules
3267 // are local or imported.
3268 Record.push_back(getSubmoduleID(E.first));
3269 Record.push_back(E.second);
3270 }
3271 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
3272 }
3273
3274 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
3275 // Might be unnecessary as use declarations are only used to build the
3276 // module itself.
3277
3278 // TODO: Consider serializing undeclared uses of modules.
3279
3280 // Emit the link libraries.
3281 for (const auto &LL : Mod->LinkLibraries) {
3282 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
3283 LL.IsFramework};
3284 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
3285 }
3286
3287 // Emit the conflicts.
3288 for (const auto &C : Mod->Conflicts) {
3289 // FIXME: This may fail; we don't require that all conflicting modules
3290 // are local or imported.
3291 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
3292 getSubmoduleID(C.Other)};
3293 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
3294 }
3295
3296 // Emit the configuration macros.
3297 for (const auto &CM : Mod->ConfigMacros) {
3298 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
3299 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
3300 }
3301
3302 // Emit the reachable initializers.
3303 // The initializer may only be unreachable in reduced BMI.
3304 if (Context && !GeneratingReducedBMI) {
3305 RecordData Inits;
3306 for (Decl *D : Context->getModuleInitializers(Mod))
3307 if (wasDeclEmitted(D))
3308 AddDeclRef(D, Inits);
3309 if (!Inits.empty())
3310 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
3311 }
3312
3313 // Emit the name of the re-exported module, if any.
3314 if (!Mod->ExportAsModule.empty()) {
3315 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
3316 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
3317 }
3318
3319 // Emit one SUBMODULE_CHILD record per direct child so the reader can
3320 // populate PendingSubmodules and demand-load children by name.
3321 for (Module *Child : Mod->submodules()) {
3322 RecordData::value_type Record[] = {SUBMODULE_CHILD,
3323 getSubmoduleID(Child)};
3324 Stream.EmitRecordWithBlob(ChildAbbrev, Record, Child->Name);
3325 }
3326
3327 // Emit the sentinel signifying the end of this submodule.
3328 {
3329 RecordData Record;
3330 Stream.EmitRecord(SUBMODULE_END, Record);
3331 }
3332
3333 // Queue up the submodules of this module.
3334 for (Module *M : Mod->submodules())
3335 Q.push(M);
3336 }
3337
3338 Stream.ExitBlock();
3339
3340 assert((NextSubmoduleID - FirstSubmoduleID == SubmoduleOffsets.size()) &&
3341 "Wrong # of submodules; found a reference to a non-local, "
3342 "non-imported submodule?");
3343
3344 Abbrev = std::make_shared<BitCodeAbbrev>();
3345 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_METADATA));
3346 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Submodule count
3347 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Base submodule ID
3348 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Top-level submod ID
3349 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Submodule offsets
3350 unsigned SubmoduleMetadataAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3351
3352 RecordData::value_type Record[] = {
3353 SUBMODULE_METADATA, SubmoduleOffsets.size(),
3354 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS, TopLevelID};
3355 Stream.EmitRecordWithBlob(SubmoduleMetadataAbbrev, Record,
3356 bytes(SubmoduleOffsets));
3357}
3358
3359void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3360 bool isModule) {
3361 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3362 DiagStateIDMap;
3363 unsigned CurrID = 0;
3364 RecordData Record;
3365
3366 auto EncodeDiagStateFlags =
3367 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3368 unsigned Result = (unsigned)DS->ExtBehavior;
3369 for (unsigned Val :
3370 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3371 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3372 (unsigned)DS->SuppressSystemWarnings})
3373 Result = (Result << 1) | Val;
3374 return Result;
3375 };
3376
3377 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3378 Record.push_back(Flags);
3379
3380 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3381 bool IncludeNonPragmaStates) {
3382 // Ensure that the diagnostic state wasn't modified since it was created.
3383 // We will not correctly round-trip this information otherwise.
3384 assert(Flags == EncodeDiagStateFlags(State) &&
3385 "diag state flags vary in single AST file");
3386
3387 // If we ever serialize non-pragma mappings outside the initial state, the
3388 // code below will need to consider more than getDefaultMapping.
3389 assert(!IncludeNonPragmaStates ||
3390 State == Diag.DiagStatesByLoc.FirstDiagState);
3391
3392 unsigned &DiagStateID = DiagStateIDMap[State];
3393 Record.push_back(DiagStateID);
3394
3395 if (DiagStateID == 0) {
3396 DiagStateID = ++CurrID;
3397 SmallVector<std::pair<unsigned, DiagnosticMapping>> Mappings;
3398
3399 // Add a placeholder for the number of mappings.
3400 auto SizeIdx = Record.size();
3401 Record.emplace_back();
3402 for (const auto &I : *State) {
3403 // Maybe skip non-pragmas.
3404 if (!I.second.isPragma() && !IncludeNonPragmaStates)
3405 continue;
3406 // Skip default mappings. We have a mapping for every diagnostic ever
3407 // emitted, regardless of whether it was customized.
3408 if (!I.second.isPragma() &&
3409 I.second == Diag.getDiagnosticIDs()->getDefaultMapping(I.first))
3410 continue;
3411 Mappings.push_back(I);
3412 }
3413
3414 // Sort by diag::kind for deterministic output.
3415 llvm::sort(Mappings, llvm::less_first());
3416
3417 for (const auto &I : Mappings) {
3418 Record.push_back(I.first);
3419 Record.push_back(I.second.serialize());
3420 }
3421 // Update the placeholder.
3422 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
3423 }
3424 };
3425
3426 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3427
3428 // Reserve a spot for the number of locations with state transitions.
3429 auto NumLocationsIdx = Record.size();
3430 Record.emplace_back();
3431
3432 // Emit the state transitions.
3433 unsigned NumLocations = 0;
3434 SmallVector<std::pair<FileID, const DiagnosticsEngine::DiagStateMap::File *>,
3435 16>
3436 Files;
3437 for (const auto &[ID, FilePtr] : Diag.DiagStatesByLoc.Files)
3438 Files.emplace_back(ID, FilePtr.get());
3439 llvm::sort(Files, llvm::less_first());
3440
3441 for (auto [FID, File] : Files) {
3442 if (!FID.isValid() || !File->HasLocalTransitions)
3443 continue;
3444 ++NumLocations;
3445
3446 AddFileID(FID, Record);
3447
3448 Record.push_back(File->StateTransitions.size());
3449 for (auto &StatePoint : File->StateTransitions) {
3450 Record.push_back(StatePoint.Offset);
3451 AddDiagState(StatePoint.State, false);
3452 }
3453 }
3454
3455 // Backpatch the number of locations.
3456 Record[NumLocationsIdx] = NumLocations;
3457
3458 // Emit CurDiagStateLoc. Do it last in order to match source order.
3459 //
3460 // This also protects against a hypothetical corner case with simulating
3461 // -Werror settings for implicit modules in the ASTReader, where reading
3462 // CurDiagState out of context could change whether warning pragmas are
3463 // treated as errors.
3464 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3465 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3466
3467 // Emit the push stack so that unmatched pushes from a preamble can be
3468 // restored when the main file is parsed. Each entry is a DiagState that
3469 // was active at the time of a `#pragma diagnostic push`.
3470 Record.push_back(Diag.DiagStateOnPushStack.size());
3471 for (const auto *State : Diag.DiagStateOnPushStack)
3472 AddDiagState(State, false);
3473
3474 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3475}
3476
3477//===----------------------------------------------------------------------===//
3478// Type Serialization
3479//===----------------------------------------------------------------------===//
3480
3481/// Write the representation of a type to the AST stream.
3482void ASTWriter::WriteType(ASTContext &Context, QualType T) {
3483 TypeIdx &IdxRef = TypeIdxs[T];
3484 if (IdxRef.getValue() == 0) // we haven't seen this type before.
3485 IdxRef = TypeIdx(0, NextTypeID++);
3486 TypeIdx Idx = IdxRef;
3487
3488 assert(Idx.getModuleFileIndex() == 0 && "Re-writing a type from a prior AST");
3489 assert(Idx.getValue() >= FirstTypeID && "Writing predefined type");
3490
3491 // Emit the type's representation.
3492 uint64_t Offset =
3493 ASTTypeWriter(Context, *this).write(T) - DeclTypesBlockStartOffset;
3494
3495 // Record the offset for this type.
3496 uint64_t Index = Idx.getValue() - FirstTypeID;
3497 if (TypeOffsets.size() == Index)
3498 TypeOffsets.emplace_back(Offset);
3499 else if (TypeOffsets.size() < Index) {
3500 TypeOffsets.resize(Index + 1);
3501 TypeOffsets[Index].set(Offset);
3502 } else {
3503 llvm_unreachable("Types emitted in wrong order");
3504 }
3505}
3506
3507//===----------------------------------------------------------------------===//
3508// Declaration Serialization
3509//===----------------------------------------------------------------------===//
3510
3512 auto *ND = dyn_cast<NamedDecl>(D);
3513 if (!ND)
3514 return false;
3515
3517 return false;
3518
3519 return ND->getFormalLinkage() == Linkage::Internal;
3520}
3521
3522/// Write the block containing all of the declaration IDs
3523/// lexically declared within the given DeclContext.
3524///
3525/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3526/// bitstream, or 0 if no block was written.
3527uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3528 const DeclContext *DC) {
3529 if (DC->decls_empty())
3530 return 0;
3531
3532 // In reduced BMI, we don't care the declarations in functions.
3533 if (GeneratingReducedBMI && DC->isFunctionOrMethod())
3534 return 0;
3535
3536 uint64_t Offset = Stream.GetCurrentBitNo();
3537 SmallVector<DeclID, 128> KindDeclPairs;
3538 for (const auto *D : DC->decls()) {
3539 if (DoneWritingDeclsAndTypes && !wasDeclEmitted(D))
3540 continue;
3541
3542 // We don't need to write decls with internal linkage into reduced BMI.
3543 // If such decls gets emitted due to it get used from inline functions,
3544 // the program illegal. However, there are too many use of static inline
3545 // functions in the global module fragment and it will be breaking change
3546 // to forbid that. So we have to allow to emit such declarations from GMF.
3547 if (GeneratingReducedBMI && !D->isFromExplicitGlobalModule() &&
3549 continue;
3550
3551 KindDeclPairs.push_back(D->getKind());
3552 KindDeclPairs.push_back(GetDeclRef(D).getRawValue());
3553 }
3554
3555 ++NumLexicalDeclContexts;
3556 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3557 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3558 bytes(KindDeclPairs));
3559 return Offset;
3560}
3561
3562void ASTWriter::WriteTypeDeclOffsets() {
3563 using namespace llvm;
3564
3565 // Write the type offsets array
3566 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3567 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3568 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3569 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3570 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3571 {
3572 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size()};
3573 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3574 }
3575
3576 // Write the declaration offsets array
3577 Abbrev = std::make_shared<BitCodeAbbrev>();
3578 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3579 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3580 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3581 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3582 {
3583 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size()};
3584 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3585 }
3586}
3587
3588void ASTWriter::WriteFileDeclIDsMap() {
3589 using namespace llvm;
3590
3591 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs;
3592 SortedFileDeclIDs.reserve(FileDeclIDs.size());
3593 for (const auto &P : FileDeclIDs)
3594 SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
3595 llvm::sort(SortedFileDeclIDs, llvm::less_first());
3596
3597 // Join the vectors of DeclIDs from all files.
3598 SmallVector<DeclID, 256> FileGroupedDeclIDs;
3599 for (auto &FileDeclEntry : SortedFileDeclIDs) {
3600 DeclIDInFileInfo &Info = *FileDeclEntry.second;
3601 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3602 llvm::stable_sort(Info.DeclIDs);
3603 for (auto &LocDeclEntry : Info.DeclIDs)
3604 FileGroupedDeclIDs.push_back(LocDeclEntry.second.getRawValue());
3605 }
3606
3607 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3608 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3609 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3610 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3611 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3612 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3613 FileGroupedDeclIDs.size()};
3614 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3615}
3616
3617void ASTWriter::WriteComments(ASTContext &Context) {
3618 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3619 llvm::scope_exit _([this] { Stream.ExitBlock(); });
3621 return;
3622
3623 RecordData Record;
3624 for (const auto &FO : Context.Comments.OrderedComments) {
3625 for (const auto &OC : FO.second) {
3626 const RawComment *I = OC.second;
3627 Record.clear();
3628 AddSourceRange(I->getSourceRange(), Record);
3629 Record.push_back(I->getKind());
3630 Record.push_back(I->isTrailingComment());
3631 Record.push_back(I->isAlmostTrailingComment());
3632 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3633 }
3634 }
3635}
3636
3637//===----------------------------------------------------------------------===//
3638// Global Method Pool and Selector Serialization
3639//===----------------------------------------------------------------------===//
3640
3641namespace {
3642
3643// Trait used for the on-disk hash table used in the method pool.
3644class ASTMethodPoolTrait {
3645 ASTWriter &Writer;
3646
3647public:
3648 using key_type = Selector;
3649 using key_type_ref = key_type;
3650
3651 struct data_type {
3652 SelectorID ID;
3653 ObjCMethodList Instance, Factory;
3654 };
3655 using data_type_ref = const data_type &;
3656
3657 using hash_value_type = unsigned;
3658 using offset_type = unsigned;
3659
3660 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3661
3662 static hash_value_type ComputeHash(Selector Sel) {
3663 return serialization::ComputeHash(Sel);
3664 }
3665
3666 std::pair<unsigned, unsigned>
3667 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3668 data_type_ref Methods) {
3669 unsigned KeyLen =
3670 2 + (Sel.getNumArgs() ? Sel.getNumArgs() * sizeof(IdentifierID)
3671 : sizeof(IdentifierID));
3672 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3673 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3674 Method = Method->getNext())
3675 if (ShouldWriteMethodListNode(Method))
3676 DataLen += sizeof(DeclID);
3677 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3678 Method = Method->getNext())
3679 if (ShouldWriteMethodListNode(Method))
3680 DataLen += sizeof(DeclID);
3681 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3682 }
3683
3684 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3685 using namespace llvm::support;
3686
3687 endian::Writer LE(Out, llvm::endianness::little);
3688 uint64_t Start = Out.tell();
3689 assert((Start >> 32) == 0 && "Selector key offset too large");
3690 Writer.SetSelectorOffset(Sel, Start);
3691 unsigned N = Sel.getNumArgs();
3692 LE.write<uint16_t>(N);
3693 if (N == 0)
3694 N = 1;
3695 for (unsigned I = 0; I != N; ++I)
3696 LE.write<IdentifierID>(
3698 }
3699
3700 void EmitData(raw_ostream& Out, key_type_ref,
3701 data_type_ref Methods, unsigned DataLen) {
3702 using namespace llvm::support;
3703
3704 endian::Writer LE(Out, llvm::endianness::little);
3705 uint64_t Start = Out.tell(); (void)Start;
3706 LE.write<uint32_t>(Methods.ID);
3707 unsigned NumInstanceMethods = 0;
3708 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3709 Method = Method->getNext())
3710 if (ShouldWriteMethodListNode(Method))
3711 ++NumInstanceMethods;
3712
3713 unsigned NumFactoryMethods = 0;
3714 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3715 Method = Method->getNext())
3716 if (ShouldWriteMethodListNode(Method))
3717 ++NumFactoryMethods;
3718
3719 unsigned InstanceBits = Methods.Instance.getBits();
3720 assert(InstanceBits < 4);
3721 unsigned InstanceHasMoreThanOneDeclBit =
3722 Methods.Instance.hasMoreThanOneDecl();
3723 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3724 (InstanceHasMoreThanOneDeclBit << 2) |
3725 InstanceBits;
3726 unsigned FactoryBits = Methods.Factory.getBits();
3727 assert(FactoryBits < 4);
3728 unsigned FactoryHasMoreThanOneDeclBit =
3729 Methods.Factory.hasMoreThanOneDecl();
3730 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3731 (FactoryHasMoreThanOneDeclBit << 2) |
3732 FactoryBits;
3733 LE.write<uint16_t>(FullInstanceBits);
3734 LE.write<uint16_t>(FullFactoryBits);
3735 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3736 Method = Method->getNext())
3737 if (ShouldWriteMethodListNode(Method))
3738 LE.write<DeclID>((DeclID)Writer.getDeclID(Method->getMethod()));
3739 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3740 Method = Method->getNext())
3741 if (ShouldWriteMethodListNode(Method))
3742 LE.write<DeclID>((DeclID)Writer.getDeclID(Method->getMethod()));
3743
3744 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3745 }
3746
3747private:
3748 static bool ShouldWriteMethodListNode(const ObjCMethodList *Node) {
3749 return (Node->getMethod() && !Node->getMethod()->isFromASTFile());
3750 }
3751};
3752
3753} // namespace
3754
3755/// Write ObjC data: selectors and the method pool.
3756///
3757/// The method pool contains both instance and factory methods, stored
3758/// in an on-disk hash table indexed by the selector. The hash table also
3759/// contains an empty entry for every other selector known to Sema.
3760void ASTWriter::WriteSelectors(Sema &SemaRef) {
3761 using namespace llvm;
3762
3763 // Do we have to do anything at all?
3764 if (SemaRef.ObjC().MethodPool.empty() && SelectorIDs.empty())
3765 return;
3766 unsigned NumTableEntries = 0;
3767 // Create and write out the blob that contains selectors and the method pool.
3768 {
3769 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3770 ASTMethodPoolTrait Trait(*this);
3771
3772 // Create the on-disk hash table representation. We walk through every
3773 // selector we've seen and look it up in the method pool.
3774 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3775 for (auto &SelectorAndID : SelectorIDs) {
3776 Selector S = SelectorAndID.first;
3777 SelectorID ID = SelectorAndID.second;
3778 SemaObjC::GlobalMethodPool::iterator F =
3779 SemaRef.ObjC().MethodPool.find(S);
3780 ASTMethodPoolTrait::data_type Data = {
3781 ID,
3782 ObjCMethodList(),
3783 ObjCMethodList()
3784 };
3785 if (F != SemaRef.ObjC().MethodPool.end()) {
3786 Data.Instance = F->second.first;
3787 Data.Factory = F->second.second;
3788 }
3789 // Only write this selector if it's not in an existing AST or something
3790 // changed.
3791 if (Chain && ID < FirstSelectorID) {
3792 // Selector already exists. Did it change?
3793 bool changed = false;
3794 for (ObjCMethodList *M = &Data.Instance; M && M->getMethod();
3795 M = M->getNext()) {
3796 if (!M->getMethod()->isFromASTFile()) {
3797 changed = true;
3798 Data.Instance = *M;
3799 break;
3800 }
3801 }
3802 for (ObjCMethodList *M = &Data.Factory; M && M->getMethod();
3803 M = M->getNext()) {
3804 if (!M->getMethod()->isFromASTFile()) {
3805 changed = true;
3806 Data.Factory = *M;
3807 break;
3808 }
3809 }
3810 if (!changed)
3811 continue;
3812 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3813 // A new method pool entry.
3814 ++NumTableEntries;
3815 }
3816 Generator.insert(S, Data, Trait);
3817 }
3818
3819 // Create the on-disk hash table in a buffer.
3820 SmallString<4096> MethodPool;
3821 uint32_t BucketOffset;
3822 {
3823 using namespace llvm::support;
3824
3825 ASTMethodPoolTrait Trait(*this);
3826 llvm::raw_svector_ostream Out(MethodPool);
3827 // Make sure that no bucket is at offset 0
3828 endian::write<uint32_t>(Out, 0, llvm::endianness::little);
3829 BucketOffset = Generator.Emit(Out, Trait);
3830 }
3831
3832 // Create a blob abbreviation
3833 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3834 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3835 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3836 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3837 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3838 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3839
3840 // Write the method pool
3841 {
3842 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3843 NumTableEntries};
3844 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3845 }
3846
3847 // Create a blob abbreviation for the selector table offsets.
3848 Abbrev = std::make_shared<BitCodeAbbrev>();
3849 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3850 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3851 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3852 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3853 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3854
3855 // Write the selector offsets table.
3856 {
3857 RecordData::value_type Record[] = {
3858 SELECTOR_OFFSETS, SelectorOffsets.size(),
3859 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3860 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3861 bytes(SelectorOffsets));
3862 }
3863 }
3864}
3865
3866/// Write the selectors referenced in @selector expression into AST file.
3867void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3868 using namespace llvm;
3869
3870 if (SemaRef.ObjC().ReferencedSelectors.empty())
3871 return;
3872
3873 RecordData Record;
3874 ASTRecordWriter Writer(SemaRef.Context, *this, Record);
3875
3876 // Note: this writes out all references even for a dependent AST. But it is
3877 // very tricky to fix, and given that @selector shouldn't really appear in
3878 // headers, probably not worth it. It's not a correctness issue.
3879 for (auto &SelectorAndLocation : SemaRef.ObjC().ReferencedSelectors) {
3880 Selector Sel = SelectorAndLocation.first;
3881 SourceLocation Loc = SelectorAndLocation.second;
3882 Writer.AddSelectorRef(Sel);
3883 Writer.AddSourceLocation(Loc);
3884 }
3885 Writer.Emit(REFERENCED_SELECTOR_POOL);
3886}
3887
3888//===----------------------------------------------------------------------===//
3889// Identifier Table Serialization
3890//===----------------------------------------------------------------------===//
3891
3892/// Determine the declaration that should be put into the name lookup table to
3893/// represent the given declaration in this module. This is usually D itself,
3894/// but if D was imported and merged into a local declaration, we want the most
3895/// recent local declaration instead. The chosen declaration will be the most
3896/// recent declaration in any module that imports this one.
3898 NamedDecl *D) {
3899 if (!LangOpts.Modules || !D->isFromASTFile())
3900 return D;
3901
3902 if (Decl *Redecl = D->getPreviousDecl()) {
3903 // For Redeclarable decls, a prior declaration might be local.
3904 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3905 // If we find a local decl, we're done.
3906 if (!Redecl->isFromASTFile()) {
3907 // Exception: in very rare cases (for injected-class-names), not all
3908 // redeclarations are in the same semantic context. Skip ones in a
3909 // different context. They don't go in this lookup table at all.
3910 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3912 continue;
3913 return cast<NamedDecl>(Redecl);
3914 }
3915
3916 // If we find a decl from a (chained-)PCH stop since we won't find a
3917 // local one.
3918 if (Redecl->getOwningModuleID() == 0)
3919 break;
3920 }
3921 } else if (Decl *First = D->getCanonicalDecl()) {
3922 // For Mergeable decls, the first decl might be local.
3923 if (!First->isFromASTFile())
3924 return cast<NamedDecl>(First);
3925 }
3926
3927 // All declarations are imported. Our most recent declaration will also be
3928 // the most recent one in anyone who imports us.
3929 return D;
3930}
3931
3932namespace {
3933
3934bool IsInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset,
3935 bool IsModule, bool IsCPlusPlus) {
3936 bool NeedDecls = !IsModule || !IsCPlusPlus;
3937
3938 bool IsInteresting =
3939 II->getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
3940 II->getBuiltinID() != Builtin::ID::NotBuiltin ||
3941 II->getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
3942 if (MacroOffset ||
3943 (II->hasMacroDefinition() &&
3945 II->isPoisoned() || (!IsModule && IsInteresting) ||
3947 (NeedDecls && II->getFETokenInfo()))
3948 return true;
3949
3950 return false;
3951}
3952
3953bool IsInterestingNonMacroIdentifier(const IdentifierInfo *II,
3954 ASTWriter &Writer) {
3955 bool IsModule = Writer.isWritingModule();
3956 bool IsCPlusPlus = Writer.getLangOpts().CPlusPlus;
3957 return IsInterestingIdentifier(II, /*MacroOffset=*/0, IsModule, IsCPlusPlus);
3958}
3959
3960class ASTIdentifierTableTrait {
3961 ASTWriter &Writer;
3962 Preprocessor &PP;
3963 IdentifierResolver *IdResolver;
3964 bool IsModule;
3965 bool NeedDecls;
3966 ASTWriter::RecordData *InterestingIdentifierOffsets;
3967
3968 /// Determines whether this is an "interesting" identifier that needs a
3969 /// full IdentifierInfo structure written into the hash table. Notably, this
3970 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3971 /// to check that.
3972 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3973 return IsInterestingIdentifier(II, MacroOffset, IsModule,
3974 Writer.getLangOpts().CPlusPlus);
3975 }
3976
3977public:
3978 using key_type = const IdentifierInfo *;
3979 using key_type_ref = key_type;
3980
3981 using data_type = IdentifierID;
3982 using data_type_ref = data_type;
3983
3984 using hash_value_type = unsigned;
3985 using offset_type = unsigned;
3986
3987 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3988 IdentifierResolver *IdResolver, bool IsModule,
3989 ASTWriter::RecordData *InterestingIdentifierOffsets)
3990 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3991 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3992 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3993
3994 bool needDecls() const { return NeedDecls; }
3995
3996 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3997 return llvm::djbHash(II->getName());
3998 }
3999
4000 bool isInterestingIdentifier(const IdentifierInfo *II) {
4001 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
4002 return isInterestingIdentifier(II, MacroOffset);
4003 }
4004
4005 std::pair<unsigned, unsigned>
4006 EmitKeyDataLength(raw_ostream &Out, const IdentifierInfo *II, IdentifierID ID) {
4007 // Record the location of the identifier data. This is used when generating
4008 // the mapping from persistent IDs to strings.
4009 Writer.SetIdentifierOffset(II, Out.tell());
4010
4011 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
4012
4013 // Emit the offset of the key/data length information to the interesting
4014 // identifiers table if necessary.
4015 if (InterestingIdentifierOffsets &&
4016 isInterestingIdentifier(II, MacroOffset))
4017 InterestingIdentifierOffsets->push_back(Out.tell());
4018
4019 unsigned KeyLen = II->getLength() + 1;
4020 unsigned DataLen = sizeof(IdentifierID); // bytes for the persistent ID << 1
4021 if (isInterestingIdentifier(II, MacroOffset)) {
4022 DataLen += 2; // 2 bytes for builtin ID
4023 DataLen += 2; // 2 bytes for flags
4024 if (MacroOffset || (II->hasMacroDefinition() &&
4026 DataLen += 4; // MacroDirectives offset.
4027
4028 if (NeedDecls && IdResolver)
4029 DataLen += std::distance(IdResolver->begin(II), IdResolver->end()) *
4030 sizeof(DeclID);
4031 }
4032 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
4033 }
4034
4035 void EmitKey(raw_ostream &Out, const IdentifierInfo *II, unsigned KeyLen) {
4036 Out.write(II->getNameStart(), KeyLen);
4037 }
4038
4039 void EmitData(raw_ostream &Out, const IdentifierInfo *II, IdentifierID ID,
4040 unsigned) {
4041 using namespace llvm::support;
4042
4043 endian::Writer LE(Out, llvm::endianness::little);
4044
4045 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
4046 if (!isInterestingIdentifier(II, MacroOffset)) {
4047 LE.write<IdentifierID>(ID << 1);
4048 return;
4049 }
4050
4051 LE.write<IdentifierID>((ID << 1) | 0x01);
4052 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
4053 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
4054 LE.write<uint16_t>(Bits);
4055 Bits = 0;
4056 bool HasMacroDefinition =
4057 (MacroOffset != 0) || (II->hasMacroDefinition() &&
4059 Bits = (Bits << 1) | unsigned(HasMacroDefinition);
4060 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
4061 Bits = (Bits << 1) | unsigned(II->isPoisoned());
4062 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
4063 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
4064 LE.write<uint16_t>(Bits);
4065
4066 if (HasMacroDefinition)
4067 LE.write<uint32_t>(MacroOffset);
4068
4069 if (NeedDecls && IdResolver) {
4070 // Emit the declaration IDs in reverse order, because the
4071 // IdentifierResolver provides the declarations as they would be
4072 // visible (e.g., the function "stat" would come before the struct
4073 // "stat"), but the ASTReader adds declarations to the end of the list
4074 // (so we need to see the struct "stat" before the function "stat").
4075 // Only emit declarations that aren't from a chained PCH, though.
4076 SmallVector<NamedDecl *, 16> Decls(IdResolver->decls(II));
4077 for (NamedDecl *D : llvm::reverse(Decls))
4078 LE.write<DeclID>((DeclID)Writer.getDeclID(
4080 }
4081 }
4082};
4083
4084} // namespace
4085
4086/// If the \param IdentifierID ID is a local Identifier ID. If the higher
4087/// bits of ID is 0, it implies that the ID doesn't come from AST files.
4088static bool isLocalIdentifierID(IdentifierID ID) { return !(ID >> 32); }
4089
4090/// Write the identifier table into the AST file.
4091///
4092/// The identifier table consists of a blob containing string data
4093/// (the actual identifiers themselves) and a separate "offsets" index
4094/// that maps identifier IDs to locations within the blob.
4095void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
4096 IdentifierResolver *IdResolver,
4097 bool IsModule) {
4098 using namespace llvm;
4099
4100 RecordData InterestingIdents;
4101
4102 // Create and write out the blob that contains the identifier
4103 // strings.
4104 {
4105 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
4106 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule,
4107 IsModule ? &InterestingIdents : nullptr);
4108
4109 // Create the on-disk hash table representation. We only store offsets
4110 // for identifiers that appear here for the first time.
4111 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
4112 for (auto IdentIDPair : IdentifierIDs) {
4113 const IdentifierInfo *II = IdentIDPair.first;
4114 IdentifierID ID = IdentIDPair.second;
4115 assert(II && "NULL identifier in identifier table");
4116
4117 // Write out identifiers if either the ID is local or the identifier has
4118 // changed since it was loaded.
4120 (Trait.needDecls() &&
4122 Generator.insert(II, ID, Trait);
4123 }
4124
4125 // Create the on-disk hash table in a buffer.
4126 SmallString<4096> IdentifierTable;
4127 uint32_t BucketOffset;
4128 {
4129 using namespace llvm::support;
4130
4131 llvm::raw_svector_ostream Out(IdentifierTable);
4132 // Make sure that no bucket is at offset 0
4133 endian::write<uint32_t>(Out, 0, llvm::endianness::little);
4134 BucketOffset = Generator.Emit(Out, Trait);
4135 }
4136
4137 // Create a blob abbreviation
4138 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4139 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
4140 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4141 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4142 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4143
4144 // Write the identifier table
4145 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
4146 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
4147 }
4148
4149 // Write the offsets table for identifier IDs.
4150 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4151 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
4152 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
4153 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4154 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4155
4156#ifndef NDEBUG
4157 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
4158 assert(IdentifierOffsets[I] && "Missing identifier offset?");
4159#endif
4160
4161 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
4162 IdentifierOffsets.size()};
4163 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
4164 bytes(IdentifierOffsets));
4165
4166 // In C++, write the list of interesting identifiers (those that are
4167 // defined as macros, poisoned, or similar unusual things).
4168 if (!InterestingIdents.empty())
4169 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
4170}
4171
4173 if (!RD->isInNamedModule())
4174 return;
4175
4176 PendingEmittingVTables.push_back(RD);
4177}
4178
4180 TouchedModuleFiles.insert(MF);
4181}
4182
4183//===----------------------------------------------------------------------===//
4184// DeclContext's Name Lookup Table Serialization
4185//===----------------------------------------------------------------------===//
4186
4187namespace {
4188
4189class ASTDeclContextNameLookupTraitBase {
4190protected:
4191 ASTWriter &Writer;
4192 using DeclIDsTy = llvm::SmallVector<LocalDeclID, 64>;
4193 DeclIDsTy DeclIDs;
4194
4195public:
4196 /// A start and end index into DeclIDs, representing a sequence of decls.
4197 using data_type = std::pair<unsigned, unsigned>;
4198 using data_type_ref = const data_type &;
4199
4200 using hash_value_type = unsigned;
4201 using offset_type = unsigned;
4202
4203 explicit ASTDeclContextNameLookupTraitBase(ASTWriter &Writer)
4204 : Writer(Writer) {}
4205
4206 data_type getData(const DeclIDsTy &LocalIDs) {
4207 unsigned Start = DeclIDs.size();
4208 for (auto ID : LocalIDs)
4209 DeclIDs.push_back(ID);
4210 return std::make_pair(Start, DeclIDs.size());
4211 }
4212
4213 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
4214 unsigned Start = DeclIDs.size();
4215 DeclIDs.insert(
4216 DeclIDs.end(),
4217 DeclIDIterator<GlobalDeclID, LocalDeclID>(FromReader.begin()),
4218 DeclIDIterator<GlobalDeclID, LocalDeclID>(FromReader.end()));
4219 return std::make_pair(Start, DeclIDs.size());
4220 }
4221
4222 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
4223 assert(Writer.hasChain() &&
4224 "have reference to loaded module file but no chain?");
4225
4226 using namespace llvm::support;
4227 Writer.addTouchedModuleFile(F);
4228 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F),
4229 llvm::endianness::little);
4230 }
4231
4232 std::pair<unsigned, unsigned> EmitKeyDataLengthBase(raw_ostream &Out,
4233 DeclarationNameKey Name,
4234 data_type_ref Lookup) {
4235 unsigned KeyLen = 1;
4236 switch (Name.getKind()) {
4240 KeyLen += sizeof(IdentifierID);
4241 break;
4245 KeyLen += 4;
4246 break;
4248 KeyLen += 1;
4249 break;
4254 break;
4255 }
4256
4257 // length of DeclIDs.
4258 unsigned DataLen = sizeof(DeclID) * (Lookup.second - Lookup.first);
4259
4260 return {KeyLen, DataLen};
4261 }
4262
4263 void EmitKeyBase(raw_ostream &Out, DeclarationNameKey Name) {
4264 using namespace llvm::support;
4265
4266 endian::Writer LE(Out, llvm::endianness::little);
4267 LE.write<uint8_t>(Name.getKind());
4268 switch (Name.getKind()) {
4272 LE.write<IdentifierID>(Writer.getIdentifierRef(Name.getIdentifier()));
4273 return;
4277 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
4278 return;
4280 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
4281 "Invalid operator?");
4282 LE.write<uint8_t>(Name.getOperatorKind());
4283 return;
4288 return;
4289 }
4290
4291 llvm_unreachable("Invalid name kind?");
4292 }
4293
4294 void EmitDataBase(raw_ostream &Out, data_type Lookup, unsigned DataLen) {
4295 using namespace llvm::support;
4296
4297 endian::Writer LE(Out, llvm::endianness::little);
4298 uint64_t Start = Out.tell(); (void)Start;
4299 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
4300 LE.write<DeclID>((DeclID)DeclIDs[I]);
4301 assert(Out.tell() - Start == DataLen && "Data length is wrong");
4302 }
4303};
4304
4305class ModuleLevelNameLookupTrait : public ASTDeclContextNameLookupTraitBase {
4306public:
4307 using primary_module_hash_type = unsigned;
4308
4309 using key_type = std::pair<DeclarationNameKey, primary_module_hash_type>;
4310 using key_type_ref = key_type;
4311
4312 explicit ModuleLevelNameLookupTrait(ASTWriter &Writer)
4313 : ASTDeclContextNameLookupTraitBase(Writer) {}
4314
4315 static bool EqualKey(key_type_ref a, key_type_ref b) { return a == b; }
4316
4317 hash_value_type ComputeHash(key_type Key) {
4318 llvm::FoldingSetNodeID ID;
4319 ID.AddInteger(Key.first.getHash());
4320 ID.AddInteger(Key.second);
4321 return ID.computeStableHash();
4322 }
4323
4324 std::pair<unsigned, unsigned>
4325 EmitKeyDataLength(raw_ostream &Out, key_type Key, data_type_ref Lookup) {
4326 auto [KeyLen, DataLen] = EmitKeyDataLengthBase(Out, Key.first, Lookup);
4327 KeyLen += sizeof(Key.second);
4328 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
4329 }
4330
4331 void EmitKey(raw_ostream &Out, key_type Key, unsigned) {
4332 EmitKeyBase(Out, Key.first);
4333 llvm::support::endian::Writer LE(Out, llvm::endianness::little);
4334 LE.write<primary_module_hash_type>(Key.second);
4335 }
4336
4337 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
4338 unsigned DataLen) {
4339 EmitDataBase(Out, Lookup, DataLen);
4340 }
4341};
4342
4343class ASTDeclContextNameTrivialLookupTrait
4344 : public ASTDeclContextNameLookupTraitBase {
4345public:
4346 using key_type = DeclarationNameKey;
4347 using key_type_ref = key_type;
4348
4349public:
4350 using ASTDeclContextNameLookupTraitBase::ASTDeclContextNameLookupTraitBase;
4351
4352 using ASTDeclContextNameLookupTraitBase::getData;
4353
4354 static bool EqualKey(key_type_ref a, key_type_ref b) { return a == b; }
4355
4356 hash_value_type ComputeHash(key_type Name) { return Name.getHash(); }
4357
4358 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
4359 DeclarationNameKey Name,
4360 data_type_ref Lookup) {
4361 auto [KeyLen, DataLen] = EmitKeyDataLengthBase(Out, Name, Lookup);
4362 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
4363 }
4364
4365 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
4366 return EmitKeyBase(Out, Name);
4367 }
4368
4369 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
4370 unsigned DataLen) {
4371 EmitDataBase(Out, Lookup, DataLen);
4372 }
4373};
4374
4375static bool isModuleLocalDecl(NamedDecl *D) {
4376 // For decls not in a file context, they should have the same visibility
4377 // with their parent.
4378 if (auto *Parent = dyn_cast<NamedDecl>(D->getNonTransparentDeclContext());
4380 return isModuleLocalDecl(Parent);
4381
4382 // Deduction guides are not found by name lookup. Keep them in the general
4383 // lookup table so that Sema can consider all reachable deduction guides,
4384 // including when instantiating an exported template that uses a
4385 // non-exported class template.
4387 return false;
4388
4389 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
4390 if (isa<CXXDeductionGuideDecl>(FTD->getTemplatedDecl()))
4391 return false;
4392
4393 if (D->getFormalLinkage() != Linkage::Module)
4394 return false;
4395
4396 // It is hard for the serializer to judge if the in-class friend declaration
4397 // is visible or not, so we just transfer the task to Sema. It should be a
4398 // safe decision since Sema is able to handle the lookup rules for in-class
4399 // friend declarations good enough already.
4400 if (D->getFriendObjectKind() &&
4402 return false;
4403
4404 return true;
4405}
4406
4407static bool isTULocalInNamedModules(NamedDecl *D) {
4408 Module *NamedModule = D->getTopLevelOwningNamedModule();
4409 if (!NamedModule)
4410 return false;
4411
4412 // For none-top level decls, we choose to move it to the general visible
4413 // lookup table. Since the consumer may get its parent somehow and performs
4414 // a lookup in it (considering looking up the operator function in lambda).
4415 // The difference between module local lookup table and TU local lookup table
4416 // is, the consumers still have a chance to lookup in the module local lookup
4417 // table but **now** the consumers won't read the TU local lookup table if
4418 // the consumer is not the original TU.
4419 //
4420 // FIXME: It seems to be an optimization chance (and also a more correct
4421 // semantics) to remain the TULocal lookup table and performing similar lookup
4422 // with the module local lookup table except that we only allow the lookups
4423 // with the same module unit.
4425 return false;
4426
4427 return D->getLinkageInternal() == Linkage::Internal;
4428}
4429
4430class ASTDeclContextNameLookupTrait
4431 : public ASTDeclContextNameTrivialLookupTrait {
4432public:
4433 using TULocalDeclsMapTy = llvm::DenseMap<key_type, DeclIDsTy>;
4434
4435 using ModuleLevelDeclsMapTy =
4436 llvm::DenseMap<ModuleLevelNameLookupTrait::key_type, DeclIDsTy>;
4437
4438private:
4439 enum class LookupVisibility {
4440 GenerallyVisibile,
4441 // The decls can only be found by other TU in the same module.
4442 // Note a clang::Module models a module unit instead of logical module
4443 // in C++20.
4444 ModuleLocalVisible,
4445 // The decls can only be found by the TU itself that defines it.
4446 TULocal,
4447 };
4448
4449 LookupVisibility getLookupVisibility(NamedDecl *D) const {
4450 // Only named modules have other lookup visibility.
4451 if (!Writer.isWritingStdCXXNamedModules())
4452 return LookupVisibility::GenerallyVisibile;
4453
4454 if (isModuleLocalDecl(D))
4455 return LookupVisibility::ModuleLocalVisible;
4456 if (isTULocalInNamedModules(D))
4457 return LookupVisibility::TULocal;
4458
4459 // A trick to handle enum constants. The enum constants is special since
4460 // they can be found directly without their parent context. This makes it
4461 // tricky to decide if an EnumConstantDecl is visible or not by their own
4462 // visibilities. E.g., for a class member, we can assume it is visible if
4463 // the user get its parent somehow. But for an enum constant, the users may
4464 // access if without its parent context. Although we can fix the problem in
4465 // Sema lookup process, it might be too complex, we just make a trick here.
4466 // Note that we only removes enum constant from the lookup table from its
4467 // parent of parent. We DON'T remove the enum constant from its parent. So
4468 // we don't need to care about merging problems here.
4469 if (auto *ECD = dyn_cast<EnumConstantDecl>(D);
4470 ECD && DC.isFileContext() && ECD->getTopLevelOwningNamedModule()) {
4471 if (llvm::all_of(
4472 DC.noload_lookup(
4473 cast<EnumDecl>(ECD->getDeclContext())->getDeclName()),
4474 [](auto *Found) {
4475 return Found->isInvisibleOutsideTheOwningModule();
4476 }))
4477 return ECD->isFromExplicitGlobalModule() ||
4478 ECD->isInAnonymousNamespace()
4479 ? LookupVisibility::TULocal
4480 : LookupVisibility::ModuleLocalVisible;
4481 }
4482
4483 return LookupVisibility::GenerallyVisibile;
4484 }
4485
4486 DeclContext &DC;
4487 ModuleLevelDeclsMapTy ModuleLocalDeclsMap;
4488 TULocalDeclsMapTy TULocalDeclsMap;
4489
4490public:
4491 using ASTDeclContextNameTrivialLookupTrait::
4492 ASTDeclContextNameTrivialLookupTrait;
4493
4494 ASTDeclContextNameLookupTrait(ASTWriter &Writer, DeclContext &DC)
4495 : ASTDeclContextNameTrivialLookupTrait(Writer), DC(DC) {}
4496
4497 template <typename Coll> data_type getData(const Coll &Decls) {
4498 unsigned Start = DeclIDs.size();
4499 auto AddDecl = [this](NamedDecl *D) {
4500 NamedDecl *DeclForLocalLookup =
4502
4503 if (Writer.getDoneWritingDeclsAndTypes() &&
4504 !Writer.wasDeclEmitted(DeclForLocalLookup))
4505 return;
4506
4507 // Try to avoid writing internal decls to reduced BMI.
4508 // See comments in ASTWriter::WriteDeclContextLexicalBlock for details.
4509 if (Writer.isGeneratingReducedBMI() &&
4510 !DeclForLocalLookup->isFromExplicitGlobalModule() &&
4511 IsInternalDeclFromFileContext(DeclForLocalLookup))
4512 return;
4513
4514 auto ID = Writer.GetDeclRef(DeclForLocalLookup);
4515
4516 switch (getLookupVisibility(DeclForLocalLookup)) {
4517 case LookupVisibility::ModuleLocalVisible:
4518 if (UnsignedOrNone PrimaryModuleHash =
4520 auto Key = std::make_pair(D->getDeclName(), *PrimaryModuleHash);
4521 auto Iter = ModuleLocalDeclsMap.find(Key);
4522 if (Iter == ModuleLocalDeclsMap.end())
4523 ModuleLocalDeclsMap.insert({Key, DeclIDsTy{ID}});
4524 else
4525 Iter->second.push_back(ID);
4526 return;
4527 }
4528 break;
4529 case LookupVisibility::TULocal: {
4530 auto Iter = TULocalDeclsMap.find(D->getDeclName());
4531 if (Iter == TULocalDeclsMap.end())
4532 TULocalDeclsMap.insert({D->getDeclName(), DeclIDsTy{ID}});
4533 else
4534 Iter->second.push_back(ID);
4535 return;
4536 }
4537 case LookupVisibility::GenerallyVisibile:
4538 // Generally visible decls go into the general lookup table.
4539 break;
4540 }
4541
4542 DeclIDs.push_back(ID);
4543 };
4544 ASTReader *Chain = Writer.getChain();
4545 for (NamedDecl *D : Decls) {
4546 if (Chain && isa<NamespaceDecl>(D) && D->isFromASTFile() &&
4547 D == Chain->getKeyDeclaration(D)) {
4548 // In ASTReader, we stored only the key declaration of a namespace decl
4549 // for this TU. If we have an external namespace decl, this is that
4550 // key declaration and we need to re-expand it to write out the first
4551 // decl from each module.
4552 //
4553 // See comment 'ASTReader::FindExternalVisibleDeclsByName' for details.
4554 auto Firsts =
4555 Writer.CollectFirstDeclFromEachModule(D, /*IncludeLocal=*/false);
4556 for (const auto &[_, First] : Firsts)
4557 AddDecl(cast<NamedDecl>(const_cast<Decl *>(First)));
4558 } else {
4559 AddDecl(D);
4560 }
4561 }
4562 return std::make_pair(Start, DeclIDs.size());
4563 }
4564
4565 const ModuleLevelDeclsMapTy &getModuleLocalDecls() {
4566 return ModuleLocalDeclsMap;
4567 }
4568
4569 const TULocalDeclsMapTy &getTULocalDecls() { return TULocalDeclsMap; }
4570};
4571
4572} // namespace
4573
4574namespace {
4575class LazySpecializationInfoLookupTrait {
4576 ASTWriter &Writer;
4577 llvm::SmallVector<serialization::reader::LazySpecializationInfo, 64> Specs;
4578
4579public:
4580 using key_type = unsigned;
4581 using key_type_ref = key_type;
4582
4583 /// A start and end index into Specs, representing a sequence of decls.
4584 using data_type = std::pair<unsigned, unsigned>;
4585 using data_type_ref = const data_type &;
4586
4587 using hash_value_type = unsigned;
4588 using offset_type = unsigned;
4589
4590 explicit LazySpecializationInfoLookupTrait(ASTWriter &Writer)
4591 : Writer(Writer) {}
4592
4593 template <typename Col, typename Col2>
4594 data_type getData(Col &&C, Col2 &ExistingInfo) {
4595 unsigned Start = Specs.size();
4596 for (auto *D : C) {
4597 NamedDecl *ND = getDeclForLocalLookup(Writer.getLangOpts(),
4598 const_cast<NamedDecl *>(D));
4599 Specs.push_back(GlobalDeclID(Writer.GetDeclRef(ND).getRawValue()));
4600 }
4602 ExistingInfo)
4603 Specs.push_back(Info);
4604 return std::make_pair(Start, Specs.size());
4605 }
4606
4607 data_type ImportData(
4609 unsigned Start = Specs.size();
4610 for (auto ID : FromReader)
4611 Specs.push_back(ID);
4612 return std::make_pair(Start, Specs.size());
4613 }
4614
4615 static bool EqualKey(key_type_ref a, key_type_ref b) { return a == b; }
4616
4617 hash_value_type ComputeHash(key_type Name) { return Name; }
4618
4619 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
4620 assert(Writer.hasChain() &&
4621 "have reference to loaded module file but no chain?");
4622
4623 using namespace llvm::support;
4624 Writer.addTouchedModuleFile(F);
4625 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F),
4626 llvm::endianness::little);
4627 }
4628
4629 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
4630 key_type HashValue,
4631 data_type_ref Lookup) {
4632 // 4 bytes for each slot.
4633 unsigned KeyLen = 4;
4634 unsigned DataLen = sizeof(serialization::reader::LazySpecializationInfo) *
4635 (Lookup.second - Lookup.first);
4636
4637 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
4638 }
4639
4640 void EmitKey(raw_ostream &Out, key_type HashValue, unsigned) {
4641 using namespace llvm::support;
4642
4643 endian::Writer LE(Out, llvm::endianness::little);
4644 LE.write<uint32_t>(HashValue);
4645 }
4646
4647 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
4648 unsigned DataLen) {
4649 using namespace llvm::support;
4650
4651 endian::Writer LE(Out, llvm::endianness::little);
4652 uint64_t Start = Out.tell();
4653 (void)Start;
4654 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I) {
4655 LE.write<DeclID>(Specs[I].getRawValue());
4656 }
4657 assert(Out.tell() - Start == DataLen && "Data length is wrong");
4658 }
4659};
4660
4661unsigned CalculateODRHashForSpecs(const Decl *Spec) {
4662 ArrayRef<TemplateArgument> Args;
4663 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Spec))
4664 Args = CTSD->getTemplateArgs().asArray();
4665 else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Spec))
4666 Args = VTSD->getTemplateArgs().asArray();
4667 else if (auto *FD = dyn_cast<FunctionDecl>(Spec))
4668 Args = FD->getTemplateSpecializationArgs()->asArray();
4669 else
4670 llvm_unreachable("New Specialization Kind?");
4671
4672 return StableHashForTemplateArguments(Args);
4673}
4674} // namespace
4675
4676void ASTWriter::GenerateSpecializationInfoLookupTable(
4677 const NamedDecl *D, llvm::SmallVectorImpl<const Decl *> &Specializations,
4678 llvm::SmallVectorImpl<char> &LookupTable, bool IsPartial) {
4679 assert(D->isFirstDecl());
4680
4681 // Create the on-disk hash table representation.
4682 MultiOnDiskHashTableGenerator<reader::LazySpecializationInfoLookupTrait,
4683 LazySpecializationInfoLookupTrait>
4684 Generator;
4685 LazySpecializationInfoLookupTrait Trait(*this);
4686
4687 llvm::MapVector<unsigned, llvm::SmallVector<const NamedDecl *, 4>>
4688 SpecializationMaps;
4689
4690 for (auto *Specialization : Specializations) {
4691 unsigned HashedValue = CalculateODRHashForSpecs(Specialization);
4692
4693 auto Iter = SpecializationMaps.find(HashedValue);
4694 if (Iter == SpecializationMaps.end())
4695 Iter = SpecializationMaps
4696 .try_emplace(HashedValue,
4697 llvm::SmallVector<const NamedDecl *, 4>())
4698 .first;
4699
4700 Iter->second.push_back(cast<NamedDecl>(Specialization));
4701 }
4702
4703 auto *Lookups =
4704 Chain ? Chain->getLoadedSpecializationsLookupTables(D, IsPartial)
4705 : nullptr;
4706
4707 for (auto &[HashValue, Specs] : SpecializationMaps) {
4708 SmallVector<serialization::reader::LazySpecializationInfo, 16>
4709 ExisitingSpecs;
4710 // We have to merge the lookup table manually here. We can't depend on the
4711 // merge mechanism offered by
4712 // clang::serialization::MultiOnDiskHashTableGenerator since that generator
4713 // assumes the we'll get the same value with the same key.
4714 // And also underlying llvm::OnDiskChainedHashTableGenerator assumes that we
4715 // won't insert the values with the same key twice. So we have to merge the
4716 // lookup table here manually.
4717 if (Lookups)
4718 ExisitingSpecs = Lookups->Table.find(HashValue);
4719
4720 Generator.insert(HashValue, Trait.getData(Specs, ExisitingSpecs), Trait);
4721 }
4722
4723 // Reduced BMI may not emit everything in the lookup table,
4724 // If Reduced BMI **partially** emits some decls,
4725 // then the generator may not emit the corresponding entry for the
4726 // corresponding name is already there. See
4727 // MultiOnDiskHashTableGenerator::insert and
4728 // MultiOnDiskHashTableGenerator::emit for details.
4729 // So we won't emit the lookup table if we're generating reduced BMI.
4730 auto *ToEmitMaybeMergedLookupTable =
4731 (!isGeneratingReducedBMI() && Lookups) ? &Lookups->Table : nullptr;
4732 Generator.emit(LookupTable, Trait, ToEmitMaybeMergedLookupTable);
4733}
4734
4735uint64_t ASTWriter::WriteSpecializationInfoLookupTable(
4736 const NamedDecl *D, llvm::SmallVectorImpl<const Decl *> &Specializations,
4737 bool IsPartial) {
4738
4739 llvm::SmallString<4096> LookupTable;
4740 GenerateSpecializationInfoLookupTable(D, Specializations, LookupTable,
4741 IsPartial);
4742
4743 uint64_t Offset = Stream.GetCurrentBitNo();
4744 RecordData::value_type Record[] = {static_cast<RecordData::value_type>(
4746 Stream.EmitRecordWithBlob(IsPartial ? DeclPartialSpecializationsAbbrev
4747 : DeclSpecializationsAbbrev,
4748 Record, LookupTable);
4749
4750 return Offset;
4751}
4752
4753/// Returns true if all of the lookup result are either external, not emitted or
4754/// predefined. In such cases, the lookup result is not interesting and we don't
4755/// need to record the result in the current being written module. Return false
4756/// otherwise.
4759 for (auto *D : Result.getLookupResult()) {
4760 auto *LocalD = getDeclForLocalLookup(Writer.getLangOpts(), D);
4761 if (LocalD->isFromASTFile())
4762 continue;
4763
4764 // We can only be sure whether the local declaration is reachable
4765 // after we done writing the declarations and types.
4766 if (Writer.getDoneWritingDeclsAndTypes() && !Writer.wasDeclEmitted(LocalD))
4767 continue;
4768
4769 // We don't need to emit the predefined decls.
4770 if (Writer.isDeclPredefined(LocalD))
4771 continue;
4772
4773 return false;
4774 }
4775
4776 return true;
4777}
4778
4779void ASTWriter::GenerateNameLookupTable(
4780 ASTContext &Context, const DeclContext *ConstDC,
4781 llvm::SmallVectorImpl<char> &LookupTable,
4782 llvm::SmallVectorImpl<char> &ModuleLocalLookupTable,
4783 llvm::SmallVectorImpl<char> &TULookupTable) {
4784 assert(!ConstDC->hasLazyLocalLexicalLookups() &&
4785 !ConstDC->hasLazyExternalLexicalLookups() &&
4786 "must call buildLookups first");
4787
4788 // FIXME: We need to build the lookups table, which is logically const.
4789 auto *DC = const_cast<DeclContext*>(ConstDC);
4790 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
4791
4792 // Create the on-disk hash table representation.
4793 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
4794 ASTDeclContextNameLookupTrait>
4795 Generator;
4796 ASTDeclContextNameLookupTrait Trait(*this, *DC);
4797
4798 // The first step is to collect the declaration names which we need to
4799 // serialize into the name lookup table, and to collect them in a stable
4800 // order.
4801 SmallVector<DeclarationName, 16> Names;
4802
4803 // We also track whether we're writing out the DeclarationNameKey for
4804 // constructors or conversion functions.
4805 bool IncludeConstructorNames = false;
4806 bool IncludeConversionNames = false;
4807
4808 for (auto &[Name, Result] : *DC->buildLookup()) {
4809 // If there are no local declarations in our lookup result, we
4810 // don't need to write an entry for the name at all. If we can't
4811 // write out a lookup set without performing more deserialization,
4812 // just skip this entry.
4813 //
4814 // Also in reduced BMI, we'd like to avoid writing unreachable
4815 // declarations in GMF, so we need to avoid writing declarations
4816 // that entirely external or unreachable.
4817 if (GeneratingReducedBMI && isLookupResultNotInteresting(*this, Result))
4818 continue;
4819 // We also skip empty results. If any of the results could be external and
4820 // the currently available results are empty, then all of the results are
4821 // external and we skip it above. So the only way we get here with an empty
4822 // results is when no results could have been external *and* we have
4823 // external results.
4824 //
4825 // FIXME: While we might want to start emitting on-disk entries for negative
4826 // lookups into a decl context as an optimization, today we *have* to skip
4827 // them because there are names with empty lookup results in decl contexts
4828 // which we can't emit in any stable ordering: we lookup constructors and
4829 // conversion functions in the enclosing namespace scope creating empty
4830 // results for them. This in almost certainly a bug in Clang's name lookup,
4831 // but that is likely to be hard or impossible to fix and so we tolerate it
4832 // here by omitting lookups with empty results.
4833 if (Result.getLookupResult().empty())
4834 continue;
4835
4836 switch (Name.getNameKind()) {
4837 default:
4838 Names.push_back(Name);
4839 break;
4840
4842 IncludeConstructorNames = true;
4843 break;
4844
4846 IncludeConversionNames = true;
4847 break;
4848 }
4849 }
4850
4851 // Sort the names into a stable order.
4852 llvm::sort(Names);
4853
4854 if (IncludeConstructorNames || IncludeConversionNames) {
4855 // We need to establish an ordering of constructor and conversion function
4856 // names, and they don't have an intrinsic ordering. We also need to write
4857 // out all constructor and conversion function results if we write out any
4858 // of them, because they're all tracked under the same lookup key.
4859 llvm::SmallPtrSet<DeclarationName, 8> AddedNames;
4860 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls()) {
4861 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4862 auto Name = ChildND->getDeclName();
4863 switch (Name.getNameKind()) {
4864 default:
4865 continue;
4866
4868 if (!IncludeConstructorNames)
4869 continue;
4870 break;
4871
4873 if (!IncludeConversionNames)
4874 continue;
4875 break;
4876 }
4877 if (AddedNames.insert(Name).second)
4878 Names.push_back(Name);
4879 }
4880 }
4881 }
4882 // Next we need to do a lookup with each name into this decl context to fully
4883 // populate any results from external sources. We don't actually use the
4884 // results of these lookups because we only want to use the results after all
4885 // results have been loaded and the pointers into them will be stable.
4886 for (auto &Name : Names)
4887 DC->lookup(Name);
4888
4889 // Now we need to insert the results for each name into the hash table. For
4890 // constructor names and conversion function names, we actually need to merge
4891 // all of the results for them into one list of results each and insert
4892 // those.
4893 SmallVector<NamedDecl *, 8> ConstructorDecls;
4894 SmallVector<NamedDecl *, 8> ConversionDecls;
4895
4896 // Now loop over the names, either inserting them or appending for the two
4897 // special cases.
4898 for (auto &Name : Names) {
4900
4901 switch (Name.getNameKind()) {
4902 default:
4903 Generator.insert(Name, Trait.getData(Result), Trait);
4904 break;
4905
4907 ConstructorDecls.append(Result.begin(), Result.end());
4908 break;
4909
4911 ConversionDecls.append(Result.begin(), Result.end());
4912 break;
4913 }
4914 }
4915
4916 // Handle our two special cases if we ended up having any. We arbitrarily use
4917 // the first declaration's name here because the name itself isn't part of
4918 // the key, only the kind of name is used.
4919 if (!ConstructorDecls.empty())
4920 Generator.insert(ConstructorDecls.front()->getDeclName(),
4921 Trait.getData(ConstructorDecls), Trait);
4922 if (!ConversionDecls.empty())
4923 Generator.insert(ConversionDecls.front()->getDeclName(),
4924 Trait.getData(ConversionDecls), Trait);
4925
4926 // Create the on-disk hash table. Also emit the existing imported and
4927 // merged table if there is one.
4928 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4929 // Reduced BMI may not emit everything in the lookup table,
4930 // If Reduced BMI **partially** emits some decls,
4931 // then the generator may not emit the corresponding entry for the
4932 // corresponding name is already there. See
4933 // MultiOnDiskHashTableGenerator::insert and
4934 // MultiOnDiskHashTableGenerator::emit for details.
4935 // So we won't emit the lookup table if we're generating reduced BMI.
4936 auto *ToEmitMaybeMergedLookupTable =
4937 (!isGeneratingReducedBMI() && Lookups) ? &Lookups->Table : nullptr;
4938 Generator.emit(LookupTable, Trait, ToEmitMaybeMergedLookupTable);
4939
4940 const auto &ModuleLocalDecls = Trait.getModuleLocalDecls();
4941 if (!ModuleLocalDecls.empty()) {
4942 MultiOnDiskHashTableGenerator<reader::ModuleLocalNameLookupTrait,
4943 ModuleLevelNameLookupTrait>
4944 ModuleLocalLookupGenerator;
4945 ModuleLevelNameLookupTrait ModuleLocalTrait(*this);
4946
4947 for (const auto &ModuleLocalIter : ModuleLocalDecls) {
4948 const auto &Key = ModuleLocalIter.first;
4949 const auto &IDs = ModuleLocalIter.second;
4950 ModuleLocalLookupGenerator.insert(Key, ModuleLocalTrait.getData(IDs),
4951 ModuleLocalTrait);
4952 }
4953
4954 // See the above comment. We won't emit the merged table if we're generating
4955 // reduced BMI.
4956 auto *ModuleLocalLookups =
4957 (isGeneratingReducedBMI() && Chain &&
4958 Chain->getModuleLocalLookupTables(DC))
4959 ? &Chain->getModuleLocalLookupTables(DC)->Table
4960 : nullptr;
4961 ModuleLocalLookupGenerator.emit(ModuleLocalLookupTable, ModuleLocalTrait,
4962 ModuleLocalLookups);
4963 }
4964
4965 const auto &TULocalDecls = Trait.getTULocalDecls();
4966 if (!TULocalDecls.empty() && !isGeneratingReducedBMI()) {
4967 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
4968 ASTDeclContextNameTrivialLookupTrait>
4969 TULookupGenerator;
4970 ASTDeclContextNameTrivialLookupTrait TULocalTrait(*this);
4971
4972 for (const auto &TULocalIter : TULocalDecls) {
4973 const auto &Key = TULocalIter.first;
4974 const auto &IDs = TULocalIter.second;
4975 TULookupGenerator.insert(Key, TULocalTrait.getData(IDs), TULocalTrait);
4976 }
4977
4978 // See the above comment. We won't emit the merged table if we're generating
4979 // reduced BMI.
4980 auto *TULocalLookups =
4981 (isGeneratingReducedBMI() && Chain && Chain->getTULocalLookupTables(DC))
4982 ? &Chain->getTULocalLookupTables(DC)->Table
4983 : nullptr;
4984 TULookupGenerator.emit(TULookupTable, TULocalTrait, TULocalLookups);
4985 }
4986}
4987
4988/// Write the block containing all of the declaration IDs
4989/// visible from the given DeclContext.
4990///
4991/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4992/// bitstream, or 0 if no block was written.
4993void ASTWriter::WriteDeclContextVisibleBlock(
4994 ASTContext &Context, DeclContext *DC, VisibleLookupBlockOffsets &Offsets) {
4995 assert(!Offsets);
4996
4997 // If we imported a key declaration of this namespace, write the visible
4998 // lookup results as an update record for it rather than including them
4999 // on this declaration. We will only look at key declarations on reload.
5000 if (isa<NamespaceDecl>(DC) && Chain &&
5002 // Only do this once, for the first local declaration of the namespace.
5003 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
5004 Prev = Prev->getPreviousDecl())
5005 if (!Prev->isFromASTFile())
5006 return;
5007
5008 // Note that we need to emit an update record for the primary context.
5009 UpdatedDeclContexts.insert(DC->getPrimaryContext());
5010
5011 // Make sure all visible decls are written. They will be recorded later. We
5012 // do this using a side data structure so we can sort the names into
5013 // a deterministic order.
5014 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
5015 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
5016 LookupResults;
5017 if (Map) {
5018 LookupResults.reserve(Map->size());
5019 for (auto &Entry : *Map)
5020 LookupResults.push_back(
5021 std::make_pair(Entry.first, Entry.second.getLookupResult()));
5022 }
5023
5024 llvm::sort(LookupResults, llvm::less_first());
5025 for (auto &NameAndResult : LookupResults) {
5026 DeclarationName Name = NameAndResult.first;
5027 DeclContext::lookup_result Result = NameAndResult.second;
5030 // We have to work around a name lookup bug here where negative lookup
5031 // results for these names get cached in namespace lookup tables (these
5032 // names should never be looked up in a namespace).
5033 assert(Result.empty() && "Cannot have a constructor or conversion "
5034 "function name in a namespace!");
5035 continue;
5036 }
5037
5038 for (NamedDecl *ND : Result) {
5039 if (ND->isFromASTFile())
5040 continue;
5041
5042 if (DoneWritingDeclsAndTypes && !wasDeclEmitted(ND))
5043 continue;
5044
5045 // We don't need to force emitting internal decls into reduced BMI.
5046 // See comments in ASTWriter::WriteDeclContextLexicalBlock for details.
5047 if (GeneratingReducedBMI && !ND->isFromExplicitGlobalModule() &&
5049 continue;
5050
5051 GetDeclRef(ND);
5052 }
5053 }
5054
5055 return;
5056 }
5057
5058 if (DC->getPrimaryContext() != DC)
5059 return;
5060
5061 // Skip contexts which don't support name lookup.
5062 if (!DC->isLookupContext())
5063 return;
5064
5065 // If not in C++, we perform name lookup for the translation unit via the
5066 // IdentifierInfo chains, don't bother to build a visible-declarations table.
5067 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
5068 return;
5069
5070 // Serialize the contents of the mapping used for lookup. Note that,
5071 // although we have two very different code paths, the serialized
5072 // representation is the same for both cases: a declaration name,
5073 // followed by a size, followed by references to the visible
5074 // declarations that have that name.
5075 StoredDeclsMap *Map = DC->buildLookup();
5076 if (!Map || Map->empty())
5077 return;
5078
5079 Offsets.VisibleOffset = Stream.GetCurrentBitNo();
5080 // Create the on-disk hash table in a buffer.
5081 SmallString<4096> LookupTable;
5082 SmallString<4096> ModuleLocalLookupTable;
5083 SmallString<4096> TULookupTable;
5084 GenerateNameLookupTable(Context, DC, LookupTable, ModuleLocalLookupTable,
5085 TULookupTable);
5086
5087 // Write the lookup table
5088 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
5089 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
5090 LookupTable);
5091 ++NumVisibleDeclContexts;
5092
5093 if (!ModuleLocalLookupTable.empty()) {
5094 Offsets.ModuleLocalOffset = Stream.GetCurrentBitNo();
5095 assert(Offsets.ModuleLocalOffset > Offsets.VisibleOffset);
5096 // Write the lookup table
5097 RecordData::value_type ModuleLocalRecord[] = {
5099 Stream.EmitRecordWithBlob(DeclModuleLocalVisibleLookupAbbrev,
5100 ModuleLocalRecord, ModuleLocalLookupTable);
5101 ++NumModuleLocalDeclContexts;
5102 }
5103
5104 if (!TULookupTable.empty()) {
5105 Offsets.TULocalOffset = Stream.GetCurrentBitNo();
5106 // Write the lookup table
5107 RecordData::value_type TULocalDeclsRecord[] = {
5109 Stream.EmitRecordWithBlob(DeclTULocalLookupAbbrev, TULocalDeclsRecord,
5110 TULookupTable);
5111 ++NumTULocalDeclContexts;
5112 }
5113}
5114
5115/// Write an UPDATE_VISIBLE block for the given context.
5116///
5117/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
5118/// DeclContext in a dependent AST file. As such, they only exist for the TU
5119/// (in C++), for namespaces, and for classes with forward-declared unscoped
5120/// enumeration members (in C++11).
5121void ASTWriter::WriteDeclContextVisibleUpdate(ASTContext &Context,
5122 const DeclContext *DC) {
5123 StoredDeclsMap *Map = DC->getLookupPtr();
5124 if (!Map || Map->empty())
5125 return;
5126
5127 // Create the on-disk hash table in a buffer.
5128 SmallString<4096> LookupTable;
5129 SmallString<4096> ModuleLocalLookupTable;
5130 SmallString<4096> TULookupTable;
5131 GenerateNameLookupTable(Context, DC, LookupTable, ModuleLocalLookupTable,
5132 TULookupTable);
5133
5134 // If we're updating a namespace, select a key declaration as the key for the
5135 // update record; those are the only ones that will be checked on reload.
5136 if (isa<NamespaceDecl>(DC))
5138
5139 // Write the lookup table
5140 RecordData::value_type Record[] = {UPDATE_VISIBLE,
5141 getDeclID(cast<Decl>(DC)).getRawValue()};
5142 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
5143
5144 if (!ModuleLocalLookupTable.empty()) {
5145 // Write the module local lookup table
5146 RecordData::value_type ModuleLocalRecord[] = {
5147 UPDATE_MODULE_LOCAL_VISIBLE, getDeclID(cast<Decl>(DC)).getRawValue()};
5148 Stream.EmitRecordWithBlob(ModuleLocalUpdateVisibleAbbrev, ModuleLocalRecord,
5149 ModuleLocalLookupTable);
5150 }
5151
5152 if (!TULookupTable.empty()) {
5153 RecordData::value_type GMFRecord[] = {
5154 UPDATE_TU_LOCAL_VISIBLE, getDeclID(cast<Decl>(DC)).getRawValue()};
5155 Stream.EmitRecordWithBlob(TULocalUpdateVisibleAbbrev, GMFRecord,
5156 TULookupTable);
5157 }
5158}
5159
5160/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
5161void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) {
5162 RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
5163 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
5164}
5165
5166/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
5167void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
5168 if (!SemaRef.Context.getLangOpts().OpenCL)
5169 return;
5170
5171 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
5172 RecordData Record;
5173 for (const auto &I:Opts.OptMap) {
5174 AddString(I.getKey(), Record);
5175 auto V = I.getValue();
5176 Record.push_back(V.Supported ? 1 : 0);
5177 Record.push_back(V.Enabled ? 1 : 0);
5178 Record.push_back(V.WithPragma ? 1 : 0);
5179 Record.push_back(V.Avail);
5180 Record.push_back(V.Core);
5181 Record.push_back(V.Opt);
5182 }
5183 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
5184}
5185void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
5186 if (SemaRef.CUDA().ForceHostDeviceDepth > 0) {
5187 RecordData::value_type Record[] = {SemaRef.CUDA().ForceHostDeviceDepth};
5188 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
5189 }
5190}
5191
5192void ASTWriter::WriteObjCCategories() {
5193 if (ObjCClassesWithCategories.empty())
5194 return;
5195
5196 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
5197 RecordData Categories;
5198
5199 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
5200 unsigned Size = 0;
5201 unsigned StartIndex = Categories.size();
5202
5203 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
5204
5205 // Allocate space for the size.
5206 Categories.push_back(0);
5207
5208 // Add the categories.
5210 Cat = Class->known_categories_begin(),
5211 CatEnd = Class->known_categories_end();
5212 Cat != CatEnd; ++Cat, ++Size) {
5213 assert(getDeclID(*Cat).isValid() && "Bogus category");
5214 AddDeclRef(*Cat, Categories);
5215 }
5216
5217 // Update the size.
5218 Categories[StartIndex] = Size;
5219
5220 // Record this interface -> category map.
5221 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
5222 CategoriesMap.push_back(CatInfo);
5223 }
5224
5225 // Sort the categories map by the definition ID, since the reader will be
5226 // performing binary searches on this information.
5227 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
5228
5229 // Emit the categories map.
5230 using namespace llvm;
5231
5232 auto Abbrev = std::make_shared<BitCodeAbbrev>();
5233 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
5234 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
5235 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
5236 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
5237
5238 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
5239 Stream.EmitRecordWithBlob(AbbrevID, Record,
5240 reinterpret_cast<char *>(CategoriesMap.data()),
5241 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
5242
5243 // Emit the category lists.
5244 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
5245}
5246
5247void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
5249
5250 if (LPTMap.empty())
5251 return;
5252
5253 RecordData Record;
5254 for (auto &LPTMapEntry : LPTMap) {
5255 const FunctionDecl *FD = LPTMapEntry.first;
5256 LateParsedTemplate &LPT = *LPTMapEntry.second;
5257 AddDeclRef(FD, Record);
5258 AddDeclRef(LPT.D, Record);
5259 Record.push_back(LPT.FPO.getAsOpaqueInt());
5260 Record.push_back(LPT.Toks.size());
5261
5262 for (const auto &Tok : LPT.Toks) {
5263 AddToken(Tok, Record);
5264 }
5265 }
5266 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
5267}
5268
5269/// Write the state of 'pragma clang optimize' at the end of the module.
5270void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
5271 RecordData Record;
5272 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
5273 AddSourceLocation(PragmaLoc, Record);
5274 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
5275}
5276
5277/// Write the state of 'pragma ms_struct' at the end of the module.
5278void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
5279 RecordData Record;
5280 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
5281 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
5282}
5283
5284/// Write the state of 'pragma pointers_to_members' at the end of the
5285//module.
5286void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
5287 RecordData Record;
5289 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
5290 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
5291}
5292
5293/// Write the state of 'pragma align/pack' at the end of the module.
5294void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
5295 // Don't serialize pragma align/pack state for modules, since it should only
5296 // take effect on a per-submodule basis.
5297 if (WritingModule)
5298 return;
5299
5300 RecordData Record;
5301 AddAlignPackInfo(SemaRef.AlignPackStack.CurrentValue, Record);
5302 AddSourceLocation(SemaRef.AlignPackStack.CurrentPragmaLocation, Record);
5303 Record.push_back(SemaRef.AlignPackStack.Stack.size());
5304 for (const auto &StackEntry : SemaRef.AlignPackStack.Stack) {
5305 AddAlignPackInfo(StackEntry.Value, Record);
5306 AddSourceLocation(StackEntry.PragmaLocation, Record);
5307 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
5308 AddString(StackEntry.StackSlotLabel, Record);
5309 }
5310 Stream.EmitRecord(ALIGN_PACK_PRAGMA_OPTIONS, Record);
5311}
5312
5313/// Write the state of 'pragma float_control' at the end of the module.
5314void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
5315 // Don't serialize pragma float_control state for modules,
5316 // since it should only take effect on a per-submodule basis.
5317 if (WritingModule)
5318 return;
5319
5320 RecordData Record;
5321 Record.push_back(SemaRef.FpPragmaStack.CurrentValue.getAsOpaqueInt());
5322 AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
5323 Record.push_back(SemaRef.FpPragmaStack.Stack.size());
5324 for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
5325 Record.push_back(StackEntry.Value.getAsOpaqueInt());
5326 AddSourceLocation(StackEntry.PragmaLocation, Record);
5327 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
5328 AddString(StackEntry.StackSlotLabel, Record);
5329 }
5330 Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
5331}
5332
5333/// Write Sema's collected list of declarations with unverified effects.
5334void ASTWriter::WriteDeclsWithEffectsToVerify(Sema &SemaRef) {
5335 if (SemaRef.DeclsWithEffectsToVerify.empty())
5336 return;
5337 RecordData Record;
5338 for (const auto *D : SemaRef.DeclsWithEffectsToVerify) {
5339 AddDeclRef(D, Record);
5340 }
5341 Stream.EmitRecord(DECLS_WITH_EFFECTS_TO_VERIFY, Record);
5342}
5343
5344/// Write the OpenMP 'requires' directives seen in this translation unit.
5345void ASTWriter::WriteOpenMPRequiresDecls(Sema &SemaRef) {
5346 ArrayRef<const OMPRequiresDecl *> Decls = SemaRef.OpenMP().getRequiresDecls();
5347 if (Decls.empty())
5348 return;
5349 RecordData Record;
5350 for (const OMPRequiresDecl *D : Decls)
5351 if (!D->isFromASTFile())
5352 AddDeclRef(D, Record);
5353 if (!Record.empty())
5354 Stream.EmitRecord(OMP_REQUIRES_DECLS, Record);
5355}
5356
5357void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
5358 ModuleFileExtensionWriter &Writer) {
5359 // Enter the extension block.
5360 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
5361
5362 // Emit the metadata record abbreviation.
5363 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
5364 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
5365 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5366 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5367 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5368 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5369 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
5370 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
5371
5372 // Emit the metadata record.
5373 RecordData Record;
5374 auto Metadata = Writer.getExtension()->getExtensionMetadata();
5375 Record.push_back(EXTENSION_METADATA);
5376 Record.push_back(Metadata.MajorVersion);
5377 Record.push_back(Metadata.MinorVersion);
5378 Record.push_back(Metadata.BlockName.size());
5379 Record.push_back(Metadata.UserInfo.size());
5380 SmallString<64> Buffer;
5381 Buffer += Metadata.BlockName;
5382 Buffer += Metadata.UserInfo;
5383 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
5384
5385 // Emit the contents of the extension block.
5386 Writer.writeExtensionContents(SemaRef, Stream);
5387
5388 // Exit the extension block.
5389 Stream.ExitBlock();
5390}
5391
5392void ASTWriter::WriteRISCVIntrinsicPragmas(Sema &SemaRef) {
5393 RecordData Record;
5394 // Need to update this when new intrinsic class is added.
5395 Record.push_back(/*size*/ 3);
5396 Record.push_back(SemaRef.RISCV().DeclareRVVBuiltins);
5397 Record.push_back(SemaRef.RISCV().DeclareSiFiveVectorBuiltins);
5398 Record.push_back(SemaRef.RISCV().DeclareAndesVectorBuiltins);
5399 Stream.EmitRecord(RISCV_VECTOR_INTRINSICS_PRAGMA, Record);
5400}
5401
5402//===----------------------------------------------------------------------===//
5403// General Serialization Routines
5404//===----------------------------------------------------------------------===//
5405
5407 auto &Record = *this;
5408 // FIXME: Clang can't handle the serialization/deserialization of
5409 // preferred_name properly now. See
5410 // https://github.com/llvm/llvm-project/issues/56490 for example.
5411 if (!A ||
5412 (isa<PreferredNameAttr>(A) && (Writer->isWritingStdCXXNamedModules() ||
5413 Writer->isWritingStdCXXHeaderUnit())))
5414 return Record.push_back(0);
5415
5416 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
5417
5418 Record.AddIdentifierRef(A->getAttrName());
5419 Record.AddIdentifierRef(A->getScopeName());
5420 Record.AddSourceRange(A->getRange());
5421 Record.AddSourceLocation(A->getScopeLoc());
5422 Record.push_back(A->getParsedKind());
5423 Record.push_back(A->getSyntax());
5424 Record.push_back(A->getAttributeSpellingListIndexRaw());
5425 Record.push_back(A->isRegularKeywordAttribute());
5426
5427#include "clang/Serialization/AttrPCHWrite.inc"
5428}
5429
5430/// Emit the list of attributes to the specified record.
5432 push_back(Attrs.size());
5433 for (const auto *A : Attrs)
5434 AddAttr(A);
5435}
5436
5438 AddSourceLocation(Tok.getLocation(), Record);
5439 // FIXME: Should translate token kind to a stable encoding.
5440 Record.push_back(Tok.getKind());
5441 // FIXME: Should translate token flags to a stable encoding.
5442 Record.push_back(Tok.getFlags());
5443
5444 if (Tok.isAnnotation()) {
5445 AddSourceLocation(Tok.getAnnotationEndLoc(), Record);
5446 switch (Tok.getKind()) {
5447 case tok::annot_pragma_loop_hint: {
5448 auto *Info = static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
5449 AddToken(Info->PragmaName, Record);
5450 AddToken(Info->Option, Record);
5451 Record.push_back(Info->Toks.size());
5452 for (const auto &T : Info->Toks)
5453 AddToken(T, Record);
5454 break;
5455 }
5456 case tok::annot_pragma_pack: {
5457 auto *Info =
5458 static_cast<Sema::PragmaPackInfo *>(Tok.getAnnotationValue());
5459 Record.push_back(static_cast<unsigned>(Info->Action));
5460 AddString(Info->SlotLabel, Record);
5461 AddToken(Info->Alignment, Record);
5462 break;
5463 }
5464 // Some annotation tokens do not use the PtrData field.
5465 case tok::annot_pragma_openmp:
5466 case tok::annot_pragma_openmp_end:
5467 case tok::annot_pragma_unused:
5468 case tok::annot_pragma_openacc:
5469 case tok::annot_pragma_openacc_end:
5470 break;
5471 default:
5472 llvm_unreachable("missing serialization code for annotation token");
5473 }
5474 } else {
5475 Record.push_back(Tok.getLength());
5476 // FIXME: When reading literal tokens, reconstruct the literal pointer if it
5477 // is needed.
5478 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
5479 }
5480}
5481
5483 Record.push_back(Str.size());
5484 llvm::append_range(Record, Str);
5485}
5486
5488 SmallVectorImpl<char> &Blob) {
5489 Record.push_back(Str.size());
5490 llvm::append_range(Blob, Str);
5491}
5492
5494 assert(WritingAST && "can't prepare path for output when not writing AST");
5495
5496 // Leave special file names as they are.
5497 StringRef PathStr(Path.data(), Path.size());
5498 if (PathStr == "<built-in>" || PathStr == "<command line>")
5499 return false;
5500
5501 bool Changed =
5502 PP->getFileManager().makeAbsolutePath(Path, /*Canonicalize=*/true);
5503 // Remove a prefix to make the path relative, if relevant.
5504 Changed |= adjustFilenameForRelocatableAST(Path, BaseDirectory);
5505
5506 return Changed;
5507}
5508
5510 SmallString<128> FilePath(Path);
5511 PreparePathForOutput(FilePath);
5512 AddString(FilePath, Record);
5513}
5514
5516 SmallVectorImpl<char> &Blob) {
5517 SmallString<128> FilePath(Path);
5518 PreparePathForOutput(FilePath);
5519 AddStringBlob(FilePath, Record, Blob);
5520}
5521
5523 StringRef Path) {
5524 SmallString<128> FilePath(Path);
5525 PreparePathForOutput(FilePath);
5526 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
5527}
5528
5529void ASTWriter::AddVersionTuple(const VersionTuple &Version,
5531 Record.push_back(Version.getMajor());
5532 if (std::optional<unsigned> Minor = Version.getMinor())
5533 Record.push_back(*Minor + 1);
5534 else
5535 Record.push_back(0);
5536 if (std::optional<unsigned> Subminor = Version.getSubminor())
5537 Record.push_back(*Subminor + 1);
5538 else
5539 Record.push_back(0);
5540}
5541
5542/// Note that the identifier II occurs at the given offset
5543/// within the identifier table.
5544void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
5545 IdentifierID ID = IdentifierIDs[II];
5546 // Only store offsets new to this AST file. Other identifier names are looked
5547 // up earlier in the chain and thus don't need an offset.
5548 if (!isLocalIdentifierID(ID))
5549 return;
5550
5551 // For local identifiers, the module file index must be 0.
5552
5553 assert(ID != 0);
5555 assert(ID < IdentifierOffsets.size());
5556 IdentifierOffsets[ID] = Offset;
5557}
5558
5559/// Note that the selector Sel occurs at the given offset
5560/// within the method pool/selector table.
5561void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
5562 unsigned ID = SelectorIDs[Sel];
5563 assert(ID && "Unknown selector");
5564 // Don't record offsets for selectors that are also available in a different
5565 // file.
5566 if (ID < FirstSelectorID)
5567 return;
5568 SelectorOffsets[ID - FirstSelectorID] = Offset;
5569}
5570
5571ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
5572 SmallVectorImpl<char> &Buffer, ModuleCache &ModCache,
5573 const CodeGenOptions &CodeGenOpts,
5574 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
5575 bool IncludeTimestamps, bool BuildingImplicitModule,
5576 bool GeneratingReducedBMI)
5577 : Stream(Stream), Buffer(Buffer), ModCache(ModCache),
5578 CodeGenOpts(CodeGenOpts), IncludeTimestamps(IncludeTimestamps),
5579 BuildingImplicitModule(BuildingImplicitModule),
5580 GeneratingReducedBMI(GeneratingReducedBMI) {
5581 for (const auto &Ext : Extensions) {
5582 if (auto Writer = Ext->createExtensionWriter(*this))
5583 ModuleFileExtensionWriters.push_back(std::move(Writer));
5584 }
5585}
5586
5587ASTWriter::~ASTWriter() = default;
5588
5590 assert(WritingAST && "can't determine lang opts when not writing AST");
5591 return PP->getLangOpts();
5592}
5593
5594time_t ASTWriter::getTimestampForOutput(time_t ModTime) const {
5595 return IncludeTimestamps ? ModTime : 0;
5596}
5597
5599ASTWriter::WriteAST(llvm::PointerUnion<Sema *, Preprocessor *> Subject,
5600 StringRef OutputFile, Module *WritingModule,
5601 StringRef isysroot) {
5602 llvm::TimeTraceScope scope("WriteAST", OutputFile);
5603 WritingAST = true;
5604
5605 Sema *SemaPtr = dyn_cast<Sema *>(Subject);
5606 Preprocessor &PPRef =
5607 SemaPtr ? SemaPtr->getPreprocessor() : *cast<Preprocessor *>(Subject);
5608
5609 ASTHasCompilerErrors = PPRef.getDiagnostics().hasUncompilableErrorOccurred();
5610
5611 // Emit the file header.
5612 Stream.Emit((unsigned)'C', 8);
5613 Stream.Emit((unsigned)'P', 8);
5614 Stream.Emit((unsigned)'C', 8);
5615 Stream.Emit((unsigned)'H', 8);
5616
5617 WriteBlockInfoBlock();
5618
5619 PP = &PPRef;
5620 this->WritingModule = WritingModule;
5621 ASTFileSignature Signature = WriteASTCore(SemaPtr, isysroot, WritingModule);
5622 PP = nullptr;
5623 this->WritingModule = nullptr;
5624 this->BaseDirectory.clear();
5625
5626 WritingAST = false;
5627
5628 return Signature;
5629}
5630
5631template<typename Vector>
5632static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec) {
5633 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
5634 I != E; ++I) {
5635 Writer.GetDeclRef(*I);
5636 }
5637}
5638
5639template <typename Vector>
5642 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
5643 I != E; ++I) {
5644 Writer.AddEmittedDeclRef(*I, Record);
5645 }
5646}
5647
5648void ASTWriter::computeNonAffectingInputFiles() {
5649 SourceManager &SrcMgr = PP->getSourceManager();
5650 unsigned N = SrcMgr.local_sloc_entry_size();
5651
5652 IsSLocAffecting.resize(N, true);
5653 IsSLocFileEntryAffecting.resize(N, true);
5654
5655 if (!WritingModule)
5656 return;
5657
5658 auto AffectingModuleMaps = GetAffectingModuleMaps(*PP, WritingModule);
5659
5660 unsigned FileIDAdjustment = 0;
5661 unsigned OffsetAdjustment = 0;
5662
5663 NonAffectingFileIDAdjustments.reserve(N);
5664 NonAffectingOffsetAdjustments.reserve(N);
5665
5666 NonAffectingFileIDAdjustments.push_back(FileIDAdjustment);
5667 NonAffectingOffsetAdjustments.push_back(OffsetAdjustment);
5668
5669 for (unsigned I = 1; I != N; ++I) {
5670 const SrcMgr::SLocEntry *SLoc = &SrcMgr.getLocalSLocEntry(I);
5671 FileID FID = FileID::get(I);
5672 assert(&SrcMgr.getSLocEntry(FID) == SLoc);
5673
5674 if (!SLoc->isFile())
5675 continue;
5676 const SrcMgr::FileInfo &File = SLoc->getFile();
5677 const SrcMgr::ContentCache *Cache = &File.getContentCache();
5678 if (!Cache->OrigEntry)
5679 continue;
5680
5681 // Don't prune anything other than module maps.
5682 if (!isModuleMap(File.getFileCharacteristic()))
5683 continue;
5684
5685 // Don't prune module maps if all are guaranteed to be affecting.
5686 if (!AffectingModuleMaps)
5687 continue;
5688
5689 // Don't prune module maps that are affecting.
5690 if (AffectingModuleMaps->DefinitionFileIDs.contains(FID))
5691 continue;
5692
5693 IsSLocAffecting[I] = false;
5694 IsSLocFileEntryAffecting[I] =
5695 AffectingModuleMaps->DefinitionFiles.contains(*Cache->OrigEntry);
5696
5697 FileIDAdjustment += 1;
5698 // Even empty files take up one element in the offset table.
5699 OffsetAdjustment += SrcMgr.getFileIDSize(FID) + 1;
5700
5701 // If the previous file was non-affecting as well, just extend its entry
5702 // with our information.
5703 if (!NonAffectingFileIDs.empty() &&
5704 NonAffectingFileIDs.back().ID == FID.ID - 1) {
5705 NonAffectingFileIDs.back() = FID;
5706 NonAffectingRanges.back().setEnd(SrcMgr.getLocForEndOfFile(FID));
5707 NonAffectingFileIDAdjustments.back() = FileIDAdjustment;
5708 NonAffectingOffsetAdjustments.back() = OffsetAdjustment;
5709 continue;
5710 }
5711
5712 NonAffectingFileIDs.push_back(FID);
5713 NonAffectingRanges.emplace_back(SrcMgr.getLocForStartOfFile(FID),
5714 SrcMgr.getLocForEndOfFile(FID));
5715 NonAffectingFileIDAdjustments.push_back(FileIDAdjustment);
5716 NonAffectingOffsetAdjustments.push_back(OffsetAdjustment);
5717 }
5718
5719 if (!PP->getHeaderSearchInfo().getHeaderSearchOpts().ModulesIncludeVFSUsage)
5720 return;
5721
5722 FileManager &FileMgr = PP->getFileManager();
5723 FileMgr.trackVFSUsage(true);
5724 // Lookup the paths in the VFS to trigger `-ivfsoverlay` usage tracking.
5725 for (StringRef Path :
5726 PP->getHeaderSearchInfo().getHeaderSearchOpts().VFSOverlayFiles)
5727 FileMgr.getVirtualFileSystem().exists(Path);
5728 for (unsigned I = 1; I != N; ++I) {
5729 if (IsSLocAffecting[I]) {
5730 const SrcMgr::SLocEntry *SLoc = &SrcMgr.getLocalSLocEntry(I);
5731 if (!SLoc->isFile())
5732 continue;
5733 const SrcMgr::FileInfo &File = SLoc->getFile();
5734 const SrcMgr::ContentCache *Cache = &File.getContentCache();
5735 if (!Cache->OrigEntry)
5736 continue;
5737 FileMgr.getVirtualFileSystem().exists(
5738 Cache->OrigEntry->getNameAsRequested());
5739 }
5740 }
5741 FileMgr.trackVFSUsage(false);
5742}
5743
5744void ASTWriter::prepareLazyUpdates() {
5745 // In C++20 named modules with reduced BMI, we only apply the update
5746 // if these updates are touched.
5747 if (!GeneratingReducedBMI)
5748 return;
5749
5750 DeclUpdateMap DeclUpdatesTmp;
5751 // Move updates to DeclUpdatesLazy but leave CXXAddedFunctionDefinition as is.
5752 // Since added function definition is critical to the AST. If we don't take
5753 // care of it, user might meet missing definition error at linking time.
5754 // Here we leave all CXXAddedFunctionDefinition unconditionally to avoid
5755 // potential issues.
5756 // TODO: Try to refine the strategy to handle CXXAddedFunctionDefinition
5757 // precisely.
5758 for (auto &DeclUpdate : DeclUpdates) {
5759 const Decl *D = DeclUpdate.first;
5760
5761 for (auto &Update : DeclUpdate.second) {
5762 DeclUpdateKind Kind = Update.getKind();
5763
5764 if (Kind == DeclUpdateKind::CXXAddedFunctionDefinition)
5765 DeclUpdatesTmp[D].push_back(
5766 ASTWriter::DeclUpdate(DeclUpdateKind::CXXAddedFunctionDefinition));
5767 else
5768 DeclUpdatesLazy[D].push_back(Update);
5769 }
5770 }
5771 DeclUpdates.swap(DeclUpdatesTmp);
5772
5773 UpdatedDeclContextsLazy.swap(UpdatedDeclContexts);
5774 // In reduced BMI, we don't have decls have to emit even if unreferenced.
5775 DeclsToEmitEvenIfUnreferenced.clear();
5776}
5777
5778void ASTWriter::PrepareWritingSpecialDecls(Sema &SemaRef) {
5779 ASTContext &Context = SemaRef.Context;
5780
5781 bool isModule = WritingModule != nullptr;
5782
5783 prepareLazyUpdates();
5784
5785 // Set up predefined declaration IDs.
5786 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
5787 if (D) {
5788 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
5789 DeclIDs[D] = ID;
5790 PredefinedDecls.insert(D);
5791 }
5792 };
5793 RegisterPredefDecl(Context.getTranslationUnitDecl(),
5795 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
5796 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
5797 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
5798 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
5800 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
5801 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
5802 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
5804 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
5805 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
5806 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
5808 RegisterPredefDecl(Context.BuiltinZOSVaListDecl,
5810 RegisterPredefDecl(Context.MSGuidTagDecl,
5812 RegisterPredefDecl(Context.MSTypeInfoTagDecl,
5814 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
5815 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
5817 RegisterPredefDecl(Context.CFConstantStringTagDecl,
5819#define BuiltinTemplate(BTName) \
5820 RegisterPredefDecl(Context.Decl##BTName, PREDEF_DECL##BTName##_ID);
5821#include "clang/Basic/BuiltinTemplates.inc"
5822
5823 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5824
5825 // Force all top level declarations to be emitted.
5826 //
5827 // We start emitting top level declarations from the module purview to
5828 // implement the eliding unreachable declaration feature.
5829 for (const auto *D : TU->noload_decls()) {
5830 if (D->isFromASTFile())
5831 continue;
5832
5833 if (GeneratingReducedBMI) {
5835 continue;
5836
5837 // Don't force emitting static entities.
5838 //
5839 // Technically, all static entities shouldn't be in reduced BMI. The
5840 // language also specifies that the program exposes TU-local entities
5841 // is ill-formed. However, in practice, there are a lot of projects
5842 // uses `static inline` in the headers. So we can't get rid of all
5843 // static entities in reduced BMI now.
5845 continue;
5846 }
5847
5848 // If we're writing C++ named modules, don't emit declarations which are
5849 // not from modules by default. They may be built in declarations (be
5850 // handled above) or implcit declarations (see the implementation of
5851 // `Sema::Initialize()` for example).
5853 D->isImplicit())
5854 continue;
5855
5856 GetDeclRef(D);
5857 }
5858
5859 if (GeneratingReducedBMI)
5860 return;
5861
5862 // Writing all of the tentative definitions in this file, in
5863 // TentativeDefinitions order. Generally, this record will be empty for
5864 // headers.
5866
5867 // Writing all of the file scoped decls in this file.
5868 if (!isModule)
5870
5871 // Writing all of the delegating constructors we still need
5872 // to resolve.
5873 if (!isModule)
5875
5876 // Writing all of the ext_vector declarations.
5877 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls);
5878
5879 // Writing all of the VTable uses information.
5880 if (!SemaRef.VTableUses.empty())
5881 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I)
5882 GetDeclRef(SemaRef.VTableUses[I].first);
5883
5884 // Writing all of the UnusedLocalTypedefNameCandidates in a deterministic
5885 // order.
5886 SmallVector<const TypedefNameDecl *, 4> UnusedLocalTypedefs;
5887 SemaRef.getSortedUnusedLocalTypedefNameCandidates(UnusedLocalTypedefs);
5888 for (const TypedefNameDecl *TD : UnusedLocalTypedefs)
5889 GetDeclRef(TD);
5890
5891 // Writing all of pending implicit instantiations.
5892 for (const auto &I : SemaRef.PendingInstantiations)
5893 GetDeclRef(I.first);
5894 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
5895 "There are local ones at end of translation unit!");
5896
5897 // Writing some declaration references.
5898 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
5899 GetDeclRef(SemaRef.getStdNamespace());
5900 GetDeclRef(SemaRef.getStdBadAlloc());
5901 GetDeclRef(SemaRef.getStdAlignValT());
5902 }
5903
5904 if (Context.getcudaConfigureCallDecl() ||
5906 Context.getcudaLaunchDeviceDecl()) {
5910 }
5911
5912 // Writing all of the known namespaces.
5913 for (const auto &I : SemaRef.KnownNamespaces)
5914 if (!I.second)
5915 GetDeclRef(I.first);
5916
5917 // Writing all used, undefined objects that require definitions.
5918 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
5920 for (const auto &I : Undefined)
5921 GetDeclRef(I.first);
5922
5923 // Writing all delete-expressions that we would like to
5924 // analyze later in AST.
5925 if (!isModule)
5926 for (const auto &DeleteExprsInfo :
5928 GetDeclRef(DeleteExprsInfo.first);
5929
5930 // Make sure visible decls, added to DeclContexts previously loaded from
5931 // an AST file, are registered for serialization. Likewise for template
5932 // specializations added to imported templates.
5933 for (const auto *I : DeclsToEmitEvenIfUnreferenced)
5934 GetDeclRef(I);
5935 DeclsToEmitEvenIfUnreferenced.clear();
5936
5937 // Make sure all decls associated with an identifier are registered for
5938 // serialization, if we're storing decls with identifiers.
5939 if (!WritingModule || !getLangOpts().CPlusPlus) {
5940 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
5941 for (const auto &ID : SemaRef.PP.getIdentifierTable()) {
5942 const IdentifierInfo *II = ID.second;
5943 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization() ||
5945 IIs.push_back(II);
5946 }
5947 // Sort the identifiers to visit based on their name.
5948 llvm::sort(IIs, llvm::deref<std::less<>>());
5949 const LangOptions &LangOpts = getLangOpts();
5950 for (const IdentifierInfo *II : IIs)
5951 for (NamedDecl *D : SemaRef.IdResolver.decls(II))
5952 GetDeclRef(getDeclForLocalLookup(LangOpts, D));
5953 }
5954
5955 // Write all of the DeclsToCheckForDeferredDiags.
5956 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
5957 GetDeclRef(D);
5958
5959 // Write all classes that need to emit the vtable definitions if required.
5961 for (CXXRecordDecl *RD : PendingEmittingVTables)
5962 GetDeclRef(RD);
5963 else
5964 PendingEmittingVTables.clear();
5965}
5966
5967void ASTWriter::WriteSpecialDeclRecords(Sema &SemaRef) {
5968 ASTContext &Context = SemaRef.Context;
5969
5970 bool isModule = WritingModule != nullptr;
5971
5972 // Write the record containing external, unnamed definitions.
5973 if (!EagerlyDeserializedDecls.empty())
5974 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
5975
5976 if (!ModularCodegenDecls.empty())
5977 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
5978
5979 // Write the record containing tentative definitions.
5980 RecordData TentativeDefinitions;
5982 TentativeDefinitions);
5983 if (!TentativeDefinitions.empty())
5984 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
5985
5986 // Write the record containing unused file scoped decls.
5987 RecordData UnusedFileScopedDecls;
5988 if (!isModule)
5990 UnusedFileScopedDecls);
5991 if (!UnusedFileScopedDecls.empty())
5992 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
5993
5994 // Write the record containing ext_vector type names.
5995 RecordData ExtVectorDecls;
5996 AddLazyVectorEmiitedDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
5997 if (!ExtVectorDecls.empty())
5998 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
5999
6000 // Write the record containing VTable uses information.
6001 RecordData VTableUses;
6002 if (!SemaRef.VTableUses.empty()) {
6003 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
6004 CXXRecordDecl *D = SemaRef.VTableUses[I].first;
6005 if (!wasDeclEmitted(D))
6006 continue;
6007
6008 AddDeclRef(D, VTableUses);
6009 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
6010 VTableUses.push_back(SemaRef.VTablesUsed[D]);
6011 }
6012 Stream.EmitRecord(VTABLE_USES, VTableUses);
6013 }
6014
6015 // Write the record containing potentially unused local typedefs, in a
6016 // deterministic order.
6017 RecordData UnusedLocalTypedefNameCandidates;
6018 SmallVector<const TypedefNameDecl *, 4> SortedCandidates;
6019 SemaRef.getSortedUnusedLocalTypedefNameCandidates(SortedCandidates);
6020 for (const TypedefNameDecl *TD : SortedCandidates)
6021 AddEmittedDeclRef(TD, UnusedLocalTypedefNameCandidates);
6022 if (!UnusedLocalTypedefNameCandidates.empty())
6023 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
6024 UnusedLocalTypedefNameCandidates);
6025
6026 if (!GeneratingReducedBMI) {
6027 // Write the record containing pending implicit instantiations.
6028 RecordData PendingInstantiations;
6029 for (const auto &I : SemaRef.PendingInstantiations) {
6030 if (!wasDeclEmitted(I.first))
6031 continue;
6032
6033 AddDeclRef(I.first, PendingInstantiations);
6034 AddSourceLocation(I.second, PendingInstantiations);
6035 }
6036 if (!PendingInstantiations.empty())
6037 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
6038 }
6039
6040 auto AddEmittedDeclRefOrZero = [this](RecordData &Refs, Decl *D) {
6041 if (!D || !wasDeclEmitted(D))
6042 Refs.push_back(0);
6043 else
6044 AddDeclRef(D, Refs);
6045 };
6046
6047 // Write the record containing declaration references of Sema.
6048 RecordData SemaDeclRefs;
6049 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
6050 AddEmittedDeclRefOrZero(SemaDeclRefs, SemaRef.getStdNamespace());
6051 AddEmittedDeclRefOrZero(SemaDeclRefs, SemaRef.getStdBadAlloc());
6052 AddEmittedDeclRefOrZero(SemaDeclRefs, SemaRef.getStdAlignValT());
6053 }
6054 if (!SemaDeclRefs.empty())
6055 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
6056
6057 // Write the record containing decls to be checked for deferred diags.
6058 RecordData DeclsToCheckForDeferredDiags;
6059 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
6060 if (wasDeclEmitted(D))
6061 AddDeclRef(D, DeclsToCheckForDeferredDiags);
6062 if (!DeclsToCheckForDeferredDiags.empty())
6063 Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
6064 DeclsToCheckForDeferredDiags);
6065
6066 // Write the record containing CUDA-specific declaration references.
6067 RecordData CUDASpecialDeclRefs;
6068 if (auto *CudaCallDecl = Context.getcudaConfigureCallDecl(),
6069 *CudaGetParamDecl = Context.getcudaGetParameterBufferDecl(),
6070 *CudaLaunchDecl = Context.getcudaLaunchDeviceDecl();
6071 CudaCallDecl || CudaGetParamDecl || CudaLaunchDecl) {
6072 AddEmittedDeclRefOrZero(CUDASpecialDeclRefs, CudaCallDecl);
6073 AddEmittedDeclRefOrZero(CUDASpecialDeclRefs, CudaGetParamDecl);
6074 AddEmittedDeclRefOrZero(CUDASpecialDeclRefs, CudaLaunchDecl);
6075 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
6076 }
6077
6078 // Write the delegating constructors.
6079 RecordData DelegatingCtorDecls;
6080 if (!isModule)
6082 DelegatingCtorDecls);
6083 if (!DelegatingCtorDecls.empty())
6084 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
6085
6086 // Write the known namespaces.
6087 RecordData KnownNamespaces;
6088 for (const auto &I : SemaRef.KnownNamespaces) {
6089 if (!I.second && wasDeclEmitted(I.first))
6090 AddDeclRef(I.first, KnownNamespaces);
6091 }
6092 if (!KnownNamespaces.empty())
6093 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
6094
6095 // Write the undefined internal functions and variables, and inline functions.
6096 RecordData UndefinedButUsed;
6097 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
6099 for (const auto &I : Undefined) {
6100 if (!wasDeclEmitted(I.first))
6101 continue;
6102
6103 AddDeclRef(I.first, UndefinedButUsed);
6104 AddSourceLocation(I.second, UndefinedButUsed);
6105 }
6106 if (!UndefinedButUsed.empty())
6107 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
6108
6109 // Write all delete-expressions that we would like to
6110 // analyze later in AST.
6111 RecordData DeleteExprsToAnalyze;
6112 if (!isModule) {
6113 for (const auto &DeleteExprsInfo :
6115 if (!wasDeclEmitted(DeleteExprsInfo.first))
6116 continue;
6117
6118 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
6119 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
6120 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
6121 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
6122 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
6123 }
6124 }
6125 }
6126 if (!DeleteExprsToAnalyze.empty())
6127 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
6128
6129 RecordData VTablesToEmit;
6130 for (CXXRecordDecl *RD : PendingEmittingVTables) {
6131 if (!wasDeclEmitted(RD))
6132 continue;
6133
6134 AddDeclRef(RD, VTablesToEmit);
6135 }
6136
6137 if (!VTablesToEmit.empty())
6138 Stream.EmitRecord(VTABLES_TO_EMIT, VTablesToEmit);
6139}
6140
6141ASTFileSignature ASTWriter::WriteASTCore(Sema *SemaPtr, StringRef isysroot,
6142 Module *WritingModule) {
6143 using namespace llvm;
6144
6145 bool isModule = WritingModule != nullptr;
6146
6147 // Make sure that the AST reader knows to finalize itself.
6148 if (Chain)
6149 Chain->finalizeForWriting();
6150
6151 // This needs to be done very early, since everything that writes
6152 // SourceLocations or FileIDs depends on it.
6153 computeNonAffectingInputFiles();
6154
6155 writeUnhashedControlBlock(*PP);
6156
6157 // Don't reuse type ID and Identifier ID from readers for C++ standard named
6158 // modules since we want to support no-transitive-change model for named
6159 // modules. The theory for no-transitive-change model is,
6160 // for a user of a named module, the user can only access the indirectly
6161 // imported decls via the directly imported module. So that it is possible to
6162 // control what matters to the users when writing the module. It would be
6163 // problematic if the users can reuse the type IDs and identifier IDs from
6164 // indirectly imported modules arbitrarily. So we choose to clear these ID
6165 // here.
6167 TypeIdxs.clear();
6168 IdentifierIDs.clear();
6169 }
6170
6171 // Look for any identifiers that were named while processing the
6172 // headers, but are otherwise not needed. We add these to the hash
6173 // table to enable checking of the predefines buffer in the case
6174 // where the user adds new macro definitions when building the AST
6175 // file.
6176 //
6177 // We do this before emitting any Decl and Types to make sure the
6178 // Identifier ID is stable.
6179 SmallVector<const IdentifierInfo *, 128> IIs;
6180 for (const auto &ID : PP->getIdentifierTable())
6181 if (IsInterestingNonMacroIdentifier(ID.second, *this))
6182 IIs.push_back(ID.second);
6183 // Sort the identifiers lexicographically before getting the references so
6184 // that their order is stable.
6185 llvm::sort(IIs, llvm::deref<std::less<>>());
6186 for (const IdentifierInfo *II : IIs)
6187 getIdentifierRef(II);
6188
6189 // Write the set of weak, undeclared identifiers. We always write the
6190 // entire table, since later PCH files in a PCH chain are only interested in
6191 // the results at the end of the chain.
6192 RecordData WeakUndeclaredIdentifiers;
6193 if (SemaPtr) {
6194 for (const auto &WeakUndeclaredIdentifierList :
6195 SemaPtr->WeakUndeclaredIdentifiers) {
6196 const IdentifierInfo *const II = WeakUndeclaredIdentifierList.first;
6197 for (const auto &WI : WeakUndeclaredIdentifierList.second) {
6198 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
6199 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
6200 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
6201 }
6202 }
6203 }
6204
6205 // Write the set of #pragma redefine_extname'd, undeclared identifiers. We
6206 // always write the entire table, since later PCH files in a PCH chain are
6207 // only interested in the results at the end of the chain.
6208 RecordData ExtnameUndeclaredIdentifiers;
6209 if (SemaPtr && !isWritingStdCXXNamedModules()) {
6210 ASTContext &Context = SemaPtr->Context;
6211 ASTRecordWriter ExtnameUndeclaredIdentifiersWriter(
6212 Context, *this, ExtnameUndeclaredIdentifiers);
6213 for (const auto &[II, AL] : SemaPtr->ExtnameUndeclaredIdentifiers) {
6214 ExtnameUndeclaredIdentifiersWriter.AddIdentifierRef(II);
6215 ExtnameUndeclaredIdentifiersWriter.AddIdentifierRef(
6216 &Context.Idents.get(AL->getLabel()));
6217 ExtnameUndeclaredIdentifiersWriter.AddSourceLocation(AL->getLocation());
6218 }
6219 }
6220
6221 // Form the record of special types.
6222 RecordData SpecialTypes;
6223 if (SemaPtr) {
6224 ASTContext &Context = SemaPtr->Context;
6225 AddTypeRef(Context, Context.getRawCFConstantStringType(), SpecialTypes);
6226 AddTypeRef(Context, Context.getFILEType(), SpecialTypes);
6227 AddTypeRef(Context, Context.getjmp_bufType(), SpecialTypes);
6228 AddTypeRef(Context, Context.getsigjmp_bufType(), SpecialTypes);
6229 AddTypeRef(Context, Context.ObjCIdRedefinitionType, SpecialTypes);
6230 AddTypeRef(Context, Context.ObjCClassRedefinitionType, SpecialTypes);
6231 AddTypeRef(Context, Context.ObjCSelRedefinitionType, SpecialTypes);
6232 AddTypeRef(Context, Context.getucontext_tType(), SpecialTypes);
6233 }
6234
6235 if (SemaPtr)
6236 PrepareWritingSpecialDecls(*SemaPtr);
6237
6238 // Write the control block
6239 WriteControlBlock(*PP, isysroot);
6240
6241 // Write the remaining AST contents.
6242 Stream.FlushToWord();
6243 ASTBlockRange.first = Stream.GetCurrentBitNo() >> 3;
6244 Stream.EnterSubblock(AST_BLOCK_ID, 5);
6245 ASTBlockStartOffset = Stream.GetCurrentBitNo();
6246
6247 // This is so that older clang versions, before the introduction
6248 // of the control block, can read and reject the newer PCH format.
6249 {
6251 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
6252 }
6253
6254 // For method pool in the module, if it contains an entry for a selector,
6255 // the entry should be complete, containing everything introduced by that
6256 // module and all modules it imports. It's possible that the entry is out of
6257 // date, so we need to pull in the new content here.
6258
6259 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
6260 // safe, we copy all selectors out.
6261 if (SemaPtr) {
6262 llvm::SmallVector<Selector, 256> AllSelectors;
6263 for (auto &SelectorAndID : SelectorIDs)
6264 AllSelectors.push_back(SelectorAndID.first);
6265 for (auto &Selector : AllSelectors)
6266 SemaPtr->ObjC().updateOutOfDateSelector(Selector);
6267 }
6268
6269 if (Chain) {
6270 // Write the mapping information describing our module dependencies and how
6271 // each of those modules were mapped into our own offset/ID space, so that
6272 // the reader can build the appropriate mapping to its own offset/ID space.
6273 // The map consists solely of a blob with the following format:
6274 // *(module-kind:i8
6275 // module-name-len:i16 module-name:len*i8
6276 // source-location-offset:i32
6277 // identifier-id:i32
6278 // preprocessed-entity-id:i32
6279 // macro-definition-id:i32
6280 // submodule-id:i32
6281 // selector-id:i32
6282 // declaration-id:i32
6283 // c++-base-specifiers-id:i32
6284 // type-id:i32)
6285 //
6286 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule,
6287 // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the
6288 // module name. Otherwise, it is the module file name.
6289 auto Abbrev = std::make_shared<BitCodeAbbrev>();
6290 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
6291 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
6292 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
6293 SmallString<2048> Buffer;
6294 {
6295 llvm::raw_svector_ostream Out(Buffer);
6296 for (ModuleFile &M : Chain->ModuleMgr) {
6297 using namespace llvm::support;
6298
6299 endian::Writer LE(Out, llvm::endianness::little);
6300 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
6301 // FIXME: Storing a PCH's name (M.FileName) as a string does not handle
6302 // relocatable files. We probably should call
6303 // `PreparePathForOutput(M.FileName)` to properly support relocatable
6304 // PCHs.
6305 StringRef Name = M.isModule() ? M.ModuleName : M.FileName.str();
6306 LE.write<uint16_t>(Name.size());
6307 Out.write(Name.data(), Name.size());
6308
6309 // Note: if a base ID was uint max, it would not be possible to load
6310 // another module after it or have more than one entity inside it.
6311 uint32_t None = std::numeric_limits<uint32_t>::max();
6312
6313 auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) {
6314 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
6315 if (ShouldWrite)
6316 LE.write<uint32_t>(BaseID);
6317 else
6318 LE.write<uint32_t>(None);
6319 };
6320
6321 // These values should be unique within a chain, since they will be read
6322 // as keys into ContinuousRangeMaps.
6323 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
6324 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
6325 }
6326 }
6327 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
6328 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
6329 Buffer.data(), Buffer.size());
6330 }
6331
6332 if (SemaPtr)
6333 WriteDeclAndTypes(SemaPtr->Context);
6334
6335 WriteFileDeclIDsMap();
6336 WriteSourceManagerBlock(PP->getSourceManager());
6337 if (SemaPtr)
6338 WriteComments(SemaPtr->Context);
6339 WritePreprocessor(*PP, isModule);
6340 WriteHeaderSearch(PP->getHeaderSearchInfo());
6341 if (SemaPtr) {
6342 WriteSelectors(*SemaPtr);
6343 WriteReferencedSelectorsPool(*SemaPtr);
6344 WriteLateParsedTemplates(*SemaPtr);
6345 }
6346 WriteIdentifierTable(*PP, SemaPtr ? &SemaPtr->IdResolver : nullptr, isModule);
6347 if (SemaPtr) {
6348 WriteFPPragmaOptions(SemaPtr->CurFPFeatureOverrides());
6349 WriteOpenCLExtensions(*SemaPtr);
6350 WriteCUDAPragmas(*SemaPtr);
6351 WriteRISCVIntrinsicPragmas(*SemaPtr);
6352 }
6353
6354 // If we're emitting a module, write out the submodule information.
6355 if (WritingModule)
6356 WriteSubmodules(WritingModule, SemaPtr ? &SemaPtr->Context : nullptr);
6357
6358 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
6359
6360 if (SemaPtr)
6361 WriteSpecialDeclRecords(*SemaPtr);
6362
6363 // Write the record containing weak undeclared identifiers.
6364 if (!WeakUndeclaredIdentifiers.empty())
6365 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
6366 WeakUndeclaredIdentifiers);
6367
6368 // Write the record containing #pragma redefine_extname'd undeclared
6369 // identifiers.
6370 if (!ExtnameUndeclaredIdentifiers.empty())
6371 Stream.EmitRecord(EXTNAME_UNDECLARED_IDENTIFIERS,
6372 ExtnameUndeclaredIdentifiers);
6373
6374 if (!WritingModule) {
6375 // Write the submodules that were imported, if any.
6376 struct ModuleInfo {
6377 uint64_t ID;
6378 Module *M;
6379 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
6380 };
6381 llvm::SmallVector<ModuleInfo, 64> Imports;
6382 if (SemaPtr) {
6383 for (const auto *I : SemaPtr->Context.local_imports()) {
6384 assert(SubmoduleIDs.contains(I->getImportedModule()));
6385 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
6386 I->getImportedModule()));
6387 }
6388 }
6389
6390 if (!Imports.empty()) {
6391 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
6392 return A.ID < B.ID;
6393 };
6394 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
6395 return A.ID == B.ID;
6396 };
6397
6398 // Sort and deduplicate module IDs.
6399 llvm::sort(Imports, Cmp);
6400 Imports.erase(llvm::unique(Imports, Eq), Imports.end());
6401
6402 RecordData ImportedModules;
6403 for (const auto &Import : Imports) {
6404 ImportedModules.push_back(Import.ID);
6405 // FIXME: If the module has macros imported then later has declarations
6406 // imported, this location won't be the right one as a location for the
6407 // declaration imports.
6408 AddSourceLocation(PP->getModuleImportLoc(Import.M), ImportedModules);
6409 }
6410
6411 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
6412 }
6413 }
6414
6415 WriteObjCCategories();
6416 if (SemaPtr) {
6417 if (!WritingModule) {
6418 WriteOptimizePragmaOptions(*SemaPtr);
6419 WriteMSStructPragmaOptions(*SemaPtr);
6420 WriteMSPointersToMembersPragmaOptions(*SemaPtr);
6421 }
6422 WritePackPragmaOptions(*SemaPtr);
6423 WriteFloatControlPragmaOptions(*SemaPtr);
6424 WriteDeclsWithEffectsToVerify(*SemaPtr);
6425 WriteOpenMPRequiresDecls(*SemaPtr);
6426 }
6427
6428 // Some simple statistics
6429 RecordData::value_type Record[] = {NumStatements,
6430 NumMacros,
6431 NumLexicalDeclContexts,
6432 NumVisibleDeclContexts,
6433 NumModuleLocalDeclContexts,
6434 NumTULocalDeclContexts};
6435 Stream.EmitRecord(STATISTICS, Record);
6436 Stream.ExitBlock();
6437 Stream.FlushToWord();
6438 ASTBlockRange.second = Stream.GetCurrentBitNo() >> 3;
6439
6440 // Write the module file extension blocks.
6441 if (SemaPtr)
6442 for (const auto &ExtWriter : ModuleFileExtensionWriters)
6443 WriteModuleFileExtension(*SemaPtr, *ExtWriter);
6444
6445 return backpatchSignature();
6446}
6447
6448// Add update records for all mangling numbers and static local numbers.
6449// These aren't really update records, but this is a convenient way of
6450// tagging this rare extra data onto the declarations.
6451void ASTWriter::AddedManglingNumber(const Decl *D, unsigned Number) {
6452 if (D->isFromASTFile())
6453 return;
6454
6455 DeclUpdates[D].push_back(DeclUpdate(DeclUpdateKind::ManglingNumber, Number));
6456}
6457void ASTWriter::AddedStaticLocalNumbers(const Decl *D, unsigned Number) {
6458 if (D->isFromASTFile())
6459 return;
6460
6461 DeclUpdates[D].push_back(
6462 DeclUpdate(DeclUpdateKind::StaticLocalNumber, Number));
6463}
6464
6465void ASTWriter::AddedAnonymousNamespace(const TranslationUnitDecl *TU,
6466 NamespaceDecl *AnonNamespace) {
6467 // If the translation unit has an anonymous namespace, and we don't already
6468 // have an update block for it, write it as an update block.
6469 // FIXME: Why do we not do this if there's already an update block?
6470 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
6471 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
6472 if (Record.empty())
6473 Record.push_back(
6474 DeclUpdate(DeclUpdateKind::CXXAddedAnonymousNamespace, NS));
6475 }
6476}
6477
6478void ASTWriter::WriteDeclAndTypes(ASTContext &Context) {
6479 // Keep writing types, declarations, and declaration update records
6480 // until we've emitted all of them.
6481 RecordData DeclUpdatesOffsetsRecord;
6482 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/ 6);
6483 DeclTypesBlockStartOffset = Stream.GetCurrentBitNo();
6484 WriteTypeAbbrevs();
6485 WriteDeclAbbrevs();
6486 do {
6487 WriteDeclUpdatesBlocks(Context, DeclUpdatesOffsetsRecord);
6488 while (!DeclTypesToEmit.empty()) {
6489 DeclOrType DOT = DeclTypesToEmit.front();
6490 DeclTypesToEmit.pop();
6491 if (DOT.isType())
6492 WriteType(Context, DOT.getType());
6493 else
6494 WriteDecl(Context, DOT.getDecl());
6495 }
6496 } while (!DeclUpdates.empty());
6497
6498 DoneWritingDeclsAndTypes = true;
6499
6500 // DelayedNamespace is only meaningful in reduced BMI.
6501 // See the comments of DelayedNamespace for details.
6502 assert(DelayedNamespace.empty() || GeneratingReducedBMI);
6503 RecordData DelayedNamespaceRecord;
6504 for (NamespaceDecl *NS : DelayedNamespace) {
6505 LookupBlockOffsets Offsets;
6506
6507 Offsets.LexicalOffset = WriteDeclContextLexicalBlock(Context, NS);
6508 WriteDeclContextVisibleBlock(Context, NS, Offsets);
6509
6510 if (Offsets.LexicalOffset)
6511 Offsets.LexicalOffset -= DeclTypesBlockStartOffset;
6512
6513 // Write the offset relative to current block.
6514 if (Offsets.VisibleOffset)
6515 Offsets.VisibleOffset -= DeclTypesBlockStartOffset;
6516
6517 if (Offsets.ModuleLocalOffset)
6518 Offsets.ModuleLocalOffset -= DeclTypesBlockStartOffset;
6519
6520 if (Offsets.TULocalOffset)
6521 Offsets.TULocalOffset -= DeclTypesBlockStartOffset;
6522
6523 AddDeclRef(NS, DelayedNamespaceRecord);
6524 AddLookupOffsets(Offsets, DelayedNamespaceRecord);
6525 }
6526
6527 // The process of writing lexical and visible block for delayed namespace
6528 // shouldn't introduce any new decls, types or update to emit.
6529 assert(DeclTypesToEmit.empty());
6530 assert(DeclUpdates.empty());
6531
6532 Stream.ExitBlock();
6533
6534 // These things can only be done once we've written out decls and types.
6535 WriteTypeDeclOffsets();
6536 if (!DeclUpdatesOffsetsRecord.empty())
6537 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
6538
6539 if (!DelayedNamespaceRecord.empty())
6541 DelayedNamespaceRecord);
6542
6543 if (!RelatedDeclsMap.empty()) {
6544 // TODO: on disk hash table for related decls mapping might be more
6545 // efficent becuase it allows lazy deserialization.
6546 RecordData RelatedDeclsMapRecord;
6547 for (const auto &Pair : RelatedDeclsMap) {
6548 RelatedDeclsMapRecord.push_back(Pair.first.getRawValue());
6549 RelatedDeclsMapRecord.push_back(Pair.second.size());
6550 for (const auto &Lambda : Pair.second)
6551 RelatedDeclsMapRecord.push_back(Lambda.getRawValue());
6552 }
6553
6554 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
6555 Abv->Add(llvm::BitCodeAbbrevOp(RELATED_DECLS_MAP));
6556 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Array));
6557 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6558 unsigned FunctionToLambdaMapAbbrev = Stream.EmitAbbrev(std::move(Abv));
6559 Stream.EmitRecord(RELATED_DECLS_MAP, RelatedDeclsMapRecord,
6560 FunctionToLambdaMapAbbrev);
6561 }
6562
6563 if (!SpecializationsUpdates.empty()) {
6564 WriteSpecializationsUpdates(/*IsPartial=*/false);
6565 SpecializationsUpdates.clear();
6566 }
6567
6568 if (!PartialSpecializationsUpdates.empty()) {
6569 WriteSpecializationsUpdates(/*IsPartial=*/true);
6570 PartialSpecializationsUpdates.clear();
6571 }
6572
6573 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
6574 // Create a lexical update block containing all of the declarations in the
6575 // translation unit that do not come from other AST files.
6576 SmallVector<DeclID, 128> NewGlobalKindDeclPairs;
6577 for (const auto *D : TU->noload_decls()) {
6578 if (D->isFromASTFile())
6579 continue;
6580
6581 // In reduced BMI, skip unreached declarations.
6582 if (!wasDeclEmitted(D))
6583 continue;
6584
6585 NewGlobalKindDeclPairs.push_back(D->getKind());
6586 NewGlobalKindDeclPairs.push_back(GetDeclRef(D).getRawValue());
6587 }
6588
6589 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
6590 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
6591 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6592 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
6593
6594 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
6595 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
6596 bytes(NewGlobalKindDeclPairs));
6597
6598 Abv = std::make_shared<llvm::BitCodeAbbrev>();
6599 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
6600 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6601 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6602 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
6603
6604 Abv = std::make_shared<llvm::BitCodeAbbrev>();
6605 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_MODULE_LOCAL_VISIBLE));
6606 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6607 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6608 ModuleLocalUpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
6609
6610 Abv = std::make_shared<llvm::BitCodeAbbrev>();
6611 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_TU_LOCAL_VISIBLE));
6612 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6613 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6614 TULocalUpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
6615
6616 // And a visible updates block for the translation unit.
6617 WriteDeclContextVisibleUpdate(Context, TU);
6618
6619 // If we have any extern "C" names, write out a visible update for them.
6620 if (Context.ExternCContext)
6621 WriteDeclContextVisibleUpdate(Context, Context.ExternCContext);
6622
6623 // Write the visible updates to DeclContexts.
6624 for (auto *DC : UpdatedDeclContexts)
6625 WriteDeclContextVisibleUpdate(Context, DC);
6626}
6627
6628void ASTWriter::WriteSpecializationsUpdates(bool IsPartial) {
6629 auto RecordType = IsPartial ? CXX_ADDED_TEMPLATE_PARTIAL_SPECIALIZATION
6631
6632 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
6633 Abv->Add(llvm::BitCodeAbbrevOp(RecordType));
6634 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6635 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6636 auto UpdateSpecializationAbbrev = Stream.EmitAbbrev(std::move(Abv));
6637
6638 auto &SpecUpdates =
6639 IsPartial ? PartialSpecializationsUpdates : SpecializationsUpdates;
6640 for (auto &SpecializationUpdate : SpecUpdates) {
6641 const NamedDecl *D = SpecializationUpdate.first;
6642
6643 llvm::SmallString<4096> LookupTable;
6644 GenerateSpecializationInfoLookupTable(D, SpecializationUpdate.second,
6645 LookupTable, IsPartial);
6646
6647 // Write the lookup table
6648 RecordData::value_type Record[] = {
6649 static_cast<RecordData::value_type>(RecordType),
6650 getDeclID(D).getRawValue()};
6651 Stream.EmitRecordWithBlob(UpdateSpecializationAbbrev, Record, LookupTable);
6652 }
6653}
6654
6655void ASTWriter::WriteDeclUpdatesBlocks(ASTContext &Context,
6656 RecordDataImpl &OffsetsRecord) {
6657 if (DeclUpdates.empty())
6658 return;
6659
6660 DeclUpdateMap LocalUpdates;
6661 LocalUpdates.swap(DeclUpdates);
6662
6663 for (auto &DeclUpdate : LocalUpdates) {
6664 const Decl *D = DeclUpdate.first;
6665
6666 bool HasUpdatedBody = false;
6667 bool HasAddedVarDefinition = false;
6669 ASTRecordWriter Record(Context, *this, RecordData);
6670 for (auto &Update : DeclUpdate.second) {
6671 DeclUpdateKind Kind = Update.getKind();
6672
6673 // An updated body is emitted last, so that the reader doesn't need
6674 // to skip over the lazy body to reach statements for other records.
6675 if (Kind == DeclUpdateKind::CXXAddedFunctionDefinition)
6676 HasUpdatedBody = true;
6677 else if (Kind == DeclUpdateKind::CXXAddedVarDefinition)
6678 HasAddedVarDefinition = true;
6679 else
6680 Record.push_back(llvm::to_underlying(Kind));
6681
6682 switch (Kind) {
6683 case DeclUpdateKind::CXXAddedImplicitMember:
6684 case DeclUpdateKind::CXXAddedAnonymousNamespace:
6685 assert(Update.getDecl() && "no decl to add?");
6686 Record.AddDeclRef(Update.getDecl());
6687 break;
6688 case DeclUpdateKind::CXXAddedFunctionDefinition:
6689 case DeclUpdateKind::CXXAddedVarDefinition:
6690 break;
6691
6692 case DeclUpdateKind::CXXPointOfInstantiation:
6693 // FIXME: Do we need to also save the template specialization kind here?
6694 Record.AddSourceLocation(Update.getLoc());
6695 break;
6696
6697 case DeclUpdateKind::CXXInstantiatedDefaultArgument:
6698 Record.writeStmtRef(
6699 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg());
6700 break;
6701
6702 case DeclUpdateKind::CXXInstantiatedDefaultMemberInitializer:
6703 Record.AddStmt(
6704 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
6705 break;
6706
6707 case DeclUpdateKind::CXXInstantiatedClassDefinition: {
6708 auto *RD = cast<CXXRecordDecl>(D);
6709 UpdatedDeclContexts.insert(RD->getPrimaryContext());
6710 Record.push_back(RD->isParamDestroyedInCallee());
6711 Record.push_back(llvm::to_underlying(RD->getArgPassingRestrictions()));
6712 Record.AddCXXDefinitionData(RD);
6713 Record.AddOffset(WriteDeclContextLexicalBlock(Context, RD));
6714
6715 // This state is sometimes updated by template instantiation, when we
6716 // switch from the specialization referring to the template declaration
6717 // to it referring to the template definition.
6718 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
6719 Record.push_back(MSInfo->getTemplateSpecializationKind());
6720 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
6721 } else {
6723 Record.push_back(Spec->getTemplateSpecializationKind());
6724 Record.AddSourceLocation(Spec->getPointOfInstantiation());
6725
6726 // The instantiation might have been resolved to a partial
6727 // specialization. If so, record which one.
6728 auto From = Spec->getInstantiatedFrom();
6729 if (auto PartialSpec =
6730 dyn_cast<ClassTemplatePartialSpecializationDecl *>(From)) {
6731 Record.push_back(true);
6732 Record.AddDeclRef(PartialSpec);
6733 Record.AddTemplateArgumentList(
6734 &Spec->getTemplateInstantiationArgs());
6735 } else {
6736 Record.push_back(false);
6737 }
6738 }
6739 Record.push_back(llvm::to_underlying(RD->getTagKind()));
6740 Record.AddSourceLocation(RD->getLocation());
6741 Record.AddSourceLocation(RD->getBeginLoc());
6742 Record.AddSourceRange(RD->getBraceRange());
6743
6744 // Instantiation may change attributes; write them all out afresh.
6745 Record.push_back(D->hasAttrs());
6746 if (D->hasAttrs())
6747 Record.AddAttributes(D->getAttrs());
6748
6749 // FIXME: Ensure we don't get here for explicit instantiations.
6750 break;
6751 }
6752
6753 case DeclUpdateKind::CXXResolvedDtorDelete:
6754 Record.AddDeclRef(Update.getDecl());
6755 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
6756 break;
6757
6758 case DeclUpdateKind::CXXResolvedDtorGlobDelete:
6759 Record.AddDeclRef(Update.getDecl());
6760 break;
6761
6762 case DeclUpdateKind::CXXResolvedDtorArrayDelete:
6763 Record.AddDeclRef(Update.getDecl());
6764 break;
6765
6766 case DeclUpdateKind::CXXResolvedDtorGlobArrayDelete:
6767 Record.AddDeclRef(Update.getDecl());
6768 break;
6769
6770 case DeclUpdateKind::CXXResolvedExceptionSpec: {
6771 auto prototype =
6772 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
6773 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
6774 break;
6775 }
6776
6777 case DeclUpdateKind::CXXDeducedReturnType:
6778 Record.push_back(GetOrCreateTypeID(Context, Update.getType()));
6779 break;
6780
6781 case DeclUpdateKind::DeclMarkedUsed:
6782 break;
6783
6784 case DeclUpdateKind::ManglingNumber:
6785 case DeclUpdateKind::StaticLocalNumber:
6786 Record.push_back(Update.getNumber());
6787 break;
6788
6789 case DeclUpdateKind::DeclMarkedOpenMPThreadPrivate:
6790 Record.AddSourceRange(
6791 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
6792 break;
6793
6794 case DeclUpdateKind::DeclMarkedOpenMPAllocate: {
6795 auto *A = D->getAttr<OMPAllocateDeclAttr>();
6796 Record.push_back(A->getAllocatorType());
6797 Record.AddStmt(A->getAllocator());
6798 Record.AddStmt(A->getAlignment());
6799 Record.AddSourceRange(A->getRange());
6800 break;
6801 }
6802
6803 case DeclUpdateKind::DeclMarkedOpenMPIndirectCall:
6804 Record.AddSourceRange(
6805 D->getAttr<OMPTargetIndirectCallAttr>()->getRange());
6806 break;
6807
6808 case DeclUpdateKind::DeclMarkedOpenMPDeclareTarget:
6809 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
6810 Record.AddSourceRange(
6811 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
6812 break;
6813
6814 case DeclUpdateKind::DeclExported:
6815 Record.push_back(getSubmoduleID(Update.getModule()));
6816 break;
6817
6818 case DeclUpdateKind::AddedAttrToRecord:
6819 Record.AddAttributes(llvm::ArrayRef(Update.getAttr()));
6820 break;
6821 }
6822 }
6823
6824 // Add a trailing update record, if any. These must go last because we
6825 // lazily load their attached statement.
6826 if (!GeneratingReducedBMI || !CanElideDeclDef(D)) {
6827 if (HasUpdatedBody) {
6828 const auto *Def = cast<FunctionDecl>(D);
6829 Record.push_back(
6830 llvm::to_underlying(DeclUpdateKind::CXXAddedFunctionDefinition));
6831 Record.push_back(Def->isInlined());
6832 Record.AddSourceLocation(Def->getInnerLocStart());
6833 Record.AddFunctionDefinition(Def);
6834 } else if (HasAddedVarDefinition) {
6835 const auto *VD = cast<VarDecl>(D);
6836 Record.push_back(
6837 llvm::to_underlying(DeclUpdateKind::CXXAddedVarDefinition));
6838 Record.push_back(VD->isInline());
6839 Record.push_back(VD->isInlineSpecified());
6840 Record.AddVarDeclInit(VD);
6841 }
6842 }
6843
6844 AddDeclRef(D, OffsetsRecord);
6845 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
6846 }
6847}
6848
6851 uint32_t Raw = Sema::AlignPackInfo::getRawEncoding(Info);
6852 Record.push_back(Raw);
6853}
6854
6855FileID ASTWriter::getAdjustedFileID(FileID FID) const {
6856 if (FID.isInvalid() || PP->getSourceManager().isLoadedFileID(FID) ||
6857 NonAffectingFileIDs.empty())
6858 return FID;
6859 auto It = llvm::lower_bound(NonAffectingFileIDs, FID);
6860 unsigned Idx = std::distance(NonAffectingFileIDs.begin(), It);
6861 unsigned Offset = NonAffectingFileIDAdjustments[Idx];
6862 return FileID::get(FID.getOpaqueValue() - Offset);
6863}
6864
6865unsigned ASTWriter::getAdjustedNumCreatedFIDs(FileID FID) const {
6866 unsigned NumCreatedFIDs = PP->getSourceManager()
6867 .getLocalSLocEntry(FID.ID)
6868 .getFile()
6869 .NumCreatedFIDs;
6870
6871 unsigned AdjustedNumCreatedFIDs = 0;
6872 for (unsigned I = FID.ID, N = I + NumCreatedFIDs; I != N; ++I)
6873 if (IsSLocAffecting[I])
6874 ++AdjustedNumCreatedFIDs;
6875 return AdjustedNumCreatedFIDs;
6876}
6877
6878SourceLocation ASTWriter::getAdjustedLocation(SourceLocation Loc) const {
6879 if (Loc.isInvalid())
6880 return Loc;
6881 return Loc.getLocWithOffset(-getAdjustment(Loc.getOffset()));
6882}
6883
6884SourceRange ASTWriter::getAdjustedRange(SourceRange Range) const {
6885 return SourceRange(getAdjustedLocation(Range.getBegin()),
6886 getAdjustedLocation(Range.getEnd()));
6887}
6888
6890ASTWriter::getAdjustedOffset(SourceLocation::UIntTy Offset) const {
6891 return Offset - getAdjustment(Offset);
6892}
6893
6895ASTWriter::getAdjustment(SourceLocation::UIntTy Offset) const {
6896 if (NonAffectingRanges.empty())
6897 return 0;
6898
6899 if (PP->getSourceManager().isLoadedOffset(Offset))
6900 return 0;
6901
6902 if (Offset > NonAffectingRanges.back().getEnd().getOffset())
6903 return NonAffectingOffsetAdjustments.back();
6904
6905 if (Offset < NonAffectingRanges.front().getBegin().getOffset())
6906 return 0;
6907
6908 auto Contains = [](const SourceRange &Range, SourceLocation::UIntTy Offset) {
6909 return Range.getEnd().getOffset() < Offset;
6910 };
6911
6912 auto It = llvm::lower_bound(NonAffectingRanges, Offset, Contains);
6913 unsigned Idx = std::distance(NonAffectingRanges.begin(), It);
6914 return NonAffectingOffsetAdjustments[Idx];
6915}
6916
6918 Record.push_back(getAdjustedFileID(FID).getOpaqueValue());
6919}
6920
6923 SourceLocation::UIntTy BaseOffset = 0;
6924 unsigned ModuleFileIndex = 0;
6925
6926 // See SourceLocationEncoding.h for the encoding details.
6927 if (PP->getSourceManager().isLoadedSourceLocation(Loc) && Loc.isValid()) {
6928 assert(getChain());
6929 auto SLocMapI = getChain()->GlobalSLocOffsetMap.find(
6930 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6931 assert(SLocMapI != getChain()->GlobalSLocOffsetMap.end() &&
6932 "Corrupted global sloc offset map");
6933 ModuleFile *F = SLocMapI->second;
6934 BaseOffset = F->SLocEntryBaseOffset - 2;
6935 // 0 means the location is not loaded. So we need to add 1 to the index to
6936 // make it clear.
6937 ModuleFileIndex = F->Index + 1;
6938 assert(&getChain()->getModuleManager()[F->Index] == F);
6939 }
6940
6941 return SourceLocationEncoding::encode(Loc, BaseOffset, ModuleFileIndex);
6942}
6943
6946 // Skip the dummy entry.
6947 return getAdjustedOffset(SLoc.getOffset()) - 2;
6948}
6949
6952 SourceLocation::UIntTy InitialDelta,
6954 Record.push_back(Offset);
6955 return SourceLocationEncoding::Chain(Offset + InitialDelta);
6956}
6957
6961 SourceLocation::UIntTy EntryOffset = getEntryOffset(SLoc);
6962 // Anchor the chain at the entry's own local offset. The field has the dummy
6963 // entry subtracted out (see getEntryOffset), so add it back. Decoding only
6964 // requires the reader to derive the same anchor -- see
6965 // ASTReader::ReadEntryOffset -- but anchoring at the entry keeps the deltas
6966 // small, and makes the anchor trivially non-zero since local offsets are
6967 // always >= 2.
6968 return EmitSourceLocationOffset(EntryOffset, 2, Record);
6969}
6970
6972 Loc = getAdjustedLocation(Loc);
6973 Record.push_back(getRawSourceLocationEncoding(Loc));
6974}
6975
6978 // The two-argument form appends exactly one value, so rewriting Record.back()
6979 // delta encodes what it just wrote without duplicating how it is encoded.
6981 Record.back() = Chain.deltaEncode(Record.back());
6982}
6983
6985 AddSourceLocation(Range.getBegin(), Record);
6986 AddSourceLocation(Range.getEnd(), Record);
6987}
6988
6989void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
6990 AddAPInt(Value.bitcastToAPInt());
6991}
6992
6996
6998 if (!II)
6999 return 0;
7000
7001 IdentifierID &ID = IdentifierIDs[II];
7002 if (ID == 0)
7003 ID = NextIdentID++;
7004 return ID;
7005}
7006
7008 // Don't emit builtin macros like __LINE__ to the AST file unless they
7009 // have been redefined by the header (in which case they are not
7010 // isBuiltinMacro).
7011 if (!MI || MI->isBuiltinMacro())
7012 return 0;
7013
7014 MacroID &ID = MacroIDs[MI];
7015 if (ID == 0) {
7016 ID = NextMacroID++;
7017 MacroInfoToEmitData Info = { Name, MI, ID };
7018 MacroInfosToEmit.push_back(Info);
7019 }
7020 return ID;
7021}
7022
7024 return IdentMacroDirectivesOffsetMap.lookup(Name);
7025}
7026
7028 Record->push_back(Writer->getSelectorRef(SelRef));
7029}
7030
7032 if (Sel.getAsOpaquePtr() == nullptr) {
7033 return 0;
7034 }
7035
7036 SelectorID SID = SelectorIDs[Sel];
7037 if (SID == 0 && Chain) {
7038 // This might trigger a ReadSelector callback, which will set the ID for
7039 // this selector.
7040 Chain->LoadSelector(Sel);
7041 SID = SelectorIDs[Sel];
7042 }
7043 if (SID == 0) {
7044 SID = NextSelectorID++;
7045 SelectorIDs[Sel] = SID;
7046 }
7047 return SID;
7048}
7049
7053
7082
7085
7087 bool InfoHasSameExpr
7088 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
7089 Record->push_back(InfoHasSameExpr);
7090 if (InfoHasSameExpr)
7091 return; // Avoid storing the same expr twice.
7092 }
7094}
7095
7097 if (!TInfo) {
7099 return;
7100 }
7101
7102 AddTypeRef(TInfo->getType());
7103 AddTypeLoc(TInfo->getTypeLoc());
7104}
7105
7107 TypeLocWriter TLW(*this);
7108 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7109 TLW.Visit(TL);
7110}
7111
7114 Record.push_back(GetOrCreateTypeID(Context, T));
7115}
7116
7117template <typename IdxForTypeTy>
7119 IdxForTypeTy IdxForType) {
7120 if (T.isNull())
7121 return PREDEF_TYPE_NULL_ID;
7122
7123 unsigned FastQuals = T.getLocalFastQualifiers();
7124 T.removeLocalFastQualifiers();
7125
7126 if (T.hasLocalNonFastQualifiers())
7127 return IdxForType(T).asTypeID(FastQuals);
7128
7129 assert(!T.hasLocalQualifiers());
7130
7131 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr()))
7132 return TypeIdxFromBuiltin(BT).asTypeID(FastQuals);
7133
7134 if (T == Context.AutoDeductTy)
7135 return TypeIdx(0, PREDEF_TYPE_AUTO_DEDUCT).asTypeID(FastQuals);
7136 if (T == Context.AutoRRefDeductTy)
7137 return TypeIdx(0, PREDEF_TYPE_AUTO_RREF_DEDUCT).asTypeID(FastQuals);
7138
7139 return IdxForType(T).asTypeID(FastQuals);
7140}
7141
7143 return MakeTypeID(Context, T, [&](QualType T) -> TypeIdx {
7144 if (T.isNull())
7145 return TypeIdx();
7146 assert(!T.getLocalFastQualifiers());
7147
7148 TypeIdx &Idx = TypeIdxs[T];
7149 if (Idx.getValue() == 0) {
7150 if (DoneWritingDeclsAndTypes) {
7151 assert(0 && "New type seen after serializing all the types to emit!");
7152 return TypeIdx();
7153 }
7154
7155 // We haven't seen this type before. Assign it a new ID and put it
7156 // into the queue of types to emit.
7157 Idx = TypeIdx(0, NextTypeID++);
7158 DeclTypesToEmit.push(T);
7159 }
7160 return Idx;
7161 });
7162}
7163
7164llvm::MapVector<ModuleFile *, const Decl *>
7166 llvm::MapVector<ModuleFile *, const Decl *> Firsts;
7167 // FIXME: We can skip entries that we know are implied by others.
7168 for (const Decl *R = D->getMostRecentDecl(); R; R = R->getPreviousDecl()) {
7169 if (R->isFromASTFile())
7170 Firsts[Chain->getOwningModuleFile(R)] = R;
7171 else if (IncludeLocal)
7172 Firsts[nullptr] = R;
7173 }
7174 return Firsts;
7175}
7176
7179 Record.push_back(Offsets.LexicalOffset);
7180 Record.push_back(Offsets.VisibleOffset);
7181 Record.push_back(Offsets.ModuleLocalOffset);
7182 Record.push_back(Offsets.TULocalOffset);
7183}
7184
7187 MacroID MacroRef = getMacroRef(MI, Name);
7188 Record.push_back(MacroRef >> 32);
7189 Record.push_back(MacroRef & llvm::maskTrailingOnes<MacroID>(32));
7190}
7191
7193 if (!wasDeclEmitted(D))
7194 return;
7195
7196 AddDeclRef(D, Record);
7197}
7198
7200 Record.push_back(GetDeclRef(D).getRawValue());
7201}
7202
7204 assert(WritingAST && "Cannot request a declaration ID before AST writing");
7205
7206 if (!D) {
7207 return LocalDeclID();
7208 }
7209
7210 getLazyUpdates(D);
7211
7212 // If D comes from an AST file, its declaration ID is already known and
7213 // fixed.
7214 if (D->isFromASTFile()) {
7216 TouchedTopLevelModules.insert(D->getOwningModule()->getTopLevelModule());
7217
7218 return LocalDeclID(D->getGlobalID());
7219 }
7220
7221 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
7222 LocalDeclID &ID = DeclIDs[D];
7223 if (ID.isInvalid()) {
7224 if (DoneWritingDeclsAndTypes) {
7225 assert(0 && "New decl seen after serializing all the decls to emit!");
7226 return LocalDeclID();
7227 }
7228
7229 // We haven't seen this declaration before. Give it a new ID and
7230 // enqueue it in the list of declarations to emit.
7231 ID = NextDeclID++;
7232 DeclTypesToEmit.push(const_cast<Decl *>(D));
7233 }
7234
7235 return ID;
7236}
7237
7239 if (!D)
7240 return LocalDeclID();
7241
7242 // If D comes from an AST file, its declaration ID is already known and
7243 // fixed.
7244 if (D->isFromASTFile())
7245 return LocalDeclID(D->getGlobalID());
7246
7247 assert(DeclIDs.contains(D) && "Declaration not emitted!");
7248 return DeclIDs[D];
7249}
7250
7251bool ASTWriter::wasDeclEmitted(const Decl *D) const {
7252 assert(D);
7253
7254 assert(DoneWritingDeclsAndTypes &&
7255 "wasDeclEmitted should only be called after writing declarations");
7256
7257 if (D->isFromASTFile())
7258 return true;
7259
7260 bool Emitted = DeclIDs.contains(D);
7261 assert((Emitted || (!D->getOwningModule() && isWritingStdCXXNamedModules()) ||
7262 GeneratingReducedBMI) &&
7263 "The declaration within modules can only be omitted in reduced BMI.");
7264 return Emitted;
7265}
7266
7267void ASTWriter::getLazyUpdates(const Decl *D) {
7268 if (!GeneratingReducedBMI)
7269 return;
7270
7271 if (auto *Iter = DeclUpdatesLazy.find(D); Iter != DeclUpdatesLazy.end()) {
7272 for (DeclUpdate &Update : Iter->second)
7273 DeclUpdates[D].push_back(Update);
7274 DeclUpdatesLazy.erase(Iter);
7275 }
7276
7277 // If the Decl in DeclUpdatesLazy gets touched, emit the update.
7278 if (auto *DC = dyn_cast<DeclContext>(D);
7279 DC && UpdatedDeclContextsLazy.count(DC)) {
7280 UpdatedDeclContexts.insert(DC);
7281 UpdatedDeclContextsLazy.remove(DC);
7282 }
7283}
7284
7285void ASTWriter::associateDeclWithFile(const Decl *D, LocalDeclID ID) {
7286 assert(ID.isValid());
7287 assert(D);
7288
7289 SourceLocation Loc = D->getLocation();
7290 if (Loc.isInvalid())
7291 return;
7292
7293 // We only keep track of the file-level declarations of each file.
7295 return;
7296 // FIXME: ParmVarDecls that are part of a function type of a parameter of
7297 // a function/objc method, should not have TU as lexical context.
7298 // TemplateTemplateParmDecls that are part of an alias template, should not
7299 // have TU as lexical context.
7301 return;
7302
7303 SourceManager &SM = PP->getSourceManager();
7304 SourceLocation FileLoc = SM.getFileLoc(Loc);
7305 assert(SM.isLocalSourceLocation(FileLoc));
7306 auto [FID, Offset] = SM.getDecomposedLoc(FileLoc);
7307 if (FID.isInvalid())
7308 return;
7309 assert(SM.getSLocEntry(FID).isFile());
7310 assert(IsSLocAffecting[FID.ID]);
7311
7312 std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
7313 if (!Info)
7314 Info = std::make_unique<DeclIDInFileInfo>();
7315
7316 std::pair<unsigned, LocalDeclID> LocDecl(Offset, ID);
7317 LocDeclIDsTy &Decls = Info->DeclIDs;
7318 Decls.push_back(LocDecl);
7319}
7320
7323 "expected an anonymous declaration");
7324
7325 // Number the anonymous declarations within this context, if we've not
7326 // already done so.
7327 auto It = AnonymousDeclarationNumbers.find(D);
7328 if (It == AnonymousDeclarationNumbers.end()) {
7329 auto *DC = D->getLexicalDeclContext();
7330 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
7331 AnonymousDeclarationNumbers[ND] = Number;
7332 });
7333
7334 It = AnonymousDeclarationNumbers.find(D);
7335 assert(It != AnonymousDeclarationNumbers.end() &&
7336 "declaration not found within its lexical context");
7337 }
7338
7339 return It->second;
7340}
7341
7368
7370 const DeclarationNameInfo &NameInfo) {
7371 AddDeclarationName(NameInfo.getName());
7372 AddSourceLocation(NameInfo.getLoc());
7373 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
7374}
7375
7378 Record->push_back(Info.NumTemplParamLists);
7379 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
7381}
7382
7384 NestedNameSpecifierLoc QualifierLoc) {
7385 // Nested name specifiers usually aren't too long. I think that 8 would
7386 // typically accommodate the vast majority.
7388
7389 // Push each of the nested-name-specifiers's onto a stack for
7390 // serialization in reverse order.
7391 while (QualifierLoc) {
7392 NestedNames.push_back(QualifierLoc);
7393 QualifierLoc = QualifierLoc.getAsNamespaceAndPrefix().Prefix;
7394 }
7395
7396 Record->push_back(NestedNames.size());
7397 while(!NestedNames.empty()) {
7398 QualifierLoc = NestedNames.pop_back_val();
7399 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
7400 NestedNameSpecifier::Kind Kind = Qualifier.getKind();
7401 Record->push_back(llvm::to_underlying(Kind));
7402 switch (Kind) {
7404 AddDeclRef(Qualifier.getAsNamespaceAndPrefix().Namespace);
7405 AddSourceRange(QualifierLoc.getLocalSourceRange());
7406 break;
7407
7409 TypeLoc TL = QualifierLoc.castAsTypeLoc();
7410 AddTypeRef(TL.getType());
7411 AddTypeLoc(TL);
7413 break;
7414 }
7415
7418 break;
7419
7421 AddDeclRef(Qualifier.getAsMicrosoftSuper());
7422 AddSourceRange(QualifierLoc.getLocalSourceRange());
7423 break;
7424
7426 llvm_unreachable("unexpected null nested name specifier");
7427 }
7428 }
7429}
7430
7432 const TemplateParameterList *TemplateParams) {
7433 assert(TemplateParams && "No TemplateParams!");
7434 AddSourceLocation(TemplateParams->getTemplateLoc());
7435 AddSourceLocation(TemplateParams->getLAngleLoc());
7436 AddSourceLocation(TemplateParams->getRAngleLoc());
7437
7438 Record->push_back(TemplateParams->size());
7439 for (const auto &P : *TemplateParams)
7440 AddDeclRef(P);
7441 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
7442 Record->push_back(true);
7443 writeStmtRef(RequiresClause);
7444 } else {
7445 Record->push_back(false);
7446 }
7447}
7448
7449/// Emit a template argument list.
7451 const TemplateArgumentList *TemplateArgs) {
7452 assert(TemplateArgs && "No TemplateArgs!");
7453 Record->push_back(TemplateArgs->size());
7454 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
7455 AddTemplateArgument(TemplateArgs->get(i));
7456}
7457
7459 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
7460 assert(ASTTemplArgList && "No ASTTemplArgList!");
7461 AddSourceLocation(ASTTemplArgList->LAngleLoc);
7462 AddSourceLocation(ASTTemplArgList->RAngleLoc);
7463 Record->push_back(ASTTemplArgList->NumTemplateArgs);
7464 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
7465 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
7466 AddTemplateArgumentLoc(TemplArgs[i]);
7467}
7468
7470 Record->push_back(Set.size());
7472 I = Set.begin(), E = Set.end(); I != E; ++I) {
7473 AddDeclRef(I.getDecl());
7474 Record->push_back(I.getAccess());
7475 }
7476}
7477
7478// FIXME: Move this out of the main ASTRecordWriter interface.
7480 Record->push_back(Base.isVirtual());
7481 Record->push_back(Base.isBaseOfClass());
7482 Record->push_back(Base.getAccessSpecifierAsWritten());
7483 Record->push_back(Base.getInheritConstructors());
7484 AddTypeSourceInfo(Base.getTypeSourceInfo());
7485 AddSourceRange(Base.getSourceRange());
7486 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
7487 : SourceLocation());
7488}
7489
7493 ASTRecordWriter Writer(Context, W, Record);
7494 Writer.push_back(Bases.size());
7495
7496 for (auto &Base : Bases)
7497 Writer.AddCXXBaseSpecifier(Base);
7498
7500}
7501
7502// FIXME: Move this out of the main ASTRecordWriter interface.
7506
7507static uint64_t
7511 ASTRecordWriter Writer(Context, W, Record);
7512 Writer.push_back(CtorInits.size());
7513
7514 for (auto *Init : CtorInits) {
7515 if (Init->isBaseInitializer()) {
7517 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
7518 Writer.push_back(Init->isBaseVirtual());
7519 } else if (Init->isDelegatingInitializer()) {
7521 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
7522 } else if (Init->isMemberInitializer()){
7524 Writer.AddDeclRef(Init->getMember());
7525 } else {
7527 Writer.AddDeclRef(Init->getIndirectMember());
7528 }
7529
7530 Writer.AddSourceLocation(Init->getMemberLocation());
7531 Writer.AddStmt(Init->getInit());
7532 Writer.AddSourceLocation(Init->getLParenLoc());
7533 Writer.AddSourceLocation(Init->getRParenLoc());
7534 Writer.push_back(Init->isWritten());
7535 if (Init->isWritten())
7536 Writer.push_back(Init->getSourceOrder());
7537 }
7538
7540}
7541
7542// FIXME: Move this out of the main ASTRecordWriter interface.
7545 AddOffset(EmitCXXCtorInitializers(getASTContext(), *Writer, CtorInits));
7546}
7547
7549 auto &Data = D->data();
7550
7551 Record->push_back(Data.IsLambda);
7552
7553 BitsPacker DefinitionBits;
7554
7555#define FIELD(Name, Width, Merge) \
7556 if (!DefinitionBits.canWriteNextNBits(Width)) { \
7557 Record->push_back(DefinitionBits); \
7558 DefinitionBits.reset(0); \
7559 } \
7560 DefinitionBits.addBits(Data.Name, Width);
7561
7562#include "clang/AST/CXXRecordDeclDefinitionBits.def"
7563#undef FIELD
7564
7565 Record->push_back(DefinitionBits);
7566
7567 // getODRHash will compute the ODRHash if it has not been previously
7568 // computed.
7569 Record->push_back(D->getODRHash());
7570
7571 bool ModulesCodegen =
7572 !D->isDependentType() &&
7575 (Writer->getLangOpts().ModulesDebugInfo || D->isInNamedModule());
7576 Record->push_back(ModulesCodegen);
7577 if (ModulesCodegen)
7578 Writer->AddDeclRef(D, Writer->ModularCodegenDecls);
7579
7580 // IsLambda bit is already saved.
7581
7582 AddUnresolvedSet(Data.Conversions.get(getASTContext()));
7583 Record->push_back(Data.ComputedVisibleConversions);
7584 if (Data.ComputedVisibleConversions)
7585 AddUnresolvedSet(Data.VisibleConversions.get(getASTContext()));
7586 // Data.Definition is the owning decl, no need to write it.
7587
7588 if (!Data.IsLambda) {
7589 Record->push_back(Data.NumBases);
7590 if (Data.NumBases > 0)
7591 AddCXXBaseSpecifiers(Data.bases());
7592
7593 // FIXME: Make VBases lazily computed when needed to avoid storing them.
7594 Record->push_back(Data.NumVBases);
7595 if (Data.NumVBases > 0)
7596 AddCXXBaseSpecifiers(Data.vbases());
7597
7598 AddDeclRef(D->getFirstFriend());
7599 } else {
7600 auto &Lambda = D->getLambdaData();
7601
7602 BitsPacker LambdaBits;
7603 LambdaBits.addBits(Lambda.DependencyKind, /*Width=*/2);
7604 LambdaBits.addBit(Lambda.IsGenericLambda);
7605 LambdaBits.addBits(Lambda.CaptureDefault, /*Width=*/2);
7606 LambdaBits.addBits(Lambda.NumCaptures, /*Width=*/15);
7607 LambdaBits.addBit(Lambda.HasKnownInternalLinkage);
7608 Record->push_back(LambdaBits);
7609
7610 Record->push_back(Lambda.NumExplicitCaptures);
7611 Record->push_back(Lambda.ManglingNumber);
7612 Record->push_back(D->getDeviceLambdaManglingNumber());
7613 // The lambda context declaration and index within the context are provided
7614 // separately, so that they can be used for merging.
7615 AddTypeSourceInfo(Lambda.MethodTyInfo);
7616 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
7617 const LambdaCapture &Capture = Lambda.Captures.front()[I];
7619
7620 BitsPacker CaptureBits;
7621 CaptureBits.addBit(Capture.isImplicit());
7622 CaptureBits.addBits(Capture.getCaptureKind(), /*Width=*/3);
7623 Record->push_back(CaptureBits);
7624
7625 switch (Capture.getCaptureKind()) {
7626 case LCK_StarThis:
7627 case LCK_This:
7628 case LCK_VLAType:
7629 break;
7630 case LCK_ByCopy:
7631 case LCK_ByRef:
7632 ValueDecl *Var =
7633 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
7634 AddDeclRef(Var);
7635 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
7636 : SourceLocation());
7637 break;
7638 }
7639 }
7640 }
7641}
7642
7644 const Expr *Init = VD->getInit();
7645 if (!Init) {
7646 push_back(0);
7647 return;
7648 }
7649
7650 uint64_t Val = 1;
7651 if (EvaluatedStmt *ES = VD->getEvaluatedStmt()) {
7652 // This may trigger evaluation, so run it first
7653 if (VD->hasInitWithSideEffects())
7654 Val |= 16;
7655 assert(ES->CheckedForSideEffects);
7656 Val |= (ES->HasConstantInitialization ? 2 : 0);
7657 Val |= (ES->HasConstantDestruction ? 4 : 0);
7658 const APValue *Evaluated = VD->getEvaluatedValue();
7659 // If the evaluated result is constant, emit it.
7660 if (Evaluated && (Evaluated->isInt() || Evaluated->isFloat()))
7661 Val |= 8;
7662 }
7663 push_back(Val);
7664 if (Val & 8) {
7666 }
7667
7669}
7670
7671void ASTWriter::ReaderInitialized(ASTReader *Reader) {
7672 assert(Reader && "Cannot remove chain");
7673 assert((!Chain || Chain == Reader) && "Cannot replace chain");
7674 assert(FirstDeclID == NextDeclID &&
7675 FirstTypeID == NextTypeID &&
7676 FirstIdentID == NextIdentID &&
7677 FirstMacroID == NextMacroID &&
7678 FirstSubmoduleID == NextSubmoduleID &&
7679 FirstSelectorID == NextSelectorID &&
7680 "Setting chain after writing has started.");
7681
7682 Chain = Reader;
7683
7684 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
7685 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
7686 NextSelectorID = FirstSelectorID;
7687 NextSubmoduleID = FirstSubmoduleID;
7688}
7689
7690void ASTWriter::IdentifierRead(IdentifierID ID, IdentifierInfo *II) {
7691 // Don't reuse Type ID from external modules for named modules. See the
7692 // comments in WriteASTCore for details.
7694 return;
7695
7696 IdentifierID &StoredID = IdentifierIDs[II];
7697 unsigned OriginalModuleFileIndex = StoredID >> 32;
7698
7699 // Always keep the local identifier ID. See \p TypeRead() for more
7700 // information.
7701 if (OriginalModuleFileIndex == 0 && StoredID)
7702 return;
7703
7704 // Otherwise, keep the highest ID since the module file comes later has
7705 // higher module file indexes.
7706 if (ID > StoredID)
7707 StoredID = ID;
7708}
7709
7710void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
7711 // Always keep the highest ID. See \p TypeRead() for more information.
7712 MacroID &StoredID = MacroIDs[MI];
7713 unsigned OriginalModuleFileIndex = StoredID >> 32;
7714
7715 // Always keep the local macro ID. See \p TypeRead() for more information.
7716 if (OriginalModuleFileIndex == 0 && StoredID)
7717 return;
7718
7719 // Otherwise, keep the highest ID since the module file comes later has
7720 // higher module file indexes.
7721 if (ID > StoredID)
7722 StoredID = ID;
7723}
7724
7725void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
7726 // Don't reuse Type ID from external modules for named modules. See the
7727 // comments in WriteASTCore for details.
7729 return;
7730
7731 // Always take the type index that comes in later module files.
7732 // This copes with an interesting
7733 // case for chained AST writing where we schedule writing the type and then,
7734 // later, deserialize the type from another AST. In this case, we want to
7735 // keep the entry from a later module so that we can properly write it out to
7736 // the AST file.
7737 TypeIdx &StoredIdx = TypeIdxs[T];
7738
7739 // Ignore it if the type comes from the current being written module file.
7740 // Since the current module file being written logically has the highest
7741 // index.
7742 unsigned ModuleFileIndex = StoredIdx.getModuleFileIndex();
7743 if (ModuleFileIndex == 0 && StoredIdx.getValue())
7744 return;
7745
7746 // Otherwise, keep the highest ID since the module file comes later has
7747 // higher module file indexes.
7748 if (Idx.getModuleFileIndex() >= StoredIdx.getModuleFileIndex())
7749 StoredIdx = Idx;
7750}
7751
7752void ASTWriter::PredefinedDeclBuilt(PredefinedDeclIDs ID, const Decl *D) {
7753 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
7754 DeclIDs[D] = LocalDeclID(ID);
7755 PredefinedDecls.insert(D);
7756}
7757
7758void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
7759 // Always keep the highest ID. See \p TypeRead() for more information.
7760 SelectorID &StoredID = SelectorIDs[S];
7761 if (ID > StoredID)
7762 StoredID = ID;
7763}
7764
7765void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
7767 assert(!MacroDefinitions.contains(MD));
7768 MacroDefinitions[MD] = ID;
7769}
7770
7771void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
7772 assert(!SubmoduleIDs.contains(Mod));
7773 SubmoduleIDs[Mod] = ID;
7774}
7775
7776void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
7777 if (Chain && Chain->isProcessingUpdateRecords()) return;
7778 assert(D->isCompleteDefinition());
7779 assert(!WritingAST && "Already writing the AST!");
7780 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7781 // We are interested when a PCH decl is modified.
7782 if (RD->isFromASTFile()) {
7783 // A forward reference was mutated into a definition. Rewrite it.
7784 // FIXME: This happens during template instantiation, should we
7785 // have created a new definition decl instead ?
7786 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
7787 "completed a tag from another module but not by instantiation?");
7788 DeclUpdates[RD].push_back(
7789 DeclUpdate(DeclUpdateKind::CXXInstantiatedClassDefinition));
7790 }
7791 }
7792}
7793
7794static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
7795 if (D->isFromASTFile())
7796 return true;
7797
7798 // The predefined __va_list_tag struct is imported if we imported any decls.
7799 // FIXME: This is a gross hack.
7800 return D == D->getASTContext().getVaListTagDecl();
7801}
7802
7803void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
7804 if (Chain && Chain->isProcessingUpdateRecords()) return;
7805 assert(DC->isLookupContext() &&
7806 "Should not add lookup results to non-lookup contexts!");
7807
7808 // TU is handled elsewhere.
7810 return;
7811
7812 // Namespaces are handled elsewhere, except for template instantiations of
7813 // FunctionTemplateDecls in namespaces. We are interested in cases where the
7814 // local instantiations are added to an imported context. Only happens when
7815 // adding ADL lookup candidates, for example templated friends.
7818 return;
7819
7820 // We're only interested in cases where a local declaration is added to an
7821 // imported context.
7822 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
7823 return;
7824
7825 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
7826 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
7827 assert(!WritingAST && "Already writing the AST!");
7828 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
7829 // We're adding a visible declaration to a predefined decl context. Ensure
7830 // that we write out all of its lookup results so we don't get a nasty
7831 // surprise when we try to emit its lookup table.
7832 llvm::append_range(DeclsToEmitEvenIfUnreferenced, DC->decls());
7833 }
7834 DeclsToEmitEvenIfUnreferenced.push_back(D);
7835}
7836
7837void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
7838 if (Chain && Chain->isProcessingUpdateRecords()) return;
7839 assert(D->isImplicit());
7840
7841 // We're only interested in cases where a local declaration is added to an
7842 // imported context.
7843 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
7844 return;
7845
7846 if (!isa<CXXMethodDecl>(D))
7847 return;
7848
7849 // A decl coming from PCH was modified.
7850 assert(RD->isCompleteDefinition());
7851 assert(!WritingAST && "Already writing the AST!");
7852 DeclUpdates[RD].push_back(
7853 DeclUpdate(DeclUpdateKind::CXXAddedImplicitMember, D));
7854}
7855
7856void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
7857 if (Chain && Chain->isProcessingUpdateRecords()) return;
7858 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
7859 if (!Chain) return;
7860 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
7861 // If we don't already know the exception specification for this redecl
7862 // chain, add an update record for it.
7864 ->getType()
7865 ->castAs<FunctionProtoType>()
7866 ->getExceptionSpecType()))
7867 DeclUpdates[D].push_back(DeclUpdateKind::CXXResolvedExceptionSpec);
7868 });
7869}
7870
7871void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
7872 if (Chain && Chain->isProcessingUpdateRecords()) return;
7873 assert(!WritingAST && "Already writing the AST!");
7874 if (!Chain) return;
7875 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
7876 DeclUpdates[D].push_back(
7877 DeclUpdate(DeclUpdateKind::CXXDeducedReturnType, ReturnType));
7878 });
7879}
7880
7881void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
7882 const FunctionDecl *Delete,
7883 Expr *ThisArg) {
7884 if (Chain && Chain->isProcessingUpdateRecords()) return;
7885 assert(!WritingAST && "Already writing the AST!");
7886 assert(Delete && "Not given an operator delete");
7887 if (!Chain) return;
7888 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
7889 DeclUpdates[D].push_back(
7890 DeclUpdate(DeclUpdateKind::CXXResolvedDtorDelete, Delete));
7891 });
7892}
7893
7894void ASTWriter::ResolvedOperatorGlobDelete(const CXXDestructorDecl *DD,
7895 const FunctionDecl *GlobDelete) {
7896 if (Chain && Chain->isProcessingUpdateRecords())
7897 return;
7898 assert(!WritingAST && "Already writing the AST!");
7899 assert(GlobDelete && "Not given an operator delete");
7900 if (!Chain)
7901 return;
7902 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
7903 DeclUpdates[D].push_back(
7904 DeclUpdate(DeclUpdateKind::CXXResolvedDtorGlobDelete, GlobDelete));
7905 });
7906}
7907
7908void ASTWriter::ResolvedOperatorArrayDelete(const CXXDestructorDecl *DD,
7909 const FunctionDecl *ArrayDelete) {
7910 if (Chain && Chain->isProcessingUpdateRecords())
7911 return;
7912 assert(!WritingAST && "Already writing the AST!");
7913 assert(ArrayDelete && "Not given an operator delete");
7914 if (!Chain)
7915 return;
7916 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
7917 DeclUpdates[D].push_back(
7918 DeclUpdate(DeclUpdateKind::CXXResolvedDtorArrayDelete, ArrayDelete));
7919 });
7920}
7921
7922void ASTWriter::ResolvedOperatorGlobArrayDelete(
7923 const CXXDestructorDecl *DD, const FunctionDecl *GlobArrayDelete) {
7924 if (Chain && Chain->isProcessingUpdateRecords())
7925 return;
7926 assert(!WritingAST && "Already writing the AST!");
7927 assert(GlobArrayDelete && "Not given an operator delete");
7928 if (!Chain)
7929 return;
7930 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
7931 DeclUpdates[D].push_back(DeclUpdate(
7932 DeclUpdateKind::CXXResolvedDtorGlobArrayDelete, GlobArrayDelete));
7933 });
7934}
7935
7936void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
7937 if (Chain && Chain->isProcessingUpdateRecords()) return;
7938 assert(!WritingAST && "Already writing the AST!");
7939 if (!D->isFromASTFile())
7940 return; // Declaration not imported from PCH.
7941
7942 // The function definition may not have a body due to parsing errors.
7944 return;
7945
7946 // Implicit function decl from a PCH was defined.
7947 DeclUpdates[D].push_back(
7948 DeclUpdate(DeclUpdateKind::CXXAddedFunctionDefinition));
7949}
7950
7951void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
7952 if (Chain && Chain->isProcessingUpdateRecords()) return;
7953 assert(!WritingAST && "Already writing the AST!");
7954 if (!D->isFromASTFile())
7955 return;
7956
7957 DeclUpdates[D].push_back(DeclUpdate(DeclUpdateKind::CXXAddedVarDefinition));
7958}
7959
7960void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
7961 if (Chain && Chain->isProcessingUpdateRecords()) return;
7962 assert(!WritingAST && "Already writing the AST!");
7963 if (!D->isFromASTFile())
7964 return;
7965
7966 // The function definition may not have a body due to parsing errors.
7968 return;
7969
7970 DeclUpdates[D].push_back(
7971 DeclUpdate(DeclUpdateKind::CXXAddedFunctionDefinition));
7972}
7973
7974void ASTWriter::InstantiationRequested(const ValueDecl *D) {
7975 if (Chain && Chain->isProcessingUpdateRecords()) return;
7976 assert(!WritingAST && "Already writing the AST!");
7977 if (!D->isFromASTFile())
7978 return;
7979
7980 // Since the actual instantiation is delayed, this really means that we need
7981 // to update the instantiation location.
7982 SourceLocation POI;
7983 if (auto *VD = dyn_cast<VarDecl>(D))
7984 POI = VD->getPointOfInstantiation();
7985 else
7986 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
7987 DeclUpdates[D].push_back(
7988 DeclUpdate(DeclUpdateKind::CXXPointOfInstantiation, POI));
7989}
7990
7991void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
7992 if (Chain && Chain->isProcessingUpdateRecords()) return;
7993 assert(!WritingAST && "Already writing the AST!");
7994 if (!D->isFromASTFile())
7995 return;
7996
7997 DeclUpdates[D].push_back(
7998 DeclUpdate(DeclUpdateKind::CXXInstantiatedDefaultArgument, D));
7999}
8000
8001void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
8002 assert(!WritingAST && "Already writing the AST!");
8003 if (!D->isFromASTFile())
8004 return;
8005
8006 DeclUpdates[D].push_back(
8007 DeclUpdate(DeclUpdateKind::CXXInstantiatedDefaultMemberInitializer, D));
8008}
8009
8010void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
8011 const ObjCInterfaceDecl *IFD) {
8012 if (Chain && Chain->isProcessingUpdateRecords()) return;
8013 assert(!WritingAST && "Already writing the AST!");
8014 if (!IFD->isFromASTFile())
8015 return; // Declaration not imported from PCH.
8016
8017 assert(IFD->getDefinition() && "Category on a class without a definition?");
8018 ObjCClassesWithCategories.insert(
8019 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
8020}
8021
8022void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
8023 if (Chain && Chain->isProcessingUpdateRecords()) return;
8024 assert(!WritingAST && "Already writing the AST!");
8025
8026 // If there is *any* declaration of the entity that's not from an AST file,
8027 // we can skip writing the update record. We make sure that isUsed() triggers
8028 // completion of the redeclaration chain of the entity.
8029 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
8030 if (IsLocalDecl(Prev))
8031 return;
8032
8033 DeclUpdates[D].push_back(DeclUpdate(DeclUpdateKind::DeclMarkedUsed));
8034}
8035
8036void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
8037 if (Chain && Chain->isProcessingUpdateRecords()) return;
8038 assert(!WritingAST && "Already writing the AST!");
8039 if (!D->isFromASTFile())
8040 return;
8041
8042 DeclUpdates[D].push_back(
8043 DeclUpdate(DeclUpdateKind::DeclMarkedOpenMPThreadPrivate));
8044}
8045
8046void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
8047 if (Chain && Chain->isProcessingUpdateRecords()) return;
8048 assert(!WritingAST && "Already writing the AST!");
8049 if (!D->isFromASTFile())
8050 return;
8051
8052 DeclUpdates[D].push_back(
8053 DeclUpdate(DeclUpdateKind::DeclMarkedOpenMPAllocate, A));
8054}
8055
8056void ASTWriter::DeclarationMarkedOpenMPIndirectCall(const Decl *D) {
8057 if (Chain && Chain->isProcessingUpdateRecords())
8058 return;
8059 assert(!WritingAST && "Already writing the AST!");
8060 if (!D->isFromASTFile())
8061 return;
8062
8063 DeclUpdates[D].push_back(
8064 DeclUpdate(DeclUpdateKind::DeclMarkedOpenMPIndirectCall));
8065}
8066
8067void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
8068 const Attr *Attr) {
8069 if (Chain && Chain->isProcessingUpdateRecords()) return;
8070 assert(!WritingAST && "Already writing the AST!");
8071 if (!D->isFromASTFile())
8072 return;
8073
8074 DeclUpdates[D].push_back(
8075 DeclUpdate(DeclUpdateKind::DeclMarkedOpenMPDeclareTarget, Attr));
8076}
8077
8078void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
8079 if (Chain && Chain->isProcessingUpdateRecords()) return;
8080 assert(!WritingAST && "Already writing the AST!");
8081 assert(!D->isUnconditionallyVisible() && "expected a hidden declaration");
8082 DeclUpdates[D].push_back(DeclUpdate(DeclUpdateKind::DeclExported, M));
8083}
8084
8085void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
8086 const RecordDecl *Record) {
8087 if (Chain && Chain->isProcessingUpdateRecords()) return;
8088 assert(!WritingAST && "Already writing the AST!");
8089 if (!Record->isFromASTFile())
8090 return;
8091 DeclUpdates[Record].push_back(
8092 DeclUpdate(DeclUpdateKind::AddedAttrToRecord, Attr));
8093}
8094
8095void ASTWriter::AddedCXXTemplateSpecialization(
8097 assert(!WritingAST && "Already writing the AST!");
8098
8099 if (!TD->getFirstDecl()->isFromASTFile())
8100 return;
8101 if (Chain && Chain->isProcessingUpdateRecords())
8102 return;
8103
8104 DeclsToEmitEvenIfUnreferenced.push_back(D);
8105}
8106
8107void ASTWriter::AddedCXXTemplateSpecialization(
8108 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
8109 assert(!WritingAST && "Already writing the AST!");
8110
8111 if (!TD->getFirstDecl()->isFromASTFile())
8112 return;
8113 if (Chain && Chain->isProcessingUpdateRecords())
8114 return;
8115
8116 DeclsToEmitEvenIfUnreferenced.push_back(D);
8117}
8118
8119void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
8120 const FunctionDecl *D) {
8121 assert(!WritingAST && "Already writing the AST!");
8122
8123 if (!TD->getFirstDecl()->isFromASTFile())
8124 return;
8125 if (Chain && Chain->isProcessingUpdateRecords())
8126 return;
8127
8128 DeclsToEmitEvenIfUnreferenced.push_back(D);
8129}
8130
8131//===----------------------------------------------------------------------===//
8132//// OMPClause Serialization
8133////===----------------------------------------------------------------------===//
8134
8135namespace {
8136
8137class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
8138 ASTRecordWriter &Record;
8139
8140public:
8141 OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
8142#define GEN_CLANG_CLAUSE_CLASS
8143#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
8144#include "llvm/Frontend/OpenMP/OMP.inc"
8145 void writeClause(OMPClause *C);
8146 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
8147 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
8148};
8149
8150}
8151
8153 OMPClauseWriter(*this).writeClause(C);
8154}
8155
8156void OMPClauseWriter::writeClause(OMPClause *C) {
8157 Record.push_back(unsigned(C->getClauseKind()));
8158 Visit(C);
8159 Record.AddSourceLocation(C->getBeginLoc());
8160 Record.AddSourceLocation(C->getEndLoc());
8161}
8162
8163void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
8164 Record.push_back(uint64_t(C->getCaptureRegion()));
8165 Record.AddStmt(C->getPreInitStmt());
8166}
8167
8168void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
8169 VisitOMPClauseWithPreInit(C);
8170 Record.AddStmt(C->getPostUpdateExpr());
8171}
8172
8173void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
8174 VisitOMPClauseWithPreInit(C);
8175 Record.push_back(uint64_t(C->getNameModifier()));
8176 Record.AddSourceLocation(C->getNameModifierLoc());
8177 Record.AddSourceLocation(C->getColonLoc());
8178 Record.AddStmt(C->getCondition());
8179 Record.AddSourceLocation(C->getLParenLoc());
8180}
8181
8182void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
8183 VisitOMPClauseWithPreInit(C);
8184 Record.AddStmt(C->getCondition());
8185 Record.AddSourceLocation(C->getLParenLoc());
8186}
8187
8188void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
8189 Record.push_back(C->varlist_size());
8190 Record.writeEnum(C->getPrescriptivenessModifier());
8191 Record.AddSourceLocation(C->getPrescriptivenessModifierLoc());
8192 Record.writeEnum(C->getDimsModifier());
8193 Record.AddSourceLocation(C->getDimsModifierLoc());
8194 Record.AddStmt(C->getDimsModifierExpr());
8195 VisitOMPClauseWithPreInit(C);
8196 Record.AddSourceLocation(C->getLParenLoc());
8197 for (auto *VE : C->varlist())
8198 Record.AddStmt(VE);
8199}
8200
8201void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
8202 Record.AddStmt(C->getSafelen());
8203 Record.AddSourceLocation(C->getLParenLoc());
8204}
8205
8206void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
8207 Record.AddStmt(C->getSimdlen());
8208 Record.AddSourceLocation(C->getLParenLoc());
8209}
8210
8211void OMPClauseWriter::VisitOMPSizesClause(OMPSizesClause *C) {
8212 Record.push_back(C->getNumSizes());
8213 for (Expr *Size : C->getSizesRefs())
8214 Record.AddStmt(Size);
8215 Record.AddSourceLocation(C->getLParenLoc());
8216}
8217
8218void OMPClauseWriter::VisitOMPCountsClause(OMPCountsClause *C) {
8219 Record.push_back(C->getNumCounts());
8220 Record.push_back(C->hasOmpFill());
8221 if (C->hasOmpFill())
8222 Record.push_back(*C->getOmpFillIndex());
8223 Record.AddSourceLocation(C->getOmpFillLoc());
8224 for (Expr *Count : C->getCountsRefs())
8225 Record.AddStmt(Count);
8226 Record.AddSourceLocation(C->getLParenLoc());
8227}
8228
8229void OMPClauseWriter::VisitOMPPermutationClause(OMPPermutationClause *C) {
8230 Record.push_back(C->getNumLoops());
8231 for (Expr *Size : C->getArgsRefs())
8232 Record.AddStmt(Size);
8233 Record.AddSourceLocation(C->getLParenLoc());
8234}
8235
8236void OMPClauseWriter::VisitOMPFullClause(OMPFullClause *C) {}
8237
8238void OMPClauseWriter::VisitOMPPartialClause(OMPPartialClause *C) {
8239 Record.AddStmt(C->getFactor());
8240 Record.AddSourceLocation(C->getLParenLoc());
8241}
8242
8243void OMPClauseWriter::VisitOMPDepthClause(OMPDepthClause *C) {
8244 Record.AddStmt(C->getDepth());
8245 Record.AddSourceLocation(C->getLParenLoc());
8246}
8247
8248void OMPClauseWriter::VisitOMPLoopRangeClause(OMPLoopRangeClause *C) {
8249 Record.AddStmt(C->getFirst());
8250 Record.AddStmt(C->getCount());
8251 Record.AddSourceLocation(C->getLParenLoc());
8252 Record.AddSourceLocation(C->getFirstLoc());
8253 Record.AddSourceLocation(C->getCountLoc());
8254}
8255
8256void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
8257 Record.AddStmt(C->getAllocator());
8258 Record.AddSourceLocation(C->getLParenLoc());
8259}
8260
8261void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
8262 Record.AddStmt(C->getNumForLoops());
8263 Record.AddSourceLocation(C->getLParenLoc());
8264}
8265
8266void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) {
8267 Record.AddStmt(C->getEventHandler());
8268 Record.AddSourceLocation(C->getLParenLoc());
8269}
8270
8271void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
8272 Record.push_back(unsigned(C->getDefaultKind()));
8273 Record.AddSourceLocation(C->getLParenLoc());
8274 Record.AddSourceLocation(C->getDefaultKindKwLoc());
8275 Record.push_back(unsigned(C->getDefaultVC()));
8276 Record.AddSourceLocation(C->getDefaultVCLoc());
8277}
8278
8279void OMPClauseWriter::VisitOMPThreadsetClause(OMPThreadsetClause *C) {
8280 Record.AddSourceLocation(C->getLParenLoc());
8281 Record.AddSourceLocation(C->getThreadsetKindLoc());
8282 Record.writeEnum(C->getThreadsetKind());
8283}
8284
8285void OMPClauseWriter::VisitOMPTransparentClause(OMPTransparentClause *C) {
8286 Record.AddSourceLocation(C->getLParenLoc());
8287 Record.AddStmt(C->getImpexType());
8288}
8289
8290void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
8291 Record.push_back(unsigned(C->getProcBindKind()));
8292 Record.AddSourceLocation(C->getLParenLoc());
8293 Record.AddSourceLocation(C->getProcBindKindKwLoc());
8294}
8295
8296void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
8297 VisitOMPClauseWithPreInit(C);
8298 Record.push_back(C->getScheduleKind());
8299 Record.push_back(C->getFirstScheduleModifier());
8300 Record.push_back(C->getSecondScheduleModifier());
8301 Record.AddStmt(C->getChunkSize());
8302 Record.AddSourceLocation(C->getLParenLoc());
8303 Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
8304 Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
8305 Record.AddSourceLocation(C->getScheduleKindLoc());
8306 Record.AddSourceLocation(C->getCommaLoc());
8307}
8308
8309void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
8310 Record.push_back(C->getLoopNumIterations().size());
8311 Record.AddStmt(C->getNumForLoops());
8312 for (Expr *NumIter : C->getLoopNumIterations())
8313 Record.AddStmt(NumIter);
8314 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
8315 Record.AddStmt(C->getLoopCounter(I));
8316 Record.AddSourceLocation(C->getLParenLoc());
8317}
8318
8319void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *C) {
8320 Record.AddStmt(C->getCondition());
8321 Record.AddSourceLocation(C->getLParenLoc());
8322}
8323
8324void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
8325
8326void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
8327
8328void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
8329
8330void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
8331
8332void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *) {}
8333
8334void OMPClauseWriter::VisitOMPUpdateDependObjectsClause(
8335 OMPUpdateDependObjectsClause *C) {
8336 Record.AddSourceLocation(C->getLParenLoc());
8337 Record.AddSourceLocation(C->getArgumentLoc());
8338 Record.writeEnum(C->getDependencyKind());
8339}
8340
8341void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
8342
8343void OMPClauseWriter::VisitOMPCompareClause(OMPCompareClause *) {}
8344
8345// Save the parameter of fail clause.
8346void OMPClauseWriter::VisitOMPFailClause(OMPFailClause *C) {
8347 Record.AddSourceLocation(C->getLParenLoc());
8348 Record.AddSourceLocation(C->getFailParameterLoc());
8349 Record.writeEnum(C->getFailParameter());
8350}
8351
8352void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
8353
8354void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
8355
8356void OMPClauseWriter::VisitOMPAbsentClause(OMPAbsentClause *C) {
8357 Record.push_back(static_cast<uint64_t>(C->getDirectiveKinds().size()));
8358 Record.AddSourceLocation(C->getLParenLoc());
8359 for (auto K : C->getDirectiveKinds()) {
8360 Record.writeEnum(K);
8361 }
8362}
8363
8364void OMPClauseWriter::VisitOMPHoldsClause(OMPHoldsClause *C) {
8365 Record.AddStmt(C->getExpr());
8366 Record.AddSourceLocation(C->getLParenLoc());
8367}
8368
8369void OMPClauseWriter::VisitOMPContainsClause(OMPContainsClause *C) {
8370 Record.push_back(static_cast<uint64_t>(C->getDirectiveKinds().size()));
8371 Record.AddSourceLocation(C->getLParenLoc());
8372 for (auto K : C->getDirectiveKinds()) {
8373 Record.writeEnum(K);
8374 }
8375}
8376
8377void OMPClauseWriter::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
8378
8379void OMPClauseWriter::VisitOMPNoOpenMPRoutinesClause(
8380 OMPNoOpenMPRoutinesClause *) {}
8381
8382void OMPClauseWriter::VisitOMPNoOpenMPConstructsClause(
8383 OMPNoOpenMPConstructsClause *) {}
8384
8385void OMPClauseWriter::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
8386
8387void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {}
8388
8389void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {}
8390
8391void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
8392
8393void OMPClauseWriter::VisitOMPWeakClause(OMPWeakClause *) {}
8394
8395void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
8396
8397void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
8398
8399void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
8400
8401void OMPClauseWriter::VisitOMPInitClause(OMPInitClause *C) {
8402 // Sizes for CreateEmpty on the read side: varlist_size = 1 + NumPrefs, then
8403 // NumAttrs (total attrs across all pref-specs).
8404 Record.push_back(C->varlist_size());
8405 Record.push_back(C->attrs().size());
8406 // Varlist (interop var + Fr block).
8407 for (Expr *VE : C->varlist())
8408 Record.AddStmt(VE);
8409 Record.writeBool(C->getIsTarget());
8410 Record.writeBool(C->getIsTargetSync());
8411 Record.writeBool(C->hasPreferAttrs());
8412 // Per-pref-spec: attr count + that many attr exprs, in order.
8413 for (OMPInitClause::PrefView P : C->prefs()) {
8414 Record.push_back(P.Attrs.size());
8415 for (Expr *A : P.Attrs)
8416 Record.AddStmt(A);
8417 }
8418 Record.AddSourceLocation(C->getLParenLoc());
8419 Record.AddSourceLocation(C->getVarLoc());
8420}
8421
8422void OMPClauseWriter::VisitOMPUseClause(OMPUseClause *C) {
8423 Record.AddStmt(C->getInteropVar());
8424 Record.AddSourceLocation(C->getLParenLoc());
8425 Record.AddSourceLocation(C->getVarLoc());
8426}
8427
8428void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *C) {
8429 Record.AddStmt(C->getInteropVar());
8430 Record.AddSourceLocation(C->getLParenLoc());
8431 Record.AddSourceLocation(C->getVarLoc());
8432}
8433
8434void OMPClauseWriter::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
8435 VisitOMPClauseWithPreInit(C);
8436 Record.AddStmt(C->getCondition());
8437 Record.AddSourceLocation(C->getLParenLoc());
8438}
8439
8440void OMPClauseWriter::VisitOMPNocontextClause(OMPNocontextClause *C) {
8441 VisitOMPClauseWithPreInit(C);
8442 Record.AddStmt(C->getCondition());
8443 Record.AddSourceLocation(C->getLParenLoc());
8444}
8445
8446void OMPClauseWriter::VisitOMPFilterClause(OMPFilterClause *C) {
8447 VisitOMPClauseWithPreInit(C);
8448 Record.AddStmt(C->getThreadID());
8449 Record.AddSourceLocation(C->getLParenLoc());
8450}
8451
8452void OMPClauseWriter::VisitOMPAlignClause(OMPAlignClause *C) {
8453 Record.AddStmt(C->getAlignment());
8454 Record.AddSourceLocation(C->getLParenLoc());
8455}
8456
8457void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
8458 Record.push_back(C->varlist_size());
8459 Record.AddSourceLocation(C->getLParenLoc());
8460 for (auto *VE : C->varlist()) {
8461 Record.AddStmt(VE);
8462 }
8463 for (auto *VE : C->private_copies()) {
8464 Record.AddStmt(VE);
8465 }
8466}
8467
8468void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
8469 Record.push_back(C->varlist_size());
8470 VisitOMPClauseWithPreInit(C);
8471 Record.AddSourceLocation(C->getLParenLoc());
8472 for (auto *VE : C->varlist()) {
8473 Record.AddStmt(VE);
8474 }
8475 for (auto *VE : C->private_copies()) {
8476 Record.AddStmt(VE);
8477 }
8478 for (auto *VE : C->inits()) {
8479 Record.AddStmt(VE);
8480 }
8481}
8482
8483void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
8484 Record.push_back(C->varlist_size());
8485 VisitOMPClauseWithPostUpdate(C);
8486 Record.AddSourceLocation(C->getLParenLoc());
8487 Record.writeEnum(C->getKind());
8488 Record.AddSourceLocation(C->getKindLoc());
8489 Record.AddSourceLocation(C->getColonLoc());
8490 for (auto *VE : C->varlist())
8491 Record.AddStmt(VE);
8492 for (auto *E : C->private_copies())
8493 Record.AddStmt(E);
8494 for (auto *E : C->source_exprs())
8495 Record.AddStmt(E);
8496 for (auto *E : C->destination_exprs())
8497 Record.AddStmt(E);
8498 for (auto *E : C->assignment_ops())
8499 Record.AddStmt(E);
8500}
8501
8502void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
8503 Record.push_back(C->varlist_size());
8504 Record.AddSourceLocation(C->getLParenLoc());
8505 for (auto *VE : C->varlist())
8506 Record.AddStmt(VE);
8507}
8508
8509void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
8510 Record.push_back(C->varlist_size());
8511 Record.writeEnum(C->getModifier());
8512 VisitOMPClauseWithPostUpdate(C);
8513 Record.AddSourceLocation(C->getLParenLoc());
8514 Record.AddSourceLocation(C->getModifierLoc());
8515 Record.AddSourceLocation(C->getColonLoc());
8516 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
8517 Record.AddDeclarationNameInfo(C->getNameInfo());
8518 for (auto *VE : C->varlist())
8519 Record.AddStmt(VE);
8520 for (auto *VE : C->privates())
8521 Record.AddStmt(VE);
8522 for (auto *E : C->lhs_exprs())
8523 Record.AddStmt(E);
8524 for (auto *E : C->rhs_exprs())
8525 Record.AddStmt(E);
8526 for (auto *E : C->reduction_ops())
8527 Record.AddStmt(E);
8528 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
8529 for (auto *E : C->copy_ops())
8530 Record.AddStmt(E);
8531 for (auto *E : C->copy_array_temps())
8532 Record.AddStmt(E);
8533 for (auto *E : C->copy_array_elems())
8534 Record.AddStmt(E);
8535 }
8536 auto PrivateFlags = C->private_var_reduction_flags();
8537 Record.push_back(std::distance(PrivateFlags.begin(), PrivateFlags.end()));
8538 for (bool Flag : PrivateFlags)
8539 Record.push_back(Flag);
8540}
8541
8542void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
8543 Record.push_back(C->varlist_size());
8544 VisitOMPClauseWithPostUpdate(C);
8545 Record.AddSourceLocation(C->getLParenLoc());
8546 Record.AddSourceLocation(C->getColonLoc());
8547 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
8548 Record.AddDeclarationNameInfo(C->getNameInfo());
8549 for (auto *VE : C->varlist())
8550 Record.AddStmt(VE);
8551 for (auto *VE : C->privates())
8552 Record.AddStmt(VE);
8553 for (auto *E : C->lhs_exprs())
8554 Record.AddStmt(E);
8555 for (auto *E : C->rhs_exprs())
8556 Record.AddStmt(E);
8557 for (auto *E : C->reduction_ops())
8558 Record.AddStmt(E);
8559}
8560
8561void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
8562 Record.push_back(C->varlist_size());
8563 VisitOMPClauseWithPostUpdate(C);
8564 Record.AddSourceLocation(C->getLParenLoc());
8565 Record.AddSourceLocation(C->getColonLoc());
8566 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
8567 Record.AddDeclarationNameInfo(C->getNameInfo());
8568 for (auto *VE : C->varlist())
8569 Record.AddStmt(VE);
8570 for (auto *VE : C->privates())
8571 Record.AddStmt(VE);
8572 for (auto *E : C->lhs_exprs())
8573 Record.AddStmt(E);
8574 for (auto *E : C->rhs_exprs())
8575 Record.AddStmt(E);
8576 for (auto *E : C->reduction_ops())
8577 Record.AddStmt(E);
8578 for (auto *E : C->taskgroup_descriptors())
8579 Record.AddStmt(E);
8580}
8581
8582void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
8583 Record.push_back(C->varlist_size());
8584 VisitOMPClauseWithPostUpdate(C);
8585 Record.AddSourceLocation(C->getLParenLoc());
8586 Record.AddSourceLocation(C->getColonLoc());
8587 Record.push_back(C->getModifier());
8588 Record.AddSourceLocation(C->getModifierLoc());
8589 for (auto *VE : C->varlist()) {
8590 Record.AddStmt(VE);
8591 }
8592 for (auto *VE : C->privates()) {
8593 Record.AddStmt(VE);
8594 }
8595 for (auto *VE : C->inits()) {
8596 Record.AddStmt(VE);
8597 }
8598 for (auto *VE : C->updates()) {
8599 Record.AddStmt(VE);
8600 }
8601 for (auto *VE : C->finals()) {
8602 Record.AddStmt(VE);
8603 }
8604 Record.AddStmt(C->getStep());
8605 Record.AddStmt(C->getCalcStep());
8606 for (auto *VE : C->used_expressions())
8607 Record.AddStmt(VE);
8608}
8609
8610void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
8611 Record.push_back(C->varlist_size());
8612 Record.AddSourceLocation(C->getLParenLoc());
8613 Record.AddSourceLocation(C->getColonLoc());
8614 for (auto *VE : C->varlist())
8615 Record.AddStmt(VE);
8616 Record.AddStmt(C->getAlignment());
8617}
8618
8619void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
8620 Record.push_back(C->varlist_size());
8621 Record.AddSourceLocation(C->getLParenLoc());
8622 for (auto *VE : C->varlist())
8623 Record.AddStmt(VE);
8624 for (auto *E : C->source_exprs())
8625 Record.AddStmt(E);
8626 for (auto *E : C->destination_exprs())
8627 Record.AddStmt(E);
8628 for (auto *E : C->assignment_ops())
8629 Record.AddStmt(E);
8630}
8631
8632void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
8633 Record.push_back(C->varlist_size());
8634 Record.AddSourceLocation(C->getLParenLoc());
8635 for (auto *VE : C->varlist())
8636 Record.AddStmt(VE);
8637 for (auto *E : C->source_exprs())
8638 Record.AddStmt(E);
8639 for (auto *E : C->destination_exprs())
8640 Record.AddStmt(E);
8641 for (auto *E : C->assignment_ops())
8642 Record.AddStmt(E);
8643}
8644
8645void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
8646 Record.push_back(C->varlist_size());
8647 Record.AddSourceLocation(C->getLParenLoc());
8648 for (auto *VE : C->varlist())
8649 Record.AddStmt(VE);
8650}
8651
8652void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) {
8653 Record.AddStmt(C->getDepobj());
8654 Record.AddSourceLocation(C->getLParenLoc());
8655}
8656
8657void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
8658 Record.push_back(C->varlist_size());
8659 Record.push_back(C->getNumLoops());
8660 Record.AddSourceLocation(C->getLParenLoc());
8661 Record.AddStmt(C->getModifier());
8662 Record.push_back(C->getDependencyKind());
8663 Record.AddSourceLocation(C->getDependencyLoc());
8664 Record.AddSourceLocation(C->getColonLoc());
8665 Record.AddSourceLocation(C->getOmpAllMemoryLoc());
8666 for (auto *VE : C->varlist())
8667 Record.AddStmt(VE);
8668 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
8669 Record.AddStmt(C->getLoopData(I));
8670}
8671
8672void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
8673 VisitOMPClauseWithPreInit(C);
8674 Record.writeEnum(C->getModifier());
8675 Record.AddStmt(C->getDevice());
8676 Record.AddSourceLocation(C->getModifierLoc());
8677 Record.AddSourceLocation(C->getLParenLoc());
8678}
8679
8680void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
8681 Record.push_back(C->varlist_size());
8682 Record.push_back(C->getUniqueDeclarationsNum());
8683 Record.push_back(C->getTotalComponentListNum());
8684 Record.push_back(C->getTotalComponentsNum());
8685 Record.AddSourceLocation(C->getLParenLoc());
8686 bool HasIteratorModifier = false;
8687 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
8688 Record.push_back(C->getMapTypeModifier(I));
8689 Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
8690 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
8691 HasIteratorModifier = true;
8692 }
8693 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
8694 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
8695 Record.push_back(C->getMapType());
8696 Record.AddSourceLocation(C->getMapLoc());
8697 Record.AddSourceLocation(C->getColonLoc());
8698 for (auto *E : C->varlist())
8699 Record.AddStmt(E);
8700 for (auto *E : C->mapperlists())
8701 Record.AddStmt(E);
8702 if (HasIteratorModifier)
8703 Record.AddStmt(C->getIteratorModifier());
8704 for (auto *D : C->all_decls())
8705 Record.AddDeclRef(D);
8706 for (auto N : C->all_num_lists())
8707 Record.push_back(N);
8708 for (auto N : C->all_lists_sizes())
8709 Record.push_back(N);
8710 for (auto &M : C->all_components()) {
8711 Record.AddStmt(M.getAssociatedExpression());
8712 Record.AddDeclRef(M.getAssociatedDeclaration());
8713 }
8714}
8715
8716void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
8717 Record.push_back(C->varlist_size());
8718 Record.writeEnum(C->getFirstAllocateModifier());
8719 Record.writeEnum(C->getSecondAllocateModifier());
8720 Record.AddSourceLocation(C->getLParenLoc());
8721 Record.AddSourceLocation(C->getColonLoc());
8722 Record.AddStmt(C->getAllocator());
8723 Record.AddStmt(C->getAlignment());
8724 for (auto *VE : C->varlist())
8725 Record.AddStmt(VE);
8726}
8727
8728void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
8729 Record.push_back(C->varlist_size());
8730 Record.writeEnum(C->getModifier());
8731 Record.AddSourceLocation(C->getModifierLoc());
8732 Record.AddStmt(C->getModifierExpr());
8733 VisitOMPClauseWithPreInit(C);
8734 Record.AddSourceLocation(C->getLParenLoc());
8735 for (auto *VE : C->varlist())
8736 Record.AddStmt(VE);
8737}
8738
8739void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
8740 Record.push_back(C->varlist_size());
8741 Record.writeEnum(C->getModifier());
8742 Record.AddSourceLocation(C->getModifierLoc());
8743 Record.AddStmt(C->getModifierExpr());
8744 VisitOMPClauseWithPreInit(C);
8745 Record.AddSourceLocation(C->getLParenLoc());
8746 for (auto *VE : C->varlist())
8747 Record.AddStmt(VE);
8748}
8749
8750void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
8751 VisitOMPClauseWithPreInit(C);
8752 Record.AddStmt(C->getPriority());
8753 Record.AddSourceLocation(C->getLParenLoc());
8754}
8755
8756void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
8757 VisitOMPClauseWithPreInit(C);
8758 Record.writeEnum(C->getModifier());
8759 Record.AddStmt(C->getGrainsize());
8760 Record.AddSourceLocation(C->getModifierLoc());
8761 Record.AddSourceLocation(C->getLParenLoc());
8762}
8763
8764void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
8765 VisitOMPClauseWithPreInit(C);
8766 Record.writeEnum(C->getModifier());
8767 Record.AddStmt(C->getNumTasks());
8768 Record.AddSourceLocation(C->getModifierLoc());
8769 Record.AddSourceLocation(C->getLParenLoc());
8770}
8771
8772void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
8773 Record.AddStmt(C->getHint());
8774 Record.AddSourceLocation(C->getLParenLoc());
8775}
8776
8777void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
8778 VisitOMPClauseWithPreInit(C);
8779 Record.push_back(C->getDistScheduleKind());
8780 Record.AddStmt(C->getChunkSize());
8781 Record.AddSourceLocation(C->getLParenLoc());
8782 Record.AddSourceLocation(C->getDistScheduleKindLoc());
8783 Record.AddSourceLocation(C->getCommaLoc());
8784}
8785
8786void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
8787 Record.push_back(C->getDefaultmapKind());
8788 Record.push_back(C->getDefaultmapModifier());
8789 Record.AddSourceLocation(C->getLParenLoc());
8790 Record.AddSourceLocation(C->getDefaultmapModifierLoc());
8791 Record.AddSourceLocation(C->getDefaultmapKindLoc());
8792}
8793
8794void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
8795 Record.push_back(C->varlist_size());
8796 Record.push_back(C->getUniqueDeclarationsNum());
8797 Record.push_back(C->getTotalComponentListNum());
8798 Record.push_back(C->getTotalComponentsNum());
8799 Record.AddSourceLocation(C->getLParenLoc());
8800 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
8801 Record.push_back(C->getMotionModifier(I));
8802 Record.AddSourceLocation(C->getMotionModifierLoc(I));
8803 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
8804 Record.AddStmt(C->getIteratorModifier());
8805 }
8806 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
8807 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
8808 Record.AddSourceLocation(C->getColonLoc());
8809 for (auto *E : C->varlist())
8810 Record.AddStmt(E);
8811 for (auto *E : C->mapperlists())
8812 Record.AddStmt(E);
8813 for (auto *D : C->all_decls())
8814 Record.AddDeclRef(D);
8815 for (auto N : C->all_num_lists())
8816 Record.push_back(N);
8817 for (auto N : C->all_lists_sizes())
8818 Record.push_back(N);
8819 for (auto &M : C->all_components()) {
8820 Record.AddStmt(M.getAssociatedExpression());
8821 Record.writeBool(M.isNonContiguous());
8822 Record.AddDeclRef(M.getAssociatedDeclaration());
8823 }
8824}
8825
8826void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
8827 Record.push_back(C->varlist_size());
8828 Record.push_back(C->getUniqueDeclarationsNum());
8829 Record.push_back(C->getTotalComponentListNum());
8830 Record.push_back(C->getTotalComponentsNum());
8831 Record.AddSourceLocation(C->getLParenLoc());
8832 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
8833 Record.push_back(C->getMotionModifier(I));
8834 Record.AddSourceLocation(C->getMotionModifierLoc(I));
8835 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
8836 Record.AddStmt(C->getIteratorModifier());
8837 }
8838 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
8839 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
8840 Record.AddSourceLocation(C->getColonLoc());
8841 for (auto *E : C->varlist())
8842 Record.AddStmt(E);
8843 for (auto *E : C->mapperlists())
8844 Record.AddStmt(E);
8845 for (auto *D : C->all_decls())
8846 Record.AddDeclRef(D);
8847 for (auto N : C->all_num_lists())
8848 Record.push_back(N);
8849 for (auto N : C->all_lists_sizes())
8850 Record.push_back(N);
8851 for (auto &M : C->all_components()) {
8852 Record.AddStmt(M.getAssociatedExpression());
8853 Record.writeBool(M.isNonContiguous());
8854 Record.AddDeclRef(M.getAssociatedDeclaration());
8855 }
8856}
8857
8858void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
8859 Record.push_back(C->varlist_size());
8860 Record.push_back(C->getUniqueDeclarationsNum());
8861 Record.push_back(C->getTotalComponentListNum());
8862 Record.push_back(C->getTotalComponentsNum());
8863 Record.AddSourceLocation(C->getLParenLoc());
8864 Record.writeEnum(C->getFallbackModifier());
8865 Record.AddSourceLocation(C->getFallbackModifierLoc());
8866 for (auto *E : C->varlist())
8867 Record.AddStmt(E);
8868 for (auto *VE : C->private_copies())
8869 Record.AddStmt(VE);
8870 for (auto *VE : C->inits())
8871 Record.AddStmt(VE);
8872 for (auto *D : C->all_decls())
8873 Record.AddDeclRef(D);
8874 for (auto N : C->all_num_lists())
8875 Record.push_back(N);
8876 for (auto N : C->all_lists_sizes())
8877 Record.push_back(N);
8878 for (auto &M : C->all_components()) {
8879 Record.AddStmt(M.getAssociatedExpression());
8880 Record.AddDeclRef(M.getAssociatedDeclaration());
8881 }
8882}
8883
8884void OMPClauseWriter::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
8885 Record.push_back(C->varlist_size());
8886 Record.push_back(C->getUniqueDeclarationsNum());
8887 Record.push_back(C->getTotalComponentListNum());
8888 Record.push_back(C->getTotalComponentsNum());
8889 Record.AddSourceLocation(C->getLParenLoc());
8890 for (auto *E : C->varlist())
8891 Record.AddStmt(E);
8892 for (auto *D : C->all_decls())
8893 Record.AddDeclRef(D);
8894 for (auto N : C->all_num_lists())
8895 Record.push_back(N);
8896 for (auto N : C->all_lists_sizes())
8897 Record.push_back(N);
8898 for (auto &M : C->all_components()) {
8899 Record.AddStmt(M.getAssociatedExpression());
8900 Record.AddDeclRef(M.getAssociatedDeclaration());
8901 }
8902}
8903
8904void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
8905 Record.push_back(C->varlist_size());
8906 Record.push_back(C->getUniqueDeclarationsNum());
8907 Record.push_back(C->getTotalComponentListNum());
8908 Record.push_back(C->getTotalComponentsNum());
8909 Record.AddSourceLocation(C->getLParenLoc());
8910 for (auto *E : C->varlist())
8911 Record.AddStmt(E);
8912 for (auto *D : C->all_decls())
8913 Record.AddDeclRef(D);
8914 for (auto N : C->all_num_lists())
8915 Record.push_back(N);
8916 for (auto N : C->all_lists_sizes())
8917 Record.push_back(N);
8918 for (auto &M : C->all_components()) {
8919 Record.AddStmt(M.getAssociatedExpression());
8920 Record.AddDeclRef(M.getAssociatedDeclaration());
8921 }
8922}
8923
8924void OMPClauseWriter::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
8925 Record.push_back(C->varlist_size());
8926 Record.push_back(C->getUniqueDeclarationsNum());
8927 Record.push_back(C->getTotalComponentListNum());
8928 Record.push_back(C->getTotalComponentsNum());
8929 Record.AddSourceLocation(C->getLParenLoc());
8930 for (auto *E : C->varlist())
8931 Record.AddStmt(E);
8932 for (auto *D : C->all_decls())
8933 Record.AddDeclRef(D);
8934 for (auto N : C->all_num_lists())
8935 Record.push_back(N);
8936 for (auto N : C->all_lists_sizes())
8937 Record.push_back(N);
8938 for (auto &M : C->all_components()) {
8939 Record.AddStmt(M.getAssociatedExpression());
8940 Record.AddDeclRef(M.getAssociatedDeclaration());
8941 }
8942}
8943
8944void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
8945
8946void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
8947 OMPUnifiedSharedMemoryClause *) {}
8948
8949void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
8950
8951void
8952OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
8953}
8954
8955void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
8956 OMPAtomicDefaultMemOrderClause *C) {
8957 Record.push_back(C->getAtomicDefaultMemOrderKind());
8958 Record.AddSourceLocation(C->getLParenLoc());
8959 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
8960}
8961
8962void OMPClauseWriter::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
8963
8964void OMPClauseWriter::VisitOMPAtClause(OMPAtClause *C) {
8965 Record.push_back(C->getAtKind());
8966 Record.AddSourceLocation(C->getLParenLoc());
8967 Record.AddSourceLocation(C->getAtKindKwLoc());
8968}
8969
8970void OMPClauseWriter::VisitOMPSeverityClause(OMPSeverityClause *C) {
8971 Record.push_back(C->getSeverityKind());
8972 Record.AddSourceLocation(C->getLParenLoc());
8973 Record.AddSourceLocation(C->getSeverityKindKwLoc());
8974}
8975
8976void OMPClauseWriter::VisitOMPMessageClause(OMPMessageClause *C) {
8977 VisitOMPClauseWithPreInit(C);
8978 Record.AddStmt(C->getMessageString());
8979 Record.AddSourceLocation(C->getLParenLoc());
8980}
8981
8982void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
8983 Record.push_back(C->varlist_size());
8984 Record.AddSourceLocation(C->getLParenLoc());
8985 for (auto *VE : C->varlist())
8986 Record.AddStmt(VE);
8987 for (auto *E : C->private_refs())
8988 Record.AddStmt(E);
8989}
8990
8991void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
8992 Record.push_back(C->varlist_size());
8993 Record.AddSourceLocation(C->getLParenLoc());
8994 for (auto *VE : C->varlist())
8995 Record.AddStmt(VE);
8996}
8997
8998void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
8999 Record.push_back(C->varlist_size());
9000 Record.AddSourceLocation(C->getLParenLoc());
9001 for (auto *VE : C->varlist())
9002 Record.AddStmt(VE);
9003}
9004
9005void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) {
9006 Record.writeEnum(C->getKind());
9007 Record.writeEnum(C->getModifier());
9008 Record.AddSourceLocation(C->getLParenLoc());
9009 Record.AddSourceLocation(C->getKindKwLoc());
9010 Record.AddSourceLocation(C->getModifierKwLoc());
9011}
9012
9013void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
9014 Record.push_back(C->getNumberOfAllocators());
9015 Record.AddSourceLocation(C->getLParenLoc());
9016 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
9017 OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I);
9018 Record.AddStmt(Data.Allocator);
9019 Record.AddStmt(Data.AllocatorTraits);
9020 Record.AddSourceLocation(Data.LParenLoc);
9021 Record.AddSourceLocation(Data.RParenLoc);
9022 }
9023}
9024
9025void OMPClauseWriter::VisitOMPAffinityClause(OMPAffinityClause *C) {
9026 Record.push_back(C->varlist_size());
9027 Record.AddSourceLocation(C->getLParenLoc());
9028 Record.AddStmt(C->getModifier());
9029 Record.AddSourceLocation(C->getColonLoc());
9030 for (Expr *E : C->varlist())
9031 Record.AddStmt(E);
9032}
9033
9034void OMPClauseWriter::VisitOMPBindClause(OMPBindClause *C) {
9035 Record.writeEnum(C->getBindKind());
9036 Record.AddSourceLocation(C->getLParenLoc());
9037 Record.AddSourceLocation(C->getBindKindLoc());
9038}
9039
9040void OMPClauseWriter::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
9041 VisitOMPClauseWithPreInit(C);
9042 Record.AddStmt(C->getSize());
9043 Record.AddSourceLocation(C->getLParenLoc());
9044}
9045
9046void OMPClauseWriter::VisitOMPDynGroupprivateClause(
9047 OMPDynGroupprivateClause *C) {
9048 VisitOMPClauseWithPreInit(C);
9049 Record.push_back(C->getDynGroupprivateModifier());
9050 Record.push_back(C->getDynGroupprivateFallbackModifier());
9051 Record.AddStmt(C->getSize());
9052 Record.AddSourceLocation(C->getLParenLoc());
9053 Record.AddSourceLocation(C->getDynGroupprivateModifierLoc());
9054 Record.AddSourceLocation(C->getDynGroupprivateFallbackModifierLoc());
9055}
9056
9057void OMPClauseWriter::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
9058 Record.push_back(C->varlist_size());
9059 Record.push_back(C->getNumLoops());
9060 Record.AddSourceLocation(C->getLParenLoc());
9061 Record.push_back(C->getDependenceType());
9062 Record.AddSourceLocation(C->getDependenceLoc());
9063 Record.AddSourceLocation(C->getColonLoc());
9064 for (auto *VE : C->varlist())
9065 Record.AddStmt(VE);
9066 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
9067 Record.AddStmt(C->getLoopData(I));
9068}
9069
9070void OMPClauseWriter::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
9071 Record.AddAttributes(C->getAttrs());
9072 Record.AddSourceLocation(C->getBeginLoc());
9073 Record.AddSourceLocation(C->getLParenLoc());
9074 Record.AddSourceLocation(C->getEndLoc());
9075}
9076
9077void OMPClauseWriter::VisitOMPXBareClause(OMPXBareClause *C) {}
9078
9080 writeUInt32(TI->Sets.size());
9081 for (const auto &Set : TI->Sets) {
9082 writeEnum(Set.Kind);
9083 writeUInt32(Set.Selectors.size());
9084 for (const auto &Selector : Set.Selectors) {
9085 writeEnum(Selector.Kind);
9086 writeBool(Selector.ScoreOrCondition);
9087 if (Selector.ScoreOrCondition)
9088 writeExprRef(Selector.ScoreOrCondition);
9089 writeUInt32(Selector.Properties.size());
9090 for (const auto &Property : Selector.Properties)
9091 writeEnum(Property.Kind);
9092 }
9093 }
9094}
9095
9097 if (!Data)
9098 return;
9099 writeUInt32(Data->getNumClauses());
9100 writeUInt32(Data->getNumChildren());
9101 writeBool(Data->hasAssociatedStmt());
9102 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
9103 writeOMPClause(Data->getClauses()[I]);
9104 if (Data->hasAssociatedStmt())
9105 AddStmt(Data->getAssociatedStmt());
9106 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
9107 AddStmt(Data->getChildren()[I]);
9108}
9109
9111 writeUInt32(C->getVarList().size());
9112 for (Expr *E : C->getVarList())
9113 AddStmt(E);
9114}
9115
9117 writeUInt32(Exprs.size());
9118 for (Expr *E : Exprs)
9119 AddStmt(E);
9120}
9121
9123 writeEnum(C->getClauseKind());
9124 writeSourceLocation(C->getBeginLoc());
9125 writeSourceLocation(C->getEndLoc());
9126
9127 switch (C->getClauseKind()) {
9129 const auto *DC = cast<OpenACCDefaultClause>(C);
9130 writeSourceLocation(DC->getLParenLoc());
9131 writeEnum(DC->getDefaultClauseKind());
9132 return;
9133 }
9134 case OpenACCClauseKind::If: {
9135 const auto *IC = cast<OpenACCIfClause>(C);
9136 writeSourceLocation(IC->getLParenLoc());
9137 AddStmt(const_cast<Expr*>(IC->getConditionExpr()));
9138 return;
9139 }
9141 const auto *SC = cast<OpenACCSelfClause>(C);
9142 writeSourceLocation(SC->getLParenLoc());
9143 writeBool(SC->isConditionExprClause());
9144 if (SC->isConditionExprClause()) {
9145 writeBool(SC->hasConditionExpr());
9146 if (SC->hasConditionExpr())
9147 AddStmt(const_cast<Expr *>(SC->getConditionExpr()));
9148 } else {
9149 writeUInt32(SC->getVarList().size());
9150 for (Expr *E : SC->getVarList())
9151 AddStmt(E);
9152 }
9153 return;
9154 }
9156 const auto *NGC = cast<OpenACCNumGangsClause>(C);
9157 writeSourceLocation(NGC->getLParenLoc());
9158 writeUInt32(NGC->getIntExprs().size());
9159 for (Expr *E : NGC->getIntExprs())
9160 AddStmt(E);
9161 return;
9162 }
9164 const auto *DNC = cast<OpenACCDeviceNumClause>(C);
9165 writeSourceLocation(DNC->getLParenLoc());
9166 AddStmt(const_cast<Expr*>(DNC->getIntExpr()));
9167 return;
9168 }
9170 const auto *DAC = cast<OpenACCDefaultAsyncClause>(C);
9171 writeSourceLocation(DAC->getLParenLoc());
9172 AddStmt(const_cast<Expr *>(DAC->getIntExpr()));
9173 return;
9174 }
9176 const auto *NWC = cast<OpenACCNumWorkersClause>(C);
9177 writeSourceLocation(NWC->getLParenLoc());
9178 AddStmt(const_cast<Expr*>(NWC->getIntExpr()));
9179 return;
9180 }
9182 const auto *NWC = cast<OpenACCVectorLengthClause>(C);
9183 writeSourceLocation(NWC->getLParenLoc());
9184 AddStmt(const_cast<Expr*>(NWC->getIntExpr()));
9185 return;
9186 }
9188 const auto *PC = cast<OpenACCPrivateClause>(C);
9189 writeSourceLocation(PC->getLParenLoc());
9191
9192 for (const OpenACCPrivateRecipe &R : PC->getInitRecipes()) {
9193 static_assert(sizeof(R) == 1 * sizeof(int *));
9194 AddDeclRef(R.AllocaDecl);
9195 }
9196 return;
9197 }
9199 const auto *HC = cast<OpenACCHostClause>(C);
9200 writeSourceLocation(HC->getLParenLoc());
9202 return;
9203 }
9205 const auto *DC = cast<OpenACCDeviceClause>(C);
9206 writeSourceLocation(DC->getLParenLoc());
9208 return;
9209 }
9211 const auto *FPC = cast<OpenACCFirstPrivateClause>(C);
9212 writeSourceLocation(FPC->getLParenLoc());
9214
9215 for (const OpenACCFirstPrivateRecipe &R : FPC->getInitRecipes()) {
9216 static_assert(sizeof(R) == 2 * sizeof(int *));
9217 AddDeclRef(R.AllocaDecl);
9218 AddDeclRef(R.InitFromTemporary);
9219 }
9220 return;
9221 }
9223 const auto *AC = cast<OpenACCAttachClause>(C);
9224 writeSourceLocation(AC->getLParenLoc());
9226 return;
9227 }
9229 const auto *DC = cast<OpenACCDetachClause>(C);
9230 writeSourceLocation(DC->getLParenLoc());
9232 return;
9233 }
9235 const auto *DC = cast<OpenACCDeleteClause>(C);
9236 writeSourceLocation(DC->getLParenLoc());
9238 return;
9239 }
9241 const auto *UDC = cast<OpenACCUseDeviceClause>(C);
9242 writeSourceLocation(UDC->getLParenLoc());
9244 return;
9245 }
9247 const auto *DPC = cast<OpenACCDevicePtrClause>(C);
9248 writeSourceLocation(DPC->getLParenLoc());
9250 return;
9251 }
9253 const auto *NCC = cast<OpenACCNoCreateClause>(C);
9254 writeSourceLocation(NCC->getLParenLoc());
9256 return;
9257 }
9259 const auto *PC = cast<OpenACCPresentClause>(C);
9260 writeSourceLocation(PC->getLParenLoc());
9262 return;
9263 }
9267 const auto *CC = cast<OpenACCCopyClause>(C);
9268 writeSourceLocation(CC->getLParenLoc());
9269 writeEnum(CC->getModifierList());
9271 return;
9272 }
9276 const auto *CIC = cast<OpenACCCopyInClause>(C);
9277 writeSourceLocation(CIC->getLParenLoc());
9278 writeEnum(CIC->getModifierList());
9280 return;
9281 }
9285 const auto *COC = cast<OpenACCCopyOutClause>(C);
9286 writeSourceLocation(COC->getLParenLoc());
9287 writeEnum(COC->getModifierList());
9289 return;
9290 }
9294 const auto *CC = cast<OpenACCCreateClause>(C);
9295 writeSourceLocation(CC->getLParenLoc());
9296 writeEnum(CC->getModifierList());
9298 return;
9299 }
9301 const auto *AC = cast<OpenACCAsyncClause>(C);
9302 writeSourceLocation(AC->getLParenLoc());
9303 writeBool(AC->hasIntExpr());
9304 if (AC->hasIntExpr())
9305 AddStmt(const_cast<Expr*>(AC->getIntExpr()));
9306 return;
9307 }
9309 const auto *WC = cast<OpenACCWaitClause>(C);
9310 writeSourceLocation(WC->getLParenLoc());
9311 writeBool(WC->getDevNumExpr());
9312 if (Expr *DNE = WC->getDevNumExpr())
9313 AddStmt(DNE);
9314 writeSourceLocation(WC->getQueuesLoc());
9315
9316 writeOpenACCIntExprList(WC->getQueueIdExprs());
9317 return;
9318 }
9321 const auto *DTC = cast<OpenACCDeviceTypeClause>(C);
9322 writeSourceLocation(DTC->getLParenLoc());
9323 writeUInt32(DTC->getArchitectures().size());
9324 for (const DeviceTypeArgument &Arg : DTC->getArchitectures()) {
9325 writeBool(Arg.getIdentifierInfo());
9326 if (Arg.getIdentifierInfo())
9327 AddIdentifierRef(Arg.getIdentifierInfo());
9328 writeSourceLocation(Arg.getLoc());
9329 }
9330 return;
9331 }
9333 const auto *RC = cast<OpenACCReductionClause>(C);
9334 writeSourceLocation(RC->getLParenLoc());
9335 writeEnum(RC->getReductionOp());
9337
9338 for (const OpenACCReductionRecipe &R : RC->getRecipes()) {
9339 AddDeclRef(R.AllocaDecl);
9340
9341 static_assert(sizeof(OpenACCReductionRecipe::CombinerRecipe) ==
9342 3 * sizeof(int *));
9343 writeUInt32(R.CombinerRecipes.size());
9344
9345 for (auto &CombinerRecipe : R.CombinerRecipes) {
9346 AddDeclRef(CombinerRecipe.LHS);
9347 AddDeclRef(CombinerRecipe.RHS);
9348 AddStmt(CombinerRecipe.Op);
9349 }
9350 }
9351 return;
9352 }
9359 // Nothing to do here, there is no additional information beyond the
9360 // begin/end loc and clause kind.
9361 return;
9363 const auto *CC = cast<OpenACCCollapseClause>(C);
9364 writeSourceLocation(CC->getLParenLoc());
9365 writeBool(CC->hasForce());
9366 AddStmt(const_cast<Expr *>(CC->getLoopCount()));
9367 return;
9368 }
9370 const auto *TC = cast<OpenACCTileClause>(C);
9371 writeSourceLocation(TC->getLParenLoc());
9372 writeUInt32(TC->getSizeExprs().size());
9373 for (Expr *E : TC->getSizeExprs())
9374 AddStmt(E);
9375 return;
9376 }
9378 const auto *GC = cast<OpenACCGangClause>(C);
9379 writeSourceLocation(GC->getLParenLoc());
9380 writeUInt32(GC->getNumExprs());
9381 for (unsigned I = 0; I < GC->getNumExprs(); ++I) {
9382 writeEnum(GC->getExpr(I).first);
9383 AddStmt(const_cast<Expr *>(GC->getExpr(I).second));
9384 }
9385 return;
9386 }
9388 const auto *WC = cast<OpenACCWorkerClause>(C);
9389 writeSourceLocation(WC->getLParenLoc());
9390 writeBool(WC->hasIntExpr());
9391 if (WC->hasIntExpr())
9392 AddStmt(const_cast<Expr *>(WC->getIntExpr()));
9393 return;
9394 }
9396 const auto *VC = cast<OpenACCVectorClause>(C);
9397 writeSourceLocation(VC->getLParenLoc());
9398 writeBool(VC->hasIntExpr());
9399 if (VC->hasIntExpr())
9400 AddStmt(const_cast<Expr *>(VC->getIntExpr()));
9401 return;
9402 }
9404 const auto *LC = cast<OpenACCLinkClause>(C);
9405 writeSourceLocation(LC->getLParenLoc());
9407 return;
9408 }
9410 const auto *DRC = cast<OpenACCDeviceResidentClause>(C);
9411 writeSourceLocation(DRC->getLParenLoc());
9413 return;
9414 }
9415
9417 const auto *BC = cast<OpenACCBindClause>(C);
9418 writeSourceLocation(BC->getLParenLoc());
9419 writeBool(BC->isStringArgument());
9420 if (BC->isStringArgument())
9421 AddStmt(const_cast<StringLiteral *>(BC->getStringArgument()));
9422 else
9423 AddIdentifierRef(BC->getIdentifierArgument());
9424
9425 return;
9426 }
9429 llvm_unreachable("Clause serialization not yet implemented");
9430 }
9431 llvm_unreachable("Invalid Clause Kind");
9432}
9433
9436 for (const OpenACCClause *Clause : Clauses)
9437 writeOpenACCClause(Clause);
9438}
9440 const OpenACCRoutineDeclAttr *A) {
9441 // We have to write the size so that the reader can do a resize. Unlike the
9442 // Decl version of this, we can't count on trailing storage to get this right.
9443 writeUInt32(A->Clauses.size());
9444 writeOpenACCClauseList(A->Clauses);
9445}
#define RECORD(CLASS, BASE)
Defines the clang::ASTContext interface.
#define V(N, I)
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
static NamedDecl * getDeclForLocalLookup(const LangOptions &LangOpts, NamedDecl *D)
Determine the declaration that should be put into the name lookup table to represent the given declar...
static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a buffer.
static bool isLookupResultNotInteresting(ASTWriter &Writer, StoredDeclsList &Result)
Returns true if all of the lookup result are either external, not emitted or predefined.
static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec)
static bool IsInternalDeclFromFileContext(const Decl *D)
static TypeID MakeTypeID(ASTContext &Context, QualType T, IdxForTypeTy IdxForType)
static void AddLazyVectorEmiitedDecls(ASTWriter &Writer, Vector &Vec, ASTWriter::RecordData &Record)
static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a macro expansion.
static StringRef bytes(const std::vector< T, Allocator > &v)
static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream, bool Compressed)
Create an abbreviation for the SLocEntry that refers to a buffer's blob.
static void BackpatchSignatureAt(llvm::BitstreamWriter &Stream, const ASTFileSignature &S, uint64_t BitNo)
static bool isLocalIdentifierID(IdentifierID ID)
If the.
static bool isImportedDeclContext(ASTReader *Chain, const Decl *D)
static TypeCode getTypeCodeForTypeClass(Type::TypeClass id)
static void AddStmtsExprs(llvm::BitstreamWriter &Stream, ASTWriter::RecordDataImpl &Record)
static bool adjustFilenameForRelocatableAST(SmallVectorImpl< char > &Filename, StringRef BaseDir)
Adjusts the given filename to only write out the portion of the filename that is not part of the syst...
static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob, unsigned SLocBufferBlobCompressedAbbrv, unsigned SLocBufferBlobAbbrv)
static uint64_t EmitCXXBaseSpecifiers(ASTContext &Context, ASTWriter &W, ArrayRef< CXXBaseSpecifier > Bases)
static std::pair< unsigned, unsigned > emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out)
Emit key length and data length as ULEB-encoded data, and return them as a pair.
static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule, const Preprocessor &PP)
static uint64_t EmitCXXCtorInitializers(ASTContext &Context, ASTWriter &W, ArrayRef< CXXCtorInitializer * > CtorInits)
static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a file.
Defines the Diagnostic-related interfaces.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines interfaces for clang::FileEntry and clang::FileEntryRef.
Defines the clang::FileManager interface and associated types.
Defines the clang::FileSystemOptions interface.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
Token Tok
The Token.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the LambdaCapture class.
Defines several types used to describe C++ lambda expressions that are shared between the parser and ...
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::Target Target
Definition MachO.h:51
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.
Defines the clang::OpenCLOptions class.
This file defines OpenMP AST classes for clauses.
Defines the clang::Preprocessor interface.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to RISC-V.
static void EmitBlockID(unsigned ID, const char *Name, llvm::BitstreamWriter &Stream, RecordDataImpl &Record)
Emits a block ID in the BLOCKINFO block.
static void EmitRecordID(unsigned ID, const char *Name, llvm::BitstreamWriter &Stream, RecordDataImpl &Record)
Emits a record ID in the BLOCKINFO block.
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.
Defines the clang::TargetOptions class.
#define IMPORT(DERIVED, BASE)
Definition Template.h:637
#define BLOCK(DERIVED, BASE)
Definition Template.h:653
Defines the clang::TypeLoc interface and its subclasses.
TypePropertyCache< Private > Cache
Definition Type.cpp:5099
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)
Contains data for OpenMP directives: clauses, children expressions/statements (helpers for codegen) a...
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
TranslationUnitDecl * getTranslationUnitDecl() const
QualType getRawCFConstantStringType() const
Get the structure type used to representation CFStrings, or NULL if it hasn't yet been built.
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
FunctionDecl * getcudaGetParameterBufferDecl()
QualType getFILEType() const
Retrieve the C FILE type.
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
IdentifierTable & Idents
Definition ASTContext.h:855
const LangOptions & getLangOpts() const
RawCommentList Comments
All comments in this translation unit.
TagDecl * MSTypeInfoTagDecl
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
TagDecl * MSGuidTagDecl
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
FunctionDecl * getcudaConfigureCallDecl()
import_range local_imports() const
FunctionDecl * getcudaLaunchDeviceDecl()
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:427
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
const serialization::reader::ModuleLocalLookupTable * getModuleLocalLookupTables(DeclContext *Primary) const
unsigned getTotalNumSubmodules() const
Returns the number of submodules known.
Definition ASTReader.h:2074
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition ASTReader.h:2079
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Decl * getKeyDeclaration(Decl *D)
Returns the first key declaration for the given declaration.
Definition ASTReader.h:1475
serialization::reader::LazySpecializationInfoLookupTable * getLoadedSpecializationsLookupTables(const Decl *D, bool IsPartial)
Get the loaded specializations lookup tables for D, if any.
const serialization::reader::DeclContextLookupTable * getTULocalLookupTables(DeclContext *Primary) const
An object for streaming information to a record.
void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo)
void AddCXXBaseSpecifiers(ArrayRef< CXXBaseSpecifier > Bases)
Emit a set of C++ base specifiers.
void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs)
Emit a template argument list.
uint64_t Emit(unsigned Code, unsigned Abbrev=0)
Emit the record to the stream, followed by its substatements, and return its offset.
void AddCXXTemporary(const CXXTemporary *Temp)
Emit a CXXTemporary.
void writeOMPTraitInfo(const OMPTraitInfo *TI)
Write an OMPTraitInfo object.
void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base)
Emit a C++ base specifier.
void writeOMPClause(OMPClause *C)
void writeBool(bool Value)
void AddAPValue(const APValue &Value)
Emit an APvalue.
void AddUnresolvedSet(const ASTUnresolvedSet &Set)
Emit a UnresolvedSet structure.
void AddIdentifierRef(const IdentifierInfo *II)
Emit a reference to an identifier.
void AddStmt(Stmt *S)
Add the given statement or expression to the queue of statements to emit.
void AddDeclarationName(DeclarationName Name)
Emit a declaration name.
void AddTemplateArgumentLocInfo(const TemplateArgumentLoc &Arg)
Emits a template argument location info.
void AddTypeLoc(TypeLoc TL)
Emits source location information for a type. Does not emit the type.
void AddSelectorRef(Selector S)
Emit a Selector (which is a smart pointer reference).
void writeSourceLocation(SourceLocation Loc)
void AddOffset(uint64_t BitOffset)
Add a bit offset into the record.
void AddTypeRef(QualType T)
Emit a reference to a type.
void writeOpenACCClauseList(ArrayRef< const OpenACCClause * > Clauses)
Writes out a list of OpenACC clauses.
void push_back(uint64_t N)
Minimal vector-like interface.
void AddCXXCtorInitializers(ArrayRef< CXXCtorInitializer * > CtorInits)
Emit a CXXCtorInitializer array.
void AddTemplateParameterList(const TemplateParameterList *TemplateParams)
Emit a template parameter list.
void AddTemplateArgument(const TemplateArgument &Arg)
Emit a template argument.
void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, DeclarationName Name)
void writeOpenACCIntExprList(ArrayRef< Expr * > Exprs)
void AddTemplateName(TemplateName Name)
Emit a template name.
void AddAPFloat(const llvm::APFloat &Value)
Emit a floating-point value.
void AddTypeSourceInfo(TypeSourceInfo *TInfo)
Emits a reference to a declarator info.
void AddQualifierInfo(const QualifierInfo &Info)
void writeUInt32(uint32_t Value)
void AddDeclRef(const Decl *D)
Emit a reference to a declaration.
void writeOMPChildren(OMPChildren *Data)
Writes data related to the OpenMP directives.
void AddConceptReference(const ConceptReference *CR)
void AddSourceRange(SourceRange Range)
Emit a source range.
void AddAPInt(const llvm::APInt &Value)
Emit an integral value.
void AddSourceLocation(SourceLocation Loc)
Emit a source location.
void writeOpenACCVarList(const OpenACCClauseWithVarList *C)
void AddAttributes(ArrayRef< const Attr * > Attrs)
Emit a list of attributes.
void AddASTTemplateArgumentListInfo(const ASTTemplateArgumentListInfo *ASTTemplArgList)
Emits an AST template argument list info.
void AddCXXDefinitionData(const CXXRecordDecl *D)
void AddVarDeclInit(const VarDecl *VD)
Emit information about the initializer of a VarDecl.
void writeStmtRef(const Stmt *S)
void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg)
Emits a template argument location.
void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS)
Emit a nested name specifier with source-location information.
void AddOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A)
void writeOpenACCClause(const OpenACCClause *C)
Writes out a single OpenACC Clause.
void AddAttr(const Attr *A)
An UnresolvedSet-like class which uses the ASTContext's allocator.
UnresolvedSetIterator const_iterator
Writes an AST file containing the contents of a translation unit.
Definition ASTWriter.h:98
static SourceLocationEncoding::Chain EmitSourceLocationOffset(SourceLocation::UIntTy Offset, SourceLocation::UIntTy InitialDelta, RecordDataImpl &Record)
Emit Offset as the next record field and return a chain anchored at Offset + InitialDelta,...
SourceLocation::UIntTy getEntryOffset(const SrcMgr::SLocEntry &SLoc) const
The starting offset of SLoc's entry within this module, with the dummy entry skipped.
void AddEmittedDeclRef(const Decl *D, RecordDataImpl &Record)
friend class ASTRecordWriter
Definition ASTWriter.h:101
bool isWritingStdCXXNamedModules() const
Definition ASTWriter.h:944
ArrayRef< uint64_t > RecordDataRef
Definition ASTWriter.h:105
void EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record, StringRef Path)
Emit the current record with the given path as a blob.
void AddFileID(FileID FID, RecordDataImpl &Record)
Emit a FileID.
bool isDeclPredefined(const Decl *D) const
Definition ASTWriter.h:956
bool IsLocalDecl(const Decl *D) const
Is this a local declaration (that is, one that will be written to our AST file)?
Definition ASTWriter.h:807
bool hasChain() const
Definition ASTWriter.h:939
void AddPath(StringRef Path, RecordDataImpl &Record)
Add a path to the given record.
SmallVectorImpl< uint64_t > RecordDataImpl
Definition ASTWriter.h:104
void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record)
Add a version tuple to the given record.
bool isGeneratingReducedBMI() const
Definition ASTWriter.h:952
uint32_t getMacroDirectivesOffset(const IdentifierInfo *Name)
void AddAlignPackInfo(const Sema::AlignPackInfo &Info, RecordDataImpl &Record)
Emit a AlignPackInfo.
void AddPathBlob(StringRef Str, RecordDataImpl &Record, SmallVectorImpl< char > &Blob)
llvm::MapVector< serialization::ModuleFile *, const Decl * > CollectFirstDeclFromEachModule(const Decl *D, bool IncludeLocal)
Collect the first declaration from each module file that provides a declaration of D.
void AddTypeRef(ASTContext &Context, QualType T, RecordDataImpl &Record)
Emit a reference to a type.
bool wasDeclEmitted(const Decl *D) const
Whether or not the declaration got emitted.
void AddString(StringRef Str, RecordDataImpl &Record)
Add a string to the given record.
~ASTWriter() override
bool isWritingModule() const
Definition ASTWriter.h:942
LocalDeclID GetDeclRef(const Decl *D)
Force a declaration to be emitted and get its local ID to the module file been writing.
void AddSourceRange(SourceRange Range, RecordDataImpl &Record)
Emit a source range.
LocalDeclID getDeclID(const Decl *D)
Determine the local declaration ID of an already-emitted declaration.
void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record)
Emit a source location.
ASTFileSignature WriteAST(llvm::PointerUnion< Sema *, Preprocessor * > Subject, StringRef OutputFile, Module *WritingModule, StringRef isysroot)
Write a precompiled header or a module with the AST produced by the Sema object, or a dependency scan...
void addTouchedModuleFile(serialization::ModuleFile *)
void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record)
Emit a reference to an identifier.
serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name)
Get the unique number used to refer to the given macro.
SourceLocationEncoding::RawLocEncoding getRawSourceLocationEncoding(SourceLocation Loc)
Return the raw encodings for source locations.
ASTReader * getChain() const
Definition ASTWriter.h:940
SourceLocationEncoding::Chain EmitEntryOffset(const SrcMgr::SLocEntry &SLoc, RecordDataImpl &Record)
Emit SLoc's entry offset as the record's first field and return a chain anchored at that entry,...
bool getDoneWritingDeclsAndTypes() const
Definition ASTWriter.h:954
serialization::IdentifierID getIdentifierRef(const IdentifierInfo *II)
Get the unique number used to refer to the given identifier.
ASTWriter(llvm::BitstreamWriter &Stream, SmallVectorImpl< char > &Buffer, ModuleCache &ModCache, const CodeGenOptions &CodeGenOpts, ArrayRef< std::shared_ptr< ModuleFileExtension > > Extensions, bool IncludeTimestamps=true, bool BuildingImplicitModule=false, bool GeneratingReducedBMI=false)
Create a new precompiled header writer that outputs to the given bitstream.
time_t getTimestampForOutput(time_t ModTime) const
Get a timestamp for output into the AST file.
void handleVTable(CXXRecordDecl *RD)
unsigned getLocalOrImportedSubmoduleID(const Module *Mod)
Retrieve or create a submodule ID for this module, or return 0 if the submodule is neither local (a s...
void AddToken(const Token &Tok, RecordDataImpl &Record)
Emit a token.
void AddLookupOffsets(const LookupBlockOffsets &Offsets, RecordDataImpl &Record)
serialization::SelectorID getSelectorRef(Selector Sel)
Get the unique number used to refer to the given selector.
SmallVector< uint64_t, 64 > RecordData
Definition ASTWriter.h:103
serialization::TypeID GetOrCreateTypeID(ASTContext &Context, QualType T)
Force a type to be emitted and get its ID.
unsigned getAnonymousDeclarationNumber(const NamedDecl *D)
void AddMacroRef(MacroInfo *MI, const IdentifierInfo *Name, RecordDataImpl &Record)
Emit a reference to a macro.
const LangOptions & getLangOpts() const
void SetSelectorOffset(Selector Sel, uint32_t Offset)
Note that the selector Sel occurs at the given offset within the method pool/selector table.
bool PreparePathForOutput(SmallVectorImpl< char > &Path)
Convert a path from this build process into one that is appropriate for emission in the module file.
void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset)
Note that the identifier II occurs at the given offset within the identifier table.
void AddDeclRef(const Decl *D, RecordDataImpl &Record)
Emit a reference to a declaration.
void AddStringBlob(StringRef Str, RecordDataImpl &Record, SmallVectorImpl< char > &Blob)
Wrapper for source info for arrays.
Definition TypeLoc.h:1808
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1810
Expr * getSizeExpr() const
Definition TypeLoc.h:1830
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1818
SourceLocation getRParenLoc() const
Definition TypeLoc.h:2737
SourceLocation getKWLoc() const
Definition TypeLoc.h:2721
SourceLocation getLParenLoc() const
Definition TypeLoc.h:2729
Attr - This represents one attribute.
Definition Attr.h:47
attr::Kind getKind() const
Definition Attr.h:93
SourceLocation getScopeLoc() const
const IdentifierInfo * getScopeName() const
const IdentifierInfo * getAttrName() const
const Attr * getAttr() const
The type attribute.
Definition TypeLoc.h:1031
SourceLocation getRParenLoc() const
Definition TypeLoc.h:2450
bool isDecltypeAuto() const
Definition TypeLoc.h:2449
bool isConstrained() const
Definition TypeLoc.h:2453
ConceptReference * getConceptReference() const
Definition TypeLoc.h:2459
A simple helper class to pack several bits in order into (a) 32 bit integer(s).
Definition ASTWriter.h:1108
void addBit(bool Value)
Definition ASTWriter.h:1128
void addBits(uint32_t Value, uint32_t BitsWidth)
Definition ASTWriter.h:1129
SourceLocation getCaretLoc() const
Definition TypeLoc.h:1559
SourceLocation getBuiltinLoc() const
Definition TypeLoc.h:579
TypeSpecifierType getWrittenTypeSpec() const
Definition TypeLoc.cpp:321
TypeSpecifierWidth getWrittenWidthSpec() const
Definition TypeLoc.h:641
bool needsExtraLocalData() const
Definition TypeLoc.h:606
bool hasModeAttr() const
Definition TypeLoc.h:668
TypeSpecifierSign getWrittenSignSpec() const
Definition TypeLoc.h:625
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
unsigned getDeviceLambdaManglingNumber() const
Retrieve the device side mangling number.
Definition DeclCXX.cpp:1857
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2062
unsigned getODRHash() const
Definition DeclCXX.cpp:496
Represents a C++ temporary.
Definition ExprCXX.h:1464
const CXXDestructorDecl * getDestructor() const
Definition ExprCXX.h:1475
Declaration of a class template.
Represents a class template specialization, which refers to a class template with a given set of temp...
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
A reference to a concept and its template args, as it appears in the code.
Definition ASTConcept.h:127
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition ASTConcept.h:167
NamedDecl * getFoundDecl() const
Definition ASTConcept.h:194
const DeclarationNameInfo & getConceptNameInfo() const
Definition ASTConcept.h:171
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:200
TemplateName getNamedConcept() const
Definition ASTConcept.h:198
SourceLocation getTemplateKWLoc() const
Definition ASTConcept.h:177
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
bool isFileContext() const
Definition DeclBase.h:2201
DeclContextLookupResult lookup_result
Definition DeclBase.h:2611
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isLookupContext() const
Test whether the context supports looking up names.
Definition DeclBase.h:2196
bool isTranslationUnit() const
Definition DeclBase.h:2206
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
StoredDeclsMap * buildLookup()
Ensure the lookup structure is fully-built and return it.
lookup_result noload_lookup(DeclarationName Name)
Find the declarations with the given name that are visible within this context; don't attempt to retr...
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition DeclBase.h:2415
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
bool decls_empty() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2407
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2165
StoredDeclsMap * getLookupPtr() const
Retrieve the internal representation of the lookup structure.
Definition DeclBase.h:2705
DeclID getRawValue() const
Definition DeclID.h:118
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:1079
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1094
Module * getTopLevelOwningNamedModule() const
Get the top level owning named module that owns this declaration if any.
Definition DeclBase.cpp:152
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1244
T * getAttr() const
Definition DeclBase.h:582
bool hasAttrs() const
Definition DeclBase.h:527
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
bool isInNamedModule() const
Whether this declaration comes from a named module.
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:872
@ FOK_None
Not a friend object.
Definition DeclBase.h:1235
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:1002
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:855
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition DeclBase.h:1088
bool isFromExplicitGlobalModule() const
Whether this declaration comes from explicit global module.
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:806
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
SourceLocation getLocation() const
Definition DeclBase.h:448
DeclContext * getDeclContext()
Definition DeclBase.h:457
AttrVec & getAttrs()
Definition DeclBase.h:533
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
Kind getKind() const
Definition DeclBase.h:451
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition DeclBase.cpp:110
DeclarationNameLoc - Additional source/type location info for a declaration name.
SourceLocation getCXXLiteralOperatorNameLoc() const
Return the location of the literal operator name (without the operator keyword).
TypeSourceInfo * getNamedTypeInfo() const
Returns the source type info.
SourceRange getCXXOperatorNameRange() const
Return the range of the operator name (without the operator keyword).
The name of a declaration.
NameKind getNameKind() const
Determine what kind of name this is.
SourceLocation getDecltypeLoc() const
Definition TypeLoc.h:2339
SourceLocation getRParenLoc() const
Definition TypeLoc.h:2342
SourceLocation getElaboratedKeywordLoc() const
Definition TypeLoc.h:2561
SourceLocation getTemplateNameLoc() const
Definition TypeLoc.h:2569
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:2573
Expr * getAttrExprOperand() const
The attribute's expression operand, if it has one.
Definition TypeLoc.h:2015
SourceRange getAttrOperandParensRange() const
The location of the parentheses around the operand, if there is an operand.
Definition TypeLoc.h:2026
SourceLocation getAttrNameLoc() const
The location of the attribute name, i.e.
Definition TypeLoc.h:2005
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:2637
SourceLocation getNameLoc() const
Definition TypeLoc.h:2649
SourceLocation getElaboratedKeywordLoc() const
Definition TypeLoc.h:2629
SourceLocation getNameLoc() const
Definition TypeLoc.h:2138
SourceLocation getAttrNameLoc() const
Definition TypeLoc.h:2142
SourceLocation getNameLoc() const
Definition TypeLoc.h:2105
SourceLocation getAttrNameLoc() const
Definition TypeLoc.h:2108
std::vector< std::string > Remarks
The list of -R... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > Warnings
The list of -W... options used to alter the diagnostic mappings, with the prefixes removed.
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:645
bool hasUncompilableErrorOccurred() const
Errors that actually prevent compilation, not those that are upgraded from a warning by -Werror.
Definition Diagnostic.h:927
StringRef getName() const
SourceLocation getElaboratedKeywordLoc() const
Definition TypeLoc.h:752
SourceLocation getNameLoc() const
Definition TypeLoc.h:761
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:756
This represents one expression.
Definition Expr.h:114
storage_type getAsOpaqueInt() const
storage_type getAsOpaqueInt() const
Represents a member of a struct/union/class.
Definition Decl.h:3341
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
int getOpaqueValue() const
Returns the raw integer representation of this FileID.
void trackVFSUsage(bool Active)
Enable or disable tracking of VFS usage.
llvm::vfs::FileSystem & getVirtualFileSystem() const
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
FileSystemOptions & getFileSystemOpts()
Returns the current file system options.
bool makeAbsolutePath(SmallVectorImpl< char > &Path, bool Canonicalize=false) const
Makes Path absolute taking into account FileSystemOptions and the working directory option,...
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true, bool IsText=true)
Get a FileEntryRef if it exists, without doing anything on error.
OptionalDirectoryEntryRef getOptionalDirectoryRef(StringRef DirName, bool CacheFailure=true)
Get a DirectoryEntryRef if it exists, without doing anything on error.
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:2082
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2482
Declaration of a template function.
Wrapper for source info for functions.
Definition TypeLoc.h:1675
unsigned getNumParams() const
Definition TypeLoc.h:1747
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1753
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1699
SourceRange getExceptionSpecRange() const
Definition TypeLoc.h:1727
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1691
SourceLocation getLParenLoc() const
Definition TypeLoc.h:1707
SourceLocation getRParenLoc() const
Definition TypeLoc.h:1715
unsigned ModulesPruneNonAffectingModuleMaps
Whether to prune non-affecting module map files from PCM files.
unsigned ImplicitModuleMaps
Implicit module maps.
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 ModuleUserBuildPath
The directory used for a user build.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
unsigned ModuleFileHomeIsCwd
Set the base path of a built module file to be the current working directory.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
unsigned PCHBaseDirIsCwd
Serialize precompiled header input paths relative to the current working directory.
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
std::vector< bool > collectVFSUsageAndClear() const
Collect which HeaderSearchOptions::VFSOverlayFiles have been meaningfully used so far and mark their ...
StringRef getNormalizedModuleCachePath() const
Retrieve the normalized module cache path.
std::vector< bool > computeUserEntryUsage() const
Determine which HeaderSearchOptions::UserEntries have been successfully used so far and mark their in...
ArrayRef< ModuleMap::KnownHeader > findResolvedModulesForHeader(FileEntryRef File) const
Like findAllModulesForHeader, but do not attempt to infer module ownership from umbrella headers if w...
const HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
void forEachExistingLocalFileInfo(llvm::function_ref< void(FileEntryRef, const HeaderFileInfo &)> Fn) const
Iterate HeaderFileInfo structures and their corresponding FileEntryRef, if they have ever been filled...
ModuleMap & getModuleMap()
Retrieve the module map.
StringRef getContextHash() const
Retrieve the context hash.
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool hasChangedSinceDeserialization() const
Determine whether this identifier has changed since it was loaded from an AST file.
bool isCPlusPlusOperatorKeyword() const
bool hasFETokenInfoChangedSinceDeserialization() const
Determine whether the frontend token information for this identifier has changed since it was loaded ...
bool hasMacroDefinition() const
Return true if this identifier is #defined to some other value.
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.
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
tok::NotableIdentifierKind getNotableIdentifierID() const
unsigned getObjCOrBuiltinID() const
tok::ObjCKeywordKind getObjCKeywordID() const
Return the Objective-C keyword ID for the this identifier.
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.
iterator begin(DeclarationName Name)
Returns an iterator over decls with the name 'Name'.
iterator end()
Returns the end iterator.
llvm::iterator_range< iterator > decls(DeclarationName Name)
Returns a range of decls with the name 'Name'.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
SourceLocation getAmpLoc() const
Definition TypeLoc.h:1641
Describes the capture of a variable or of this, or of a C++1y init-capture.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
CommentOptions CommentOpts
Options for parsing comments.
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
LangStandard::Kind LangStd
The used language standard.
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
std::string CurrentModule
The name of the current module, of which the main source file is a part.
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
Record the location of a macro definition.
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition MacroInfo.h:315
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Definition MacroInfo.h:352
const MacroInfo * getMacroInfo() const
Definition MacroInfo.h:409
Kind getKind() const
Definition MacroInfo.h:344
SourceLocation getLocation() const
Definition MacroInfo.h:346
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:40
bool isUsed() const
Return false if this macro is defined in the main file and has not yet been used.
Definition MacroInfo.h:225
bool isC99Varargs() const
Definition MacroInfo.h:208
SourceLocation getDefinitionEndLoc() const
Return the location of the last token in the macro.
Definition MacroInfo.h:132
ArrayRef< const IdentifierInfo * > params() const
Definition MacroInfo.h:186
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition MacroInfo.h:236
unsigned getNumParams() const
Definition MacroInfo.h:185
const Token & getReplacementToken(unsigned Tok) const
Definition MacroInfo.h:238
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
Definition MacroInfo.h:218
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Definition MacroInfo.h:126
bool hasCommaPasting() const
Definition MacroInfo.h:220
bool isObjectLike() const
Definition MacroInfo.h:203
bool isUsedForHeaderGuard() const
Determine whether this macro was used for a header guard.
Definition MacroInfo.h:295
bool isGNUVarargs() const
Definition MacroInfo.h:209
SourceLocation getExpansionLoc() const
Definition TypeLoc.h:1410
Expr * getAttrColumnOperand() const
The attribute's column operand, if it has one.
Definition TypeLoc.h:2188
SourceRange getAttrOperandParensRange() const
The location of the parentheses around the operand, if there is an operand.
Definition TypeLoc.h:2195
SourceLocation getAttrNameLoc() const
The location of the attribute name, i.e.
Definition TypeLoc.h:2176
Expr * getAttrRowOperand() const
The attribute's row operand, if it has one.
Definition TypeLoc.h:2182
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:1585
SourceLocation getStarLoc() const
Definition TypeLoc.h:1577
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:41
virtual void writeExtensionContents(Sema &SemaRef, llvm::BitstreamWriter &Stream)=0
Write the contents of the extension block into the given bitstream.
ModuleFileExtension * getExtension() const
Retrieve the module file extension with which this writer is associated.
virtual ModuleFileExtensionMetadata getExtensionMetadata() const =0
Retrieves the metadata for this module file extension.
StringRef str() const
Returns the plain module file name.
Definition Module.h:188
Module * findModule(StringRef Name) const
Retrieve an already loaded module with the given name.
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
ArrayRef< KnownHeader > findResolvedModulesForHeader(FileEntryRef File) const
Like findAllModulesForHeader, but do not attempt to infer module ownership from umbrella headers if w...
FileID getModuleMapFileIDForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module.
FileID getContainingModuleMapFileID(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
ModuleHeaderRole
Flags describing the role of a module header.
Definition ModuleMap.h:123
static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind)
Convert a header kind to a role. Requires Kind to not be HK_Excluded.
Definition ModuleMap.cpp:88
Describes a module or submodule.
Definition Module.h:340
unsigned IsExplicit
Whether this is an explicit submodule.
Definition Module.h:587
SmallVector< ExportDecl, 2 > Exports
The set of export declarations.
Definition Module.h:674
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition Module.h:609
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:731
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:346
Module * Parent
The parent of this module.
Definition Module.h:389
ModuleKind Kind
The kind of this module.
Definition Module.h:385
SmallVector< UnresolvedHeaderDirective, 0 > MissingHeaders
Headers that are mentioned in the module map file but could not be found on the file system.
Definition Module.h:544
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition Module.h:766
unsigned IsInferred
Whether this is an inferred submodule (module * { ... }).
Definition Module.h:602
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:592
std::string Name
The name of this module.
Definition Module.h:343
llvm::iterator_range< submodule_iterator > submodules()
Definition Module.h:1079
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition Module.h:598
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition Module.h:637
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:723
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition Module.h:988
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition Module.h:555
llvm::SmallSetVector< const Module *, 2 > UndeclaredUses
When NoUndeclaredIncludes is true, the set of modules this module tried to import but didn't because ...
Definition Module.h:702
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition Module.h:394
llvm::SmallVector< ModuleRef, 2 > AffectingClangModules
The set of top-level modules that affected the compilation of this module, but were not imported.
Definition Module.h:665
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition Module.h:642
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition Module.h:627
ASTFileSignature Signature
The module signature.
Definition Module.h:410
ArrayRef< Header > getHeaders(HeaderKind HK) const
Definition Module.h:505
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition Module.h:619
ArrayRef< FileEntryRef > getTopHeaders(FileManager &FileMgr)
The top-level headers associated with this module.
Definition Module.cpp:300
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition Module.h:980
bool isHeaderUnit() const
Is this module a header unit.
Definition Module.h:890
unsigned IsFramework
Whether this is a framework module.
Definition Module.h:583
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition Module.h:420
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition Module.h:614
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:943
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition Module.h:661
std::vector< Conflict > Conflicts
The list of conflicts.
Definition Module.h:756
This represents a decl that may have a name.
Definition Decl.h:276
Linkage getLinkageInternal() const
Determine what kind of linkage this entity has.
Definition Decl.cpp:1184
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1209
Represent a C++ namespace.
Definition Decl.h:594
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
TypeLoc castAsTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
SourceRange getLocalSourceRange() const
Retrieve the source range covering just the last part of this nested-name-specifier,...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Kind
The kind of specifier that completes this nested name specifier.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
This represents the 'align' clause in the 'pragma omp allocate' directive.
This represents clause 'allocate' in the 'pragma omp ...' directives.
This represents 'allocator' clause in the 'pragma omp ...' directive.
Class that handles post-update expression for some clauses, like 'lastprivate', 'reduction' etc.
Class that handles pre-initialization statement for some clauses, like 'schedule',...
This is a basic class for representing single OpenMP clause.
This represents 'collapse' clause in the 'pragma omp ...' directive.
This represents the 'counts' clause in the 'pragma omp split' directive.
This represents 'default' clause in the 'pragma omp ...' directive.
This represents the 'depth' clause on the 'pragma omp flatten' (and 'pragma omp fuse') loop-transform...
This represents 'final' clause in the 'pragma omp ...' directive.
Representation of the 'full' clause of the 'pragma omp unroll' directive.
This represents 'if' clause in the 'pragma omp ...' directive.
This class represents the 'looprange' clause in the 'pragma omp fuse' directive.
This represents 'num_threads' clause in the 'pragma omp ...' directive.
Representation of the 'partial' clause of the 'pragma omp unroll' directive.
This class represents the 'permutation' clause in the 'pragma omp interchange' directive.
This represents 'safelen' clause in the 'pragma omp ...' directive.
This represents 'simdlen' clause in the 'pragma omp ...' directive.
This represents the 'sizes' clause in the 'pragma omp tile' directive.
This represents 'threadset' clause in the 'pragma omp task ...' directive.
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2335
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
filtered_category_iterator< isKnownCategory > known_categories_iterator
Iterator that walks over all of the known categories and extensions, including those that are hidden.
Definition DeclObjC.h:1689
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition DeclObjC.h:1548
SourceLocation getNameEndLoc() const
Definition TypeLoc.h:1321
SourceLocation getNameLoc() const
Definition TypeLoc.h:1309
SourceLocation getStarLoc() const
Definition TypeLoc.h:1619
bool hasBaseTypeAsWritten() const
Definition TypeLoc.h:1254
SourceLocation getTypeArgsLAngleLoc() const
Definition TypeLoc.h:1184
unsigned getNumTypeArgs() const
Definition TypeLoc.h:1200
unsigned getNumProtocols() const
Definition TypeLoc.h:1230
TypeSourceInfo * getTypeArgTInfo(unsigned i) const
Definition TypeLoc.h:1204
SourceLocation getProtocolRAngleLoc() const
Definition TypeLoc.h:1222
SourceLocation getProtocolLoc(unsigned i) const
Definition TypeLoc.h:1234
SourceLocation getProtocolLAngleLoc() const
Definition TypeLoc.h:1214
SourceLocation getTypeArgsRAngleLoc() const
Definition TypeLoc.h:1192
Kind getKind() const
Definition ObjCRuntime.h:77
const VersionTuple & getVersion() const
Definition ObjCRuntime.h:78
unsigned getNumProtocols() const
Definition TypeLoc.h:932
SourceLocation getProtocolLoc(unsigned i) const
Definition TypeLoc.h:936
SourceLocation getProtocolLAngleLoc() const
Definition TypeLoc.h:912
SourceLocation getProtocolRAngleLoc() const
Definition TypeLoc.h:922
Represents a clause with one or more 'var' objects, represented as an expr, as its arguments.
This is the base type for all OpenACC Clauses.
SourceLocation getAttrLoc() const
Definition TypeLoc.h:1097
SourceLocation getEllipsisLoc() const
Definition TypeLoc.h:2681
SourceLocation getEllipsisLoc() const
Definition TypeLoc.h:2367
SourceLocation getRParenLoc() const
Definition TypeLoc.h:1438
SourceLocation getLParenLoc() const
Definition TypeLoc.h:1434
Represents a parameter to a function.
Definition Decl.h:1832
SourceLocation getKWLoc() const
Definition TypeLoc.h:2776
SourceLocation getStarLoc() const
Definition TypeLoc.h:1546
MacroDefinitionRecord * findMacroDefinition(const MacroInfo *MI)
Retrieve the macro definition that corresponds to the given MacroInfo.
const std::vector< SourceRange > & getSkippedRanges()
Retrieve all ranges that got skipped while preprocessing.
iterator local_begin()
Begin iterator for local, non-loaded, preprocessed entities.
iterator local_end()
End iterator for local, non-loaded, preprocessed entities.
std::vector< std::string > MacroIncludes
std::vector< std::string > Includes
bool WriteCommentListToPCH
Whether to write comment locations into the PCH when building it.
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
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 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.
ArrayRef< ModuleMacro * > getLeafModuleMacros(const IdentifierInfo *II) const
Get the list of leaf (non-overridden) module macros for a name.
ArrayRef< PPConditionalInfo > getPreambleConditionalStack() const
bool isRecordingPreamble() const
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
bool SawDateOrTime() const
Returns true if the preprocessor has seen a use of DATE or TIME in the file so far.
SourceManager & getSourceManager() const
std::optional< PreambleSkipInfo > getPreambleSkipInfo() const
bool hasRecordedPreamble() const
const TargetInfo & getTargetInfo() const
FileManager & getFileManager() const
bool alreadyIncluded(FileEntryRef File) const
Return true if this header has already been included.
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
HeaderSearch & getHeaderSearchInfo() const
SmallVector< SourceLocation, 64 > serializeSafeBufferOptOutMap() const
IdentifierTable & getIdentifierTable()
const PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
const LangOptions & getLangOpts() const
PreprocessingRecord * getPreprocessingRecord() const
Retrieve the preprocessing record, or NULL if there is no preprocessing record.
DiagnosticsEngine & getDiagnostics() const
uint32_t getCounterValue() const
SourceLocation getPreambleRecordedPragmaAssumeNonNullLoc() const
Get the location of the recorded unterminated #pragma clang assume_nonnull begin in the preamble,...
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
A (possibly-)qualified type.
Definition TypeBase.h:938
Wrapper of type source information for a type with non-trivial direct qualifiers.
Definition TypeLoc.h:300
SourceLocation getAmpAmpLoc() const
Definition TypeLoc.h:1655
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
bool isAlmostTrailingComment() const LLVM_READONLY
Returns true if it is a probable typo:
CommentKind getKind() const LLVM_READONLY
SourceRange getSourceRange() const LLVM_READONLY
Represents a struct/union/class.
Definition Decl.h:4506
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Smart pointer class that efficiently represents Objective-C method names.
const IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
void * getAsOpaquePtr() const
unsigned getNumArgs() const
void updateOutOfDateSelector(Selector Sel)
llvm::MapVector< Selector, SourceLocation > ReferencedSelectors
Method selectors used in a @selector expression.
Definition SemaObjC.h:209
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition SemaObjC.h:220
ArrayRef< const OMPRequiresDecl * > getRequiresDecls() const
The 'requires' directives seen so far in this translation unit.
bool DeclareAndesVectorBuiltins
Indicate RISC-V Andes vector builtin functions enabled or not.
Definition SemaRISCV.h:55
bool DeclareSiFiveVectorBuiltins
Indicate RISC-V SiFive vector builtin functions enabled or not.
Definition SemaRISCV.h:52
bool DeclareRVVBuiltins
Indicate RISC-V vector builtin functions enabled or not.
Definition SemaRISCV.h:49
static uint32_t getRawEncoding(const AlignPackInfo &Info)
Definition Sema.h:1939
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
SemaOpenMP & OpenMP()
Definition Sema.h:1578
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition Sema.h:6718
SemaCUDA & CUDA()
Definition Sema.h:1518
Preprocessor & getPreprocessor() const
Definition Sema.h:934
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2125
ExtVectorDeclsType ExtVectorDecls
ExtVectorDecls - This is a list all the extended vector types.
Definition Sema.h:5111
SourceLocation getOptimizeOffPragmaLocation() const
Get the location for the currently active "\#pragma clang optimizeoff". If this location is invalid,...
Definition Sema.h:2203
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2126
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11661
ASTContext & Context
Definition Sema.h:1339
SemaObjC & ObjC()
Definition Sema.h:1563
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition Sema.h:3753
SmallVector< const Decl * > DeclsWithEffectsToVerify
All functions/lambdas/blocks which have bodies and which have a non-empty FunctionEffectsRef to be ve...
Definition Sema.h:16052
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8585
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition Sema.h:6105
Preprocessor & PP
Definition Sema.h:1338
llvm::MapVector< const FunctionDecl *, std::unique_ptr< LateParsedTemplate > > LateParsedTemplateMapT
Definition Sema.h:11660
CXXRecordDecl * getStdBadAlloc() const
SemaRISCV & RISCV()
Definition Sema.h:1593
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1884
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition Sema.h:6111
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:2107
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4968
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3736
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:14357
bool MSStructPragmaOn
Definition Sema.h:1881
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition Sema.cpp:984
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6721
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14340
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition Sema.h:3760
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Retrieves list of suspicious delete-expressions that will be checked at the end of translation unit.
Definition Sema.cpp:3169
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:929
NamespaceDecl * getStdNamespace() const
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition Sema.h:1879
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3729
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:8589
void getSortedUnusedLocalTypedefNameCandidates(SmallVectorImpl< const TypedefNameDecl * > &Sorted) const
Store UnusedLocalTypedefNameCandidates in Sorted in a deterministic order.
Definition Sema.cpp:1200
IdentifierResolver IdResolver
Definition Sema.h:3652
A delta encoder for a run of source locations.
static RawLocEncoding encode(SourceLocation Loc, UIntTy BaseOffset, unsigned BaseModuleFileIndex)
Encodes a location in the source.
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.
FileIDAndOffset getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
DiagnosticsEngine & getDiagnostics() const
SourceLocation::UIntTy getNextLocalOffset() const
bool isLocalSourceLocation(SourceLocation Loc) const
Returns true if Loc did not come from a PCH/Module.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
const SrcMgr::SLocEntry & getLocalSLocEntry(unsigned Index) const
Get a local SLocEntry. This is exposed for indexing.
FileManager & getFileManager() const
unsigned local_sloc_entry_size() const
Get the number of local SLocEntries we have.
SourceLocation getLocForEndOfFile(FileID FID) const
Return the source location corresponding to the last byte of the specified file.
FileID getMainFileID() const
Returns the FileID of the main source file.
unsigned getFileIDSize(FileID FID) const
The size of the SLocEntry that FID represents.
bool hasLineTable() const
Determine if the source manager has a line table.
bool isLoadedFileID(FileID FID) const
Returns true if FID came from a PCH/Module.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
SourceLocation getFileLoc(SourceLocation Loc, unsigned MaxDepth=std::numeric_limits< unsigned >::max()) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
LineTableInfo & getLineTable()
Retrieve the stored line table.
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
OptionalFileEntryRef ContentsEntry
References the file which the contents were actually loaded from.
unsigned IsTransient
True if this file may be transient, that is, if it might not exist at some later point in time when t...
std::optional< llvm::MemoryBufferRef > getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM, SourceLocation Loc=SourceLocation()) const
Returns the memory buffer for the associated content.
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.
SourceLocation getExpansionLocStart() const
SourceLocation getSpellingLoc() const
SourceLocation getExpansionLocEnd() const
const ContentCache & getContentCache() const
This is a discriminated union of FileInfo and ExpansionInfo.
SourceLocation::UIntTy getOffset() const
const FileInfo & getFile() const
const ExpansionInfo & getExpansion() const
An array of decls optimized for the common case of only containing one entry.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3898
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3999
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:4044
SourceLocation getNameLoc() const
Definition TypeLoc.h:822
SourceLocation getElaboratedKeywordLoc() const
Definition TypeLoc.h:801
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:809
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:334
std::string Triple
The name of the target triple to compile for.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string ABI
If given, the name of the target ABI to use.
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line.
A template argument list.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Location wrapper for a TemplateArgument.
SourceLocation getTemplateEllipsisLoc() const
TemplateArgumentLocInfo getLocInfo() const
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
SourceLocation getTemplateKWLoc() const
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
SourceLocation getTemplateLoc() const
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:1938
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:1948
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:1953
SourceLocation getTemplateNameLoc() const
Definition TypeLoc.h:1936
SourceLocation getTemplateKeywordLoc() const
Definition TypeLoc.h:1932
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:1922
SourceLocation getElaboratedKeywordLoc() const
Definition TypeLoc.h:1918
Token - This structure provides full information about a lexed token.
Definition Token.h:36
The top declaration context.
Definition Decl.h:107
NamespaceDecl * getAnonymousNamespace() const
Definition Decl.h:145
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
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:171
bool isNull() const
Definition TypeLoc.h:121
TypeSourceInfo * getUnmodifiedTInfo() const
Definition TypeLoc.h:2313
A container of type source information.
Definition TypeBase.h:8549
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8560
SourceLocation getNameLoc() const
Definition TypeLoc.h:547
TypeClass getTypeClass() const
Definition TypeBase.h:2449
SourceLocation getLParenLoc() const
Definition TypeLoc.h:2256
SourceLocation getRParenLoc() const
Definition TypeLoc.h:2264
SourceLocation getTypeofLoc() const
Definition TypeLoc.h:2248
SourceLocation getKWLoc() const
Definition TypeLoc.h:2395
SourceLocation getRParenLoc() const
Definition TypeLoc.h:2401
TypeSourceInfo * getUnderlyingTInfo() const
Definition TypeLoc.h:2404
SourceLocation getLParenLoc() const
Definition TypeLoc.h:2398
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
Represents a variable declaration or definition.
Definition Decl.h:934
const APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or nullptr if the value is not yet...
Definition Decl.cpp:2643
bool hasInitWithSideEffects() const
Checks whether this declaration has an initializer with side effects.
Definition Decl.cpp:2448
EvaluatedStmt * getEvaluatedStmt() const
Definition Decl.cpp:2566
const Expr * getInit() const
Definition Decl.h:1393
Declaration of a variable template.
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getAttrNameLoc() const
Definition TypeLoc.h:2080
Expr * getSizeExpr() const
Definition TypeLoc.h:2083
SourceLocation getNameLoc() const
Definition TypeLoc.h:2077
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:687
SourceLocation getEllipsisLoc() const
Retrieve the source location of the ellipsis, whose presence indicates that the capture is a pack exp...
Definition ScopeInfo.h:691
OverloadedOperatorKind getOperatorKind() const
IdentifierInfo * getIdentifier() const
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:158
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition ModuleFile.h:484
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition ModuleFile.h:448
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition ModuleFile.h:573
unsigned Index
The index of this module in the list of modules.
Definition ModuleFile.h:171
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition ModuleFile.h:451
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition ModuleFile.h:342
ModuleFileName FileName
The file name of the module file.
Definition ModuleFile.h:177
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition ModuleFile.h:477
ModuleKind Kind
The type of this module.
Definition ModuleFile.h:174
std::string ModuleName
The name of the module.
Definition ModuleFile.h:183
A type index; the type ID with the qualifier bits removed.
Definition ASTBitCodes.h:99
uint32_t getModuleFileIndex() const
TypeID asTypeID(unsigned FastQuals) const
SmallVector< LazySpecializationInfo, 4 > data_type
The lookup result is a list of global declaration IDs.
const unsigned int LOCAL_REDECLARATIONS
Record code for a list of local redeclarations of a declaration.
TypeCode
Record codes for each kind of type.
const unsigned int DECL_UPDATES
Record of updates for a declaration that was modified after being deserialized.
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
@ PREDEF_TYPE_NULL_ID
The NULL type.
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
@ DECL_EMPTY
An EmptyDecl record.
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
@ DECL_CXX_RECORD
A CXXRecordDecl record.
@ DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION
A VarTemplatePartialSpecializationDecl record.
@ DECL_OMP_ALLOCATE
An OMPAllocateDcl record.
@ DECL_MS_PROPERTY
A MSPropertyDecl record.
@ DECL_REQUIRES_EXPR_BODY
A RequiresExprBodyDecl record.
@ DECL_STATIC_ASSERT
A StaticAssertDecl record.
@ DECL_INDIRECTFIELD
A IndirectFieldDecl record.
@ DECL_TEMPLATE_TEMPLATE_PARM
A TemplateTemplateParmDecl record.
@ DECL_IMPORT
An ImportDecl recording a module import.
@ DECL_ACCESS_SPEC
An AccessSpecDecl record.
@ DECL_OBJC_TYPE_PARAM
An ObjCTypeParamDecl record.
@ DECL_OBJC_CATEGORY_IMPL
A ObjCCategoryImplDecl record.
@ DECL_ENUM_CONSTANT
An EnumConstantDecl record.
@ DECL_PARM_VAR
A ParmVarDecl record.
@ DECL_TYPEDEF
A TypedefDecl record.
@ DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK
A TemplateTemplateParmDecl record that stores an expanded template template parameter pack.
@ DECL_HLSL_BUFFER
A HLSLBufferDecl record.
@ DECL_NAMESPACE_ALIAS
A NamespaceAliasDecl record.
@ DECL_TYPEALIAS
A TypeAliasDecl record.
@ DECL_FUNCTION_TEMPLATE
A FunctionTemplateDecl record.
@ DECL_UNRESOLVED_USING_TYPENAME
An UnresolvedUsingTypenameDecl record.
@ DECL_CLASS_TEMPLATE_SPECIALIZATION
A ClassTemplateSpecializationDecl record.
@ DECL_FILE_SCOPE_ASM
A FileScopeAsmDecl record.
@ DECL_CXX_CONSTRUCTOR
A CXXConstructorDecl record.
@ DECL_CXX_CONVERSION
A CXXConversionDecl record.
@ DECL_FIELD
A FieldDecl record.
@ DECL_LINKAGE_SPEC
A LinkageSpecDecl record.
@ DECL_CONTEXT_TU_LOCAL_VISIBLE
A record that stores the set of declarations that are only visible to the TU.
@ DECL_NAMESPACE
A NamespaceDecl record.
@ DECL_NON_TYPE_TEMPLATE_PARM
A NonTypeTemplateParmDecl record.
@ DECL_FUNCTION
A FunctionDecl record.
@ DECL_USING_DIRECTIVE
A UsingDirecitveDecl record.
@ DECL_RECORD
A RecordDecl record.
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
@ DECL_BLOCK
A BlockDecl record.
@ DECL_UNRESOLVED_USING_VALUE
An UnresolvedUsingValueDecl record.
@ DECL_TYPE_ALIAS_TEMPLATE
A TypeAliasTemplateDecl record.
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
@ DECL_OBJC_CATEGORY
A ObjCCategoryDecl record.
@ DECL_VAR
A VarDecl record.
@ DECL_USING
A UsingDecl record.
@ DECL_OBJC_PROTOCOL
A ObjCProtocolDecl record.
@ DECL_TEMPLATE_TYPE_PARM
A TemplateTypeParmDecl record.
@ DECL_VAR_TEMPLATE_SPECIALIZATION
A VarTemplateSpecializationDecl record.
@ DECL_OBJC_IMPLEMENTATION
A ObjCImplementationDecl record.
@ DECL_OBJC_COMPATIBLE_ALIAS
A ObjCCompatibleAliasDecl record.
@ DECL_FRIEND_TEMPLATE
A FriendTemplateDecl record.
@ DECL_PRAGMA_DETECT_MISMATCH
A PragmaDetectMismatchDecl record.
@ DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK
A NonTypeTemplateParmDecl record that stores an expanded non-type template parameter pack.
@ DECL_OBJC_AT_DEFS_FIELD
A ObjCAtDefsFieldDecl record.
@ DECL_IMPLICIT_PARAM
An ImplicitParamDecl record.
@ DECL_FRIEND
A FriendDecl record.
@ DECL_CXX_METHOD
A CXXMethodDecl record.
@ DECL_EXPORT
An ExportDecl record.
@ DECL_PRAGMA_COMMENT
A PragmaCommentDecl record.
@ DECL_ENUM
An EnumDecl record.
@ DECL_CONTEXT_MODULE_LOCAL_VISIBLE
A record containing the set of declarations that are only visible from DeclContext in the same module...
@ DECL_OMP_DECLARE_REDUCTION
An OMPDeclareReductionDecl record.
@ DECL_OMP_THREADPRIVATE
An OMPThreadPrivateDecl record.
@ DECL_OBJC_METHOD
A ObjCMethodDecl record.
@ DECL_CXX_DESTRUCTOR
A CXXDestructorDecl record.
@ DECL_OMP_CAPTUREDEXPR
An OMPCapturedExprDecl record.
@ DECL_CLASS_TEMPLATE
A ClassTemplateDecl record.
@ DECL_USING_SHADOW
A UsingShadowDecl record.
@ DECL_CONCEPT
A ConceptDecl record.
@ DECL_OBJC_IVAR
A ObjCIvarDecl record.
@ DECL_OBJC_PROPERTY
A ObjCPropertyDecl record.
@ DECL_OBJC_INTERFACE
A ObjCInterfaceDecl record.
@ DECL_VAR_TEMPLATE
A VarTemplateDecl record.
@ DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION
A ClassTemplatePartialSpecializationDecl record.
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
@ DECL_OBJC_PROPERTY_IMPL
A ObjCPropertyImplDecl record.
@ TYPE_EXT_QUAL
An ExtQualType record.
@ EXPR_DESIGNATED_INIT
A DesignatedInitExpr record.
@ EXPR_COMPOUND_LITERAL
A CompoundLiteralExpr record.
@ EXPR_OBJC_IVAR_REF_EXPR
An ObjCIvarRefExpr record.
@ EXPR_MEMBER
A MemberExpr record.
@ EXPR_CXX_TEMPORARY_OBJECT
A CXXTemporaryObjectExpr record.
@ EXPR_COMPOUND_ASSIGN_OPERATOR
A CompoundAssignOperator record.
@ EXPR_CXX_STATIC_CAST
A CXXStaticCastExpr record.
@ EXPR_OBJC_STRING_LITERAL
An ObjCStringLiteral record.
@ EXPR_VA_ARG
A VAArgExpr record.
@ EXPR_CXX_OPERATOR_CALL
A CXXOperatorCallExpr record.
@ STMT_OBJC_AT_TRY
An ObjCAtTryStmt record.
@ STMT_DO
A DoStmt record.
@ STMT_OBJC_CATCH
An ObjCAtCatchStmt record.
@ STMT_IF
An IfStmt record.
@ EXPR_STRING_LITERAL
A StringLiteral record.
@ EXPR_IMPLICIT_CAST
An ImplicitCastExpr record.
@ STMT_GCCASM
A GCC-style AsmStmt record.
@ EXPR_IMAGINARY_LITERAL
An ImaginaryLiteral record.
@ STMT_WHILE
A WhileStmt record.
@ EXPR_STMT
A StmtExpr record.
@ EXPR_CXX_REINTERPRET_CAST
A CXXReinterpretCastExpr record.
@ EXPR_DESIGNATED_INIT_UPDATE
A DesignatedInitUpdateExpr record.
@ STMT_OBJC_AT_SYNCHRONIZED
An ObjCAtSynchronizedStmt record.
@ EXPR_CHARACTER_LITERAL
A CharacterLiteral record.
@ EXPR_OBJC_ENCODE
An ObjCEncodeExpr record.
@ EXPR_CSTYLE_CAST
A CStyleCastExpr record.
@ EXPR_OBJC_BOOL_LITERAL
An ObjCBoolLiteralExpr record.
@ EXPR_EXT_VECTOR_ELEMENT
An ExtVectorElementExpr record.
@ STMT_RETURN
A ReturnStmt record.
@ STMT_OBJC_FOR_COLLECTION
An ObjCForCollectionStmt record.
@ STMT_CONTINUE
A ContinueStmt record.
@ EXPR_PREDEFINED
A PredefinedExpr record.
@ EXPR_CXX_BOOL_LITERAL
A CXXBoolLiteralExpr record.
@ EXPR_PAREN_LIST
A ParenListExpr record.
@ EXPR_CXX_PAREN_LIST_INIT
A CXXParenListInitExpr record.
@ STMT_COMPOUND
A CompoundStmt record.
@ STMT_FOR
A ForStmt record.
@ STMT_ATTRIBUTED
An AttributedStmt record.
@ EXPR_CXX_REWRITTEN_BINARY_OPERATOR
A CXXRewrittenBinaryOperator record.
@ STMT_GOTO
A GotoStmt record.
@ EXPR_NO_INIT
An NoInitExpr record.
@ EXPR_OBJC_PROTOCOL_EXPR
An ObjCProtocolExpr record.
@ EXPR_CXX_CONSTRUCT
A CXXConstructExpr record.
@ EXPR_CXX_DYNAMIC_CAST
A CXXDynamicCastExpr record.
@ STMT_CXX_TRY
A CXXTryStmt record.
@ EXPR_GENERIC_SELECTION
A GenericSelectionExpr record.
@ EXPR_CALL
A CallExpr record.
@ EXPR_GNU_NULL
A GNUNullExpr record.
@ EXPR_OBJC_PROPERTY_REF_EXPR
An ObjCPropertyRefExpr record.
@ EXPR_CXX_CONST_CAST
A CXXConstCastExpr record.
@ STMT_REF_PTR
A reference to a previously [de]serialized Stmt record.
@ EXPR_OBJC_MESSAGE_EXPR
An ObjCMessageExpr record.
@ STMT_CASE
A CaseStmt record.
@ STMT_STOP
A marker record that indicates that we are at the end of an expression.
@ STMT_MSASM
A MS-style AsmStmt record.
@ EXPR_CONDITIONAL_OPERATOR
A ConditionOperator record.
@ EXPR_BINARY_OPERATOR
A BinaryOperator record.
@ EXPR_CXX_STD_INITIALIZER_LIST
A CXXStdInitializerListExpr record.
@ EXPR_SHUFFLE_VECTOR
A ShuffleVectorExpr record.
@ STMT_OBJC_FINALLY
An ObjCAtFinallyStmt record.
@ EXPR_OBJC_SELECTOR_EXPR
An ObjCSelectorExpr record.
@ EXPR_FLOATING_LITERAL
A FloatingLiteral record.
@ STMT_NULL_PTR
A NULL expression.
@ STMT_DEFAULT
A DefaultStmt record.
@ EXPR_CHOOSE
A ChooseExpr record.
@ STMT_NULL
A NullStmt record.
@ EXPR_DECL_REF
A DeclRefExpr record.
@ EXPR_INIT_LIST
An InitListExpr record.
@ EXPR_IMPLICIT_VALUE_INIT
An ImplicitValueInitExpr record.
@ EXPR_PAREN
A ParenExpr record.
@ STMT_LABEL
A LabelStmt record.
@ EXPR_CXX_FUNCTIONAL_CAST
A CXXFunctionalCastExpr record.
@ EXPR_USER_DEFINED_LITERAL
A UserDefinedLiteral record.
@ EXPR_INTEGER_LITERAL
An IntegerLiteral record.
@ EXPR_CXX_MEMBER_CALL
A CXXMemberCallExpr record.
@ STMT_SWITCH
A SwitchStmt record.
@ STMT_DECL
A DeclStmt record.
@ EXPR_OBJC_KVC_REF_EXPR
UNUSED.
@ EXPR_SIZEOF_ALIGN_OF
A SizefAlignOfExpr record.
@ STMT_BREAK
A BreakStmt record.
@ STMT_OBJC_AT_THROW
An ObjCAtThrowStmt record.
@ EXPR_ADDR_LABEL
An AddrLabelExpr record.
@ STMT_CXX_FOR_RANGE
A CXXForRangeStmt record.
@ EXPR_CXX_ADDRSPACE_CAST
A CXXAddrspaceCastExpr record.
@ EXPR_ARRAY_SUBSCRIPT
An ArraySubscriptExpr record.
@ EXPR_UNARY_OPERATOR
A UnaryOperator record.
@ STMT_CXX_CATCH
A CXXCatchStmt record.
@ STMT_INDIRECT_GOTO
An IndirectGotoStmt record.
Defines the clang::TargetInfo interface.
bool isSystem(CharacteristicKind CK)
Determine whether a file / directory characteristic is for system code.
bool isModuleMap(CharacteristicKind CK)
Determine whether a file characteristic is for a module map.
VE builtins.
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1512
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
@ EXTENSION_METADATA
Metadata describing this particular extension.
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
@ SUBMODULE_REQUIRES
Specifies a required feature.
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
@ SUBMODULE_CHILD
Specifies a direct submodule by name and ID, enabling on-demand deserialization of children without l...
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
@ SUBMODULE_END
Defines the end of a single submodule. Sentinel record without any data.
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
TypeIdx TypeIdxFromBuiltin(const BuiltinType *BT)
Definition ASTCommon.cpp:26
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
@ UserFiles
When the validation is done only for user files as an optimization.
Definition ModuleFile.h:146
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition ASTBitCodes.h:66
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
@ TARGET_OPTIONS
Record code for the target options table.
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
@ CODEGEN_OPTIONS
Record code for the codegen options table.
@ LANGUAGE_OPTIONS
Record code for the language options table.
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
@ COMMENTS_BLOCK_ID
The block containing comments.
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
unsigned StableHashForTemplateArguments(llvm::ArrayRef< TemplateArgument > Args)
Calculate a stable hash value for template arguments.
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition ASTBitCodes.h:70
const unsigned VERSION_MINOR
AST file minor version number supported by this version of Clang.
Definition ASTBitCodes.h:57
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition ASTBitCodes.h:47
uint64_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
@ PP_TOKEN
Describes one token.
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
@ PP_MODULE_MACRO
A macro directive exported by a module.
void numberAnonymousDeclsWithin(const DeclContext *DC, Fn Visit)
Visit each declaration within DC that needs an anonymous declaration number and call Visit with the d...
Definition ASTCommon.h:76
@ MODULE_DIRECTORY_DEPENDENCIES
Record code for the directories this AST file depends on the listing of.
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
@ MODULE_DIRECTORY
Record code for the module build directory.
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
@ MODULE_NAME
Record code for the module name.
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
@ SIGNATURE
Record code for the signature that identifiers this AST file.
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
@ VFS_USAGE
Record code for the indices of used VFSs.
uint64_t MacroID
An ID number that refers to a macro in an AST file.
@ INPUT_FILE_HASH
The input file content hash.
@ INPUT_FILE
An input file.
const DeclContext * getDefinitiveDeclContext(const DeclContext *DC)
Retrieve the "definitive" declaration that provides all of the visible entries for the given declarat...
uint64_t TypeID
An ID number that refers to a type in an AST file.
Definition ASTBitCodes.h:88
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition ModuleFile.h:61
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
@ TYPE_OFFSET
Record code for the offsets of each type.
@ DELEGATING_CTORS
The list of delegating constructor declarations.
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
@ PP_UNSAFE_BUFFER_USAGE
Record code for #pragma clang unsafe_buffer_usage begin/end.
@ CXX_ADDED_TEMPLATE_PARTIAL_SPECIALIZATION
@ DECLS_WITH_EFFECTS_TO_VERIFY
Record code for Sema's vector of functions/blocks with effects to be verified.
@ VTABLE_USES
Record code for the array of VTable uses.
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
@ SUBMODULE_METADATA
Record that encodes the number of submodules, their base ID in the AST file, and for each module the ...
@ DECL_OFFSET
Record code for the offsets of each decl.
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
@ OMP_REQUIRES_DECLS
Record code for the OpenMP 'requires' directives seen in the TU.
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
@ EXTNAME_UNDECLARED_IDENTIFIERS
Record code for extname-redefined undeclared identifiers.
@ RELATED_DECLS_MAP
Record code for related declarations that have to be deserialized together from the same module.
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched pragma clang cuda_force_host_device begin directives we've seen.
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
@ RISCV_VECTOR_INTRINSICS_PRAGMA
Record code for pragma clang riscv intrinsic vector.
@ OPENCL_EXTENSION_DECLS
Record code for declarations associated with OpenCL extensions.
@ VTABLES_TO_EMIT
Record code for vtables to emit.
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
@ METHOD_POOL
Record code for the Objective-C method pool,.
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
@ PP_CONDITIONAL_STACK
The stack of open ifs/ifdefs recorded in a preamble.
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
@ OPENCL_EXTENSION_TYPES
Record code for types associated with OpenCL extensions.
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
@ HEADER_SEARCH_TABLE
Record code for header search information.
@ OBJC_CATEGORIES_MAP
Record code for map of Objective-C class definition IDs to the ObjC categories in a module that are a...
@ METADATA_OLD_FORMAT
This is so that older clang versions, before the introduction of the control block,...
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
@ IDENTIFIER_TABLE
Record code for the identifier table.
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
unsigned ComputeHash(Selector Sel)
uint64_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition ASTBitCodes.h:63
std::shared_ptr< MatchComputation< T > > Generator
Definition RewriteRule.h:65
RangeSelector range(RangeSelector Begin, RangeSelector End)
DEPRECATED. Use enclose.
Top level wrappers for InstallAPI frontend operations.
@ NUM_OVERLOADED_OPERATORS
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:216
@ CPlusPlus
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ LCK_ByCopy
Capturing by copy (a.k.a., by value)
Definition Lambda.h:36
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ LCK_VLAType
Capturing variable-length array type.
Definition Lambda.h:38
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
@ LCK_This
Capturing the *this object by reference.
Definition Lambda.h:34
@ 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'.
@ Shortloop
'shortloop' is represented in the ACC.td file, but isn't present in the standard.
@ 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.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
IdentifierLoc DeviceTypeArgument
static constexpr unsigned NumberOfOMPMapClauseModifiers
Number of allowed map-type-modifiers.
Definition OpenMPKinds.h:88
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
@ Undefined
Keep undefined.
PredefinedDeclIDs
Predefined declaration IDs.
Definition DeclID.h:31
@ PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID
The internal '__NSConstantString' tag type.
Definition DeclID.h:78
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition DeclID.h:36
@ PREDEF_DECL_OBJC_CLASS_ID
The Objective-C 'Class' type.
Definition DeclID.h:45
@ PREDEF_DECL_BUILTIN_MS_GUID_ID
The predeclared '_GUID' struct.
Definition DeclID.h:69
@ PREDEF_DECL_BUILTIN_MS_TYPE_INFO_TAG_ID
The predeclared 'type_info' struct.
Definition DeclID.h:81
@ PREDEF_DECL_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition DeclID.h:57
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition DeclID.h:48
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition DeclID.h:54
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition DeclID.h:42
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition DeclID.h:51
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition DeclID.h:63
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition DeclID.h:66
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition DeclID.h:75
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition DeclID.h:60
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition DeclID.h:72
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition DeclID.h:39
@ PREDEF_DECL_BUILTIN_ZOS_VA_LIST_ID
The internal '__builtin_zos_va_list' typedef.
Definition DeclID.h:84
@ Property
The type of a property.
Definition TypeBase.h:912
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool CanElideDeclDef(const Decl *D)
If we can elide the definition of.
static constexpr unsigned NumberOfOMPMotionModifiers
Number of allowed motion-modifiers.
@ PMSST_ON
Definition PragmaKinds.h:26
@ PMSST_OFF
Definition PragmaKinds.h:25
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition Version.cpp:68
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
UnsignedOrNone getPrimaryModuleHash(const Module *M)
Calculate a hash value for the primary module name of the given module.
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
int32_t uint32_t uint32_t __builtin_riscv_mhracc_i32 __builtin_riscv_mhraccu_u32 __builtin_riscv_mhraccsu_i32 __builtin_riscv_mhacc_h1_i32 __builtin_riscv_mhaccsu_h1_i32 __builtin_riscv_mulqr_i32 __builtin_riscv_mqrwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 uint16_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
int32_t uint32_t uint32_t __builtin_riscv_mhracc_i32 __builtin_riscv_mhraccu_u32 __builtin_riscv_mhraccsu_i32 __builtin_riscv_mhacc_h1_i32 __builtin_riscv_mhaccsu_h1_i32 __builtin_riscv_mulqr_i32 __builtin_riscv_mqrwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
The signature of a module, which is a hash of the AST content.
Definition Module.h:198
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition Module.h:221
static ASTFileSignature createDummy()
Definition Module.h:231
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments.
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
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...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
const DeclarationNameLoc & getInfo() const
Structure used to store a statement, the constant value to which it was evaluated (if any),...
Definition Decl.h:887
The preprocessor keeps track of this information for each file that is #included.
unsigned isModuleHeader
Whether this header is part of and built with a module.
unsigned isCompilingModuleHeader
Whether this header is part of the module that we are building, even if it doesn't build with the mod...
unsigned IsLocallyIncluded
True if this file has been included (or imported) locally.
unsigned IgnoreSysRoot
IgnoreSysRoot - This is false if an absolute path should be treated relative to the sysroot,...
FPOptions FPO
Floating-point options in the point of definition.
Definition Sema.h:16150
Decl * D
The template function declaration to be late parsed.
Definition Sema.h:16148
ObjCMethodDecl * getMethod() const
A struct with extended info about a syntactic name qualifier, to be used for the case of out-of-line ...
Definition Decl.h:755
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition Decl.h:769
NestedNameSpecifierLoc QualifierLoc
Definition Decl.h:756
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition Decl.h:762
Location information for a TemplateArgument.
TypeSourceInfo * getAsTypeSourceInfo() const
MultiOnDiskHashTable< ASTDeclContextNameLookupTrait > Table
MultiOnDiskHashTable< LazySpecializationInfoLookupTrait > Table
MultiOnDiskHashTable< ModuleLocalNameLookupTrait > Table