clang 19.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"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclBase.h"
22#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
36#include "clang/AST/Type.h"
43#include "clang/Basic/LLVM.h"
44#include "clang/Basic/Lambda.h"
46#include "clang/Basic/Module.h"
56#include "clang/Basic/Version.h"
59#include "clang/Lex/MacroInfo.h"
60#include "clang/Lex/ModuleMap.h"
64#include "clang/Lex/Token.h"
67#include "clang/Sema/Sema.h"
68#include "clang/Sema/SemaCUDA.h"
69#include "clang/Sema/Weak.h"
77#include "llvm/ADT/APFloat.h"
78#include "llvm/ADT/APInt.h"
79#include "llvm/ADT/APSInt.h"
80#include "llvm/ADT/ArrayRef.h"
81#include "llvm/ADT/DenseMap.h"
82#include "llvm/ADT/Hashing.h"
83#include "llvm/ADT/PointerIntPair.h"
84#include "llvm/ADT/STLExtras.h"
85#include "llvm/ADT/ScopeExit.h"
86#include "llvm/ADT/SmallPtrSet.h"
87#include "llvm/ADT/SmallString.h"
88#include "llvm/ADT/SmallVector.h"
89#include "llvm/ADT/StringMap.h"
90#include "llvm/ADT/StringRef.h"
91#include "llvm/Bitstream/BitCodes.h"
92#include "llvm/Bitstream/BitstreamWriter.h"
93#include "llvm/Support/Casting.h"
94#include "llvm/Support/Compression.h"
95#include "llvm/Support/DJB.h"
96#include "llvm/Support/Endian.h"
97#include "llvm/Support/EndianStream.h"
98#include "llvm/Support/Error.h"
99#include "llvm/Support/ErrorHandling.h"
100#include "llvm/Support/LEB128.h"
101#include "llvm/Support/MemoryBuffer.h"
102#include "llvm/Support/OnDiskHashTable.h"
103#include "llvm/Support/Path.h"
104#include "llvm/Support/SHA1.h"
105#include "llvm/Support/TimeProfiler.h"
106#include "llvm/Support/VersionTuple.h"
107#include "llvm/Support/raw_ostream.h"
108#include <algorithm>
109#include <cassert>
110#include <cstdint>
111#include <cstdlib>
112#include <cstring>
113#include <ctime>
114#include <limits>
115#include <memory>
116#include <optional>
117#include <queue>
118#include <tuple>
119#include <utility>
120#include <vector>
121
122using namespace clang;
123using namespace clang::serialization;
124
125template <typename T, typename Allocator>
126static StringRef bytes(const std::vector<T, Allocator> &v) {
127 if (v.empty()) return StringRef();
128 return StringRef(reinterpret_cast<const char*>(&v[0]),
129 sizeof(T) * v.size());
130}
131
132template <typename T>
133static StringRef bytes(const SmallVectorImpl<T> &v) {
134 return StringRef(reinterpret_cast<const char*>(v.data()),
135 sizeof(T) * v.size());
136}
137
138static std::string bytes(const std::vector<bool> &V) {
139 std::string Str;
140 Str.reserve(V.size() / 8);
141 for (unsigned I = 0, E = V.size(); I < E;) {
142 char Byte = 0;
143 for (unsigned Bit = 0; Bit < 8 && I < E; ++Bit, ++I)
144 Byte |= V[I] << Bit;
145 Str += Byte;
146 }
147 return Str;
148}
149
150//===----------------------------------------------------------------------===//
151// Type serialization
152//===----------------------------------------------------------------------===//
153
155 switch (id) {
156#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
157 case Type::CLASS_ID: return TYPE_##CODE_ID;
158#include "clang/Serialization/TypeBitCodes.def"
159 case Type::Builtin:
160 llvm_unreachable("shouldn't be serializing a builtin type this way");
161 }
162 llvm_unreachable("bad type kind");
163}
164
165namespace {
166
167std::optional<std::set<const FileEntry *>>
168GetAffectingModuleMaps(const Preprocessor &PP, Module *RootModule) {
169 if (!PP.getHeaderSearchInfo()
172 return std::nullopt;
173
174 const HeaderSearch &HS = PP.getHeaderSearchInfo();
175 const ModuleMap &MM = HS.getModuleMap();
176 const SourceManager &SourceMgr = PP.getSourceManager();
177
178 std::set<const FileEntry *> ModuleMaps;
179 auto CollectIncludingModuleMaps = [&](FileID FID, FileEntryRef F) {
180 if (!ModuleMaps.insert(F).second)
181 return;
182 SourceLocation Loc = SourceMgr.getIncludeLoc(FID);
183 // The include location of inferred module maps can point into the header
184 // file that triggered the inferring. Cut off the walk if that's the case.
185 while (Loc.isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
186 FID = SourceMgr.getFileID(Loc);
187 F = *SourceMgr.getFileEntryRefForID(FID);
188 if (!ModuleMaps.insert(F).second)
189 break;
190 Loc = SourceMgr.getIncludeLoc(FID);
191 }
192 };
193
194 std::set<const Module *> ProcessedModules;
195 auto CollectIncludingMapsFromAncestors = [&](const Module *M) {
196 for (const Module *Mod = M; Mod; Mod = Mod->Parent) {
197 if (!ProcessedModules.insert(Mod).second)
198 break;
199 // The containing module map is affecting, because it's being pointed
200 // into by Module::DefinitionLoc.
201 if (FileID FID = MM.getContainingModuleMapFileID(Mod); FID.isValid())
202 CollectIncludingModuleMaps(FID, *SourceMgr.getFileEntryRefForID(FID));
203 // For inferred modules, the module map that allowed inferring is not in
204 // the include chain of the virtual containing module map file. It did
205 // affect the compilation, though.
206 if (FileID FID = MM.getModuleMapFileIDForUniquing(Mod); FID.isValid())
207 CollectIncludingModuleMaps(FID, *SourceMgr.getFileEntryRefForID(FID));
208 }
209 };
210
211 // Handle all the affecting modules referenced from the root module.
212
213 std::queue<const Module *> Q;
214 Q.push(RootModule);
215 while (!Q.empty()) {
216 const Module *CurrentModule = Q.front();
217 Q.pop();
218
219 CollectIncludingMapsFromAncestors(CurrentModule);
220 for (const Module *ImportedModule : CurrentModule->Imports)
221 CollectIncludingMapsFromAncestors(ImportedModule);
222 for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses)
223 CollectIncludingMapsFromAncestors(UndeclaredModule);
224
225 for (auto *M : CurrentModule->submodules())
226 Q.push(M);
227 }
228
229 // Handle textually-included headers that belong to other modules.
230
232 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
233
234 if (FilesByUID.size() > HS.header_file_size())
235 FilesByUID.resize(HS.header_file_size());
236
237 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
238 OptionalFileEntryRef File = FilesByUID[UID];
239 if (!File)
240 continue;
241
243 if (!HFI)
244 continue; // We have no information on this being a header file.
245 if (!HFI->isCompilingModuleHeader && HFI->isModuleHeader)
246 continue; // Modular header, handled in the above module-based loop.
248 continue; // Non-modular header not included locally is not affecting.
249
250 for (const auto &KH : HS.findResolvedModulesForHeader(*File))
251 if (const Module *M = KH.getModule())
252 CollectIncludingMapsFromAncestors(M);
253 }
254
255 return ModuleMaps;
256}
257
258class ASTTypeWriter {
259 ASTWriter &Writer;
261 ASTRecordWriter BasicWriter;
262
263public:
264 ASTTypeWriter(ASTWriter &Writer)
265 : Writer(Writer), BasicWriter(Writer, Record) {}
266
267 uint64_t write(QualType T) {
268 if (T.hasLocalNonFastQualifiers()) {
269 Qualifiers Qs = T.getLocalQualifiers();
270 BasicWriter.writeQualType(T.getLocalUnqualifiedType());
271 BasicWriter.writeQualifiers(Qs);
272 return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
273 }
274
275 const Type *typePtr = T.getTypePtr();
277 atw.write(typePtr);
278 return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
279 /*abbrev*/ 0);
280 }
281};
282
283class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
284 using LocSeq = SourceLocationSequence;
285
287 LocSeq *Seq;
288
289 void addSourceLocation(SourceLocation Loc) {
290 Record.AddSourceLocation(Loc, Seq);
291 }
292 void addSourceRange(SourceRange Range) { Record.AddSourceRange(Range, Seq); }
293
294public:
295 TypeLocWriter(ASTRecordWriter &Record, LocSeq *Seq)
296 : Record(Record), Seq(Seq) {}
297
298#define ABSTRACT_TYPELOC(CLASS, PARENT)
299#define TYPELOC(CLASS, PARENT) \
300 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
301#include "clang/AST/TypeLocNodes.def"
302
303 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
304 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
305};
306
307} // namespace
308
309void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
310 // nothing to do
311}
312
313void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
314 addSourceLocation(TL.getBuiltinLoc());
315 if (TL.needsExtraLocalData()) {
316 Record.push_back(TL.getWrittenTypeSpec());
317 Record.push_back(static_cast<uint64_t>(TL.getWrittenSignSpec()));
318 Record.push_back(static_cast<uint64_t>(TL.getWrittenWidthSpec()));
319 Record.push_back(TL.hasModeAttr());
320 }
321}
322
323void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
324 addSourceLocation(TL.getNameLoc());
325}
326
327void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
328 addSourceLocation(TL.getStarLoc());
329}
330
331void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
332 // nothing to do
333}
334
335void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
336 // nothing to do
337}
338
339void TypeLocWriter::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
340 // nothing to do
341}
342
343void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
344 addSourceLocation(TL.getCaretLoc());
345}
346
347void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
348 addSourceLocation(TL.getAmpLoc());
349}
350
351void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
352 addSourceLocation(TL.getAmpAmpLoc());
353}
354
355void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
356 addSourceLocation(TL.getStarLoc());
357 Record.AddTypeSourceInfo(TL.getClassTInfo());
358}
359
360void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
361 addSourceLocation(TL.getLBracketLoc());
362 addSourceLocation(TL.getRBracketLoc());
363 Record.push_back(TL.getSizeExpr() ? 1 : 0);
364 if (TL.getSizeExpr())
365 Record.AddStmt(TL.getSizeExpr());
366}
367
368void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
369 VisitArrayTypeLoc(TL);
370}
371
372void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
373 VisitArrayTypeLoc(TL);
374}
375
376void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
377 VisitArrayTypeLoc(TL);
378}
379
380void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
382 VisitArrayTypeLoc(TL);
383}
384
385void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
387 addSourceLocation(TL.getAttrNameLoc());
389 addSourceLocation(range.getBegin());
390 addSourceLocation(range.getEnd());
391 Record.AddStmt(TL.getAttrExprOperand());
392}
393
394void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
396 addSourceLocation(TL.getNameLoc());
397}
398
399void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
400 addSourceLocation(TL.getNameLoc());
401}
402
403void TypeLocWriter::VisitDependentVectorTypeLoc(
405 addSourceLocation(TL.getNameLoc());
406}
407
408void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
409 addSourceLocation(TL.getNameLoc());
410}
411
412void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
413 addSourceLocation(TL.getAttrNameLoc());
415 addSourceLocation(range.getBegin());
416 addSourceLocation(range.getEnd());
417 Record.AddStmt(TL.getAttrRowOperand());
418 Record.AddStmt(TL.getAttrColumnOperand());
419}
420
421void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
423 addSourceLocation(TL.getAttrNameLoc());
425 addSourceLocation(range.getBegin());
426 addSourceLocation(range.getEnd());
427 Record.AddStmt(TL.getAttrRowOperand());
428 Record.AddStmt(TL.getAttrColumnOperand());
429}
430
431void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
432 addSourceLocation(TL.getLocalRangeBegin());
433 addSourceLocation(TL.getLParenLoc());
434 addSourceLocation(TL.getRParenLoc());
435 addSourceRange(TL.getExceptionSpecRange());
436 addSourceLocation(TL.getLocalRangeEnd());
437 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
438 Record.AddDeclRef(TL.getParam(i));
439}
440
441void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
442 VisitFunctionTypeLoc(TL);
443}
444
445void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
446 VisitFunctionTypeLoc(TL);
447}
448
449void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
450 addSourceLocation(TL.getNameLoc());
451}
452
453void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) {
454 addSourceLocation(TL.getNameLoc());
455}
456
457void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
458 addSourceLocation(TL.getNameLoc());
459}
460
461void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
462 if (TL.getNumProtocols()) {
463 addSourceLocation(TL.getProtocolLAngleLoc());
464 addSourceLocation(TL.getProtocolRAngleLoc());
465 }
466 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
467 addSourceLocation(TL.getProtocolLoc(i));
468}
469
470void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
471 addSourceLocation(TL.getTypeofLoc());
472 addSourceLocation(TL.getLParenLoc());
473 addSourceLocation(TL.getRParenLoc());
474}
475
476void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
477 addSourceLocation(TL.getTypeofLoc());
478 addSourceLocation(TL.getLParenLoc());
479 addSourceLocation(TL.getRParenLoc());
480 Record.AddTypeSourceInfo(TL.getUnmodifiedTInfo());
481}
482
483void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
484 addSourceLocation(TL.getDecltypeLoc());
485 addSourceLocation(TL.getRParenLoc());
486}
487
488void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
489 addSourceLocation(TL.getKWLoc());
490 addSourceLocation(TL.getLParenLoc());
491 addSourceLocation(TL.getRParenLoc());
492 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
493}
494
496 assert(CR);
502 push_back(CR->getTemplateArgsAsWritten() != nullptr);
503 if (CR->getTemplateArgsAsWritten())
505}
506
507void TypeLocWriter::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
508 addSourceLocation(TL.getEllipsisLoc());
509}
510
511void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
512 addSourceLocation(TL.getNameLoc());
513 auto *CR = TL.getConceptReference();
514 Record.push_back(TL.isConstrained() && CR);
515 if (TL.isConstrained() && CR)
516 Record.AddConceptReference(CR);
517 Record.push_back(TL.isDecltypeAuto());
518 if (TL.isDecltypeAuto())
519 addSourceLocation(TL.getRParenLoc());
520}
521
522void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
524 addSourceLocation(TL.getTemplateNameLoc());
525}
526
527void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
528 addSourceLocation(TL.getNameLoc());
529}
530
531void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
532 addSourceLocation(TL.getNameLoc());
533}
534
535void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
536 Record.AddAttr(TL.getAttr());
537}
538
539void TypeLocWriter::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
540 // Nothing to do
541}
542
543void TypeLocWriter::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
544 // Nothing to do.
545}
546
547void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
548 addSourceLocation(TL.getNameLoc());
549}
550
551void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
553 addSourceLocation(TL.getNameLoc());
554}
555
556void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
558 addSourceLocation(TL.getNameLoc());
559}
560
561void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
563 addSourceLocation(TL.getTemplateKeywordLoc());
564 addSourceLocation(TL.getTemplateNameLoc());
565 addSourceLocation(TL.getLAngleLoc());
566 addSourceLocation(TL.getRAngleLoc());
567 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
568 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
569 TL.getArgLoc(i).getLocInfo());
570}
571
572void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
573 addSourceLocation(TL.getLParenLoc());
574 addSourceLocation(TL.getRParenLoc());
575}
576
577void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
578 addSourceLocation(TL.getExpansionLoc());
579}
580
581void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
582 addSourceLocation(TL.getElaboratedKeywordLoc());
583 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
584}
585
586void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
587 addSourceLocation(TL.getNameLoc());
588}
589
590void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
591 addSourceLocation(TL.getElaboratedKeywordLoc());
592 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
593 addSourceLocation(TL.getNameLoc());
594}
595
596void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
598 addSourceLocation(TL.getElaboratedKeywordLoc());
599 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
600 addSourceLocation(TL.getTemplateKeywordLoc());
601 addSourceLocation(TL.getTemplateNameLoc());
602 addSourceLocation(TL.getLAngleLoc());
603 addSourceLocation(TL.getRAngleLoc());
604 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
605 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
606 TL.getArgLoc(I).getLocInfo());
607}
608
609void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
610 addSourceLocation(TL.getEllipsisLoc());
611}
612
613void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
614 addSourceLocation(TL.getNameLoc());
615 addSourceLocation(TL.getNameEndLoc());
616}
617
618void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
619 Record.push_back(TL.hasBaseTypeAsWritten());
620 addSourceLocation(TL.getTypeArgsLAngleLoc());
621 addSourceLocation(TL.getTypeArgsRAngleLoc());
622 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
623 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
624 addSourceLocation(TL.getProtocolLAngleLoc());
625 addSourceLocation(TL.getProtocolRAngleLoc());
626 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
627 addSourceLocation(TL.getProtocolLoc(i));
628}
629
630void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
631 addSourceLocation(TL.getStarLoc());
632}
633
634void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
635 addSourceLocation(TL.getKWLoc());
636 addSourceLocation(TL.getLParenLoc());
637 addSourceLocation(TL.getRParenLoc());
638}
639
640void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
641 addSourceLocation(TL.getKWLoc());
642}
643
644void TypeLocWriter::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
645 addSourceLocation(TL.getNameLoc());
646}
647void TypeLocWriter::VisitDependentBitIntTypeLoc(
649 addSourceLocation(TL.getNameLoc());
650}
651
652void ASTWriter::WriteTypeAbbrevs() {
653 using namespace llvm;
654
655 std::shared_ptr<BitCodeAbbrev> Abv;
656
657 // Abbreviation for TYPE_EXT_QUAL
658 Abv = std::make_shared<BitCodeAbbrev>();
659 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
660 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
661 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
662 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
663}
664
665//===----------------------------------------------------------------------===//
666// ASTWriter Implementation
667//===----------------------------------------------------------------------===//
668
669static void EmitBlockID(unsigned ID, const char *Name,
670 llvm::BitstreamWriter &Stream,
672 Record.clear();
673 Record.push_back(ID);
674 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
675
676 // Emit the block name if present.
677 if (!Name || Name[0] == 0)
678 return;
679 Record.clear();
680 while (*Name)
681 Record.push_back(*Name++);
682 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
683}
684
685static void EmitRecordID(unsigned ID, const char *Name,
686 llvm::BitstreamWriter &Stream,
688 Record.clear();
689 Record.push_back(ID);
690 while (*Name)
691 Record.push_back(*Name++);
692 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
693}
694
695static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
697#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
826#undef RECORD
827}
828
829void ASTWriter::WriteBlockInfoBlock() {
831 Stream.EnterBlockInfoBlock();
832
833#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
834#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
835
836 // Control Block.
837 BLOCK(CONTROL_BLOCK);
846
847 BLOCK(OPTIONS_BLOCK);
853
854 BLOCK(INPUT_FILES_BLOCK);
857
858 // AST Top-Level Block.
859 BLOCK(AST_BLOCK);
914
915 // SourceManager Block.
916 BLOCK(SOURCE_MANAGER_BLOCK);
922
923 // Preprocessor Block.
924 BLOCK(PREPROCESSOR_BLOCK);
930
931 // Submodule Block.
932 BLOCK(SUBMODULE_BLOCK);
952
953 // Comments Block.
954 BLOCK(COMMENTS_BLOCK);
956
957 // Decls and Types block.
958 BLOCK(DECLTYPES_BLOCK);
960 RECORD(TYPE_COMPLEX);
961 RECORD(TYPE_POINTER);
962 RECORD(TYPE_BLOCK_POINTER);
963 RECORD(TYPE_LVALUE_REFERENCE);
964 RECORD(TYPE_RVALUE_REFERENCE);
965 RECORD(TYPE_MEMBER_POINTER);
966 RECORD(TYPE_CONSTANT_ARRAY);
967 RECORD(TYPE_INCOMPLETE_ARRAY);
968 RECORD(TYPE_VARIABLE_ARRAY);
969 RECORD(TYPE_VECTOR);
970 RECORD(TYPE_EXT_VECTOR);
971 RECORD(TYPE_FUNCTION_NO_PROTO);
972 RECORD(TYPE_FUNCTION_PROTO);
973 RECORD(TYPE_TYPEDEF);
974 RECORD(TYPE_TYPEOF_EXPR);
975 RECORD(TYPE_TYPEOF);
976 RECORD(TYPE_RECORD);
977 RECORD(TYPE_ENUM);
978 RECORD(TYPE_OBJC_INTERFACE);
979 RECORD(TYPE_OBJC_OBJECT_POINTER);
980 RECORD(TYPE_DECLTYPE);
981 RECORD(TYPE_ELABORATED);
982 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
983 RECORD(TYPE_UNRESOLVED_USING);
984 RECORD(TYPE_INJECTED_CLASS_NAME);
985 RECORD(TYPE_OBJC_OBJECT);
986 RECORD(TYPE_TEMPLATE_TYPE_PARM);
987 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
988 RECORD(TYPE_DEPENDENT_NAME);
989 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
990 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
991 RECORD(TYPE_PAREN);
992 RECORD(TYPE_MACRO_QUALIFIED);
993 RECORD(TYPE_PACK_EXPANSION);
994 RECORD(TYPE_ATTRIBUTED);
995 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
996 RECORD(TYPE_AUTO);
997 RECORD(TYPE_UNARY_TRANSFORM);
998 RECORD(TYPE_ATOMIC);
999 RECORD(TYPE_DECAYED);
1000 RECORD(TYPE_ADJUSTED);
1001 RECORD(TYPE_OBJC_TYPE_PARAM);
1074
1075 // Statements and Exprs can occur in the Decls and Types block.
1076 AddStmtsExprs(Stream, Record);
1077
1078 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1082
1083 // Decls and Types block.
1084 BLOCK(EXTENSION_BLOCK);
1086
1087 BLOCK(UNHASHED_CONTROL_BLOCK);
1093
1094#undef RECORD
1095#undef BLOCK
1096 Stream.ExitBlock();
1097}
1098
1099/// Prepares a path for being written to an AST file by converting it
1100/// to an absolute path and removing nested './'s.
1101///
1102/// \return \c true if the path was changed.
1103static bool cleanPathForOutput(FileManager &FileMgr,
1104 SmallVectorImpl<char> &Path) {
1105 bool Changed = FileMgr.makeAbsolutePath(Path);
1106 return Changed | llvm::sys::path::remove_dots(Path);
1107}
1108
1109/// Adjusts the given filename to only write out the portion of the
1110/// filename that is not part of the system root directory.
1111///
1112/// \param Filename the file name to adjust.
1113///
1114/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1115/// the returned filename will be adjusted by this root directory.
1116///
1117/// \returns either the original filename (if it needs no adjustment) or the
1118/// adjusted filename (which points into the @p Filename parameter).
1119static const char *
1120adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1121 assert(Filename && "No file name to adjust?");
1122
1123 if (BaseDir.empty())
1124 return Filename;
1125
1126 // Verify that the filename and the system root have the same prefix.
1127 unsigned Pos = 0;
1128 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1129 if (Filename[Pos] != BaseDir[Pos])
1130 return Filename; // Prefixes don't match.
1131
1132 // We hit the end of the filename before we hit the end of the system root.
1133 if (!Filename[Pos])
1134 return Filename;
1135
1136 // If there's not a path separator at the end of the base directory nor
1137 // immediately after it, then this isn't within the base directory.
1138 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1139 if (!llvm::sys::path::is_separator(BaseDir.back()))
1140 return Filename;
1141 } else {
1142 // If the file name has a '/' at the current position, skip over the '/'.
1143 // We distinguish relative paths from absolute paths by the
1144 // absence of '/' at the beginning of relative paths.
1145 //
1146 // FIXME: This is wrong. We distinguish them by asking if the path is
1147 // absolute, which isn't the same thing. And there might be multiple '/'s
1148 // in a row. Use a better mechanism to indicate whether we have emitted an
1149 // absolute or relative path.
1150 ++Pos;
1151 }
1152
1153 return Filename + Pos;
1154}
1155
1156std::pair<ASTFileSignature, ASTFileSignature>
1157ASTWriter::createSignature() const {
1158 StringRef AllBytes(Buffer.data(), Buffer.size());
1159
1160 llvm::SHA1 Hasher;
1161 Hasher.update(AllBytes.slice(ASTBlockRange.first, ASTBlockRange.second));
1162 ASTFileSignature ASTBlockHash = ASTFileSignature::create(Hasher.result());
1163
1164 // Add the remaining bytes:
1165 // 1. Before the unhashed control block.
1166 Hasher.update(AllBytes.slice(0, UnhashedControlBlockRange.first));
1167 // 2. Between the unhashed control block and the AST block.
1168 Hasher.update(
1169 AllBytes.slice(UnhashedControlBlockRange.second, ASTBlockRange.first));
1170 // 3. After the AST block.
1171 Hasher.update(AllBytes.slice(ASTBlockRange.second, StringRef::npos));
1172 ASTFileSignature Signature = ASTFileSignature::create(Hasher.result());
1173
1174 return std::make_pair(ASTBlockHash, Signature);
1175}
1176
1177ASTFileSignature ASTWriter::backpatchSignature() {
1178 if (!WritingModule ||
1180 return {};
1181
1182 // For implicit modules, write the hash of the PCM as its signature.
1183
1184 auto BackpatchSignatureAt = [&](const ASTFileSignature &S, uint64_t BitNo) {
1185 for (uint8_t Byte : S) {
1186 Stream.BackpatchByte(BitNo, Byte);
1187 BitNo += 8;
1188 }
1189 };
1190
1191 ASTFileSignature ASTBlockHash;
1192 ASTFileSignature Signature;
1193 std::tie(ASTBlockHash, Signature) = createSignature();
1194
1195 BackpatchSignatureAt(ASTBlockHash, ASTBlockHashOffset);
1196 BackpatchSignatureAt(Signature, SignatureOffset);
1197
1198 return Signature;
1199}
1200
1201void ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1202 ASTContext &Context) {
1203 using namespace llvm;
1204
1205 // Flush first to prepare the PCM hash (signature).
1206 Stream.FlushToWord();
1207 UnhashedControlBlockRange.first = Stream.GetCurrentBitNo() >> 3;
1208
1209 // Enter the block and prepare to write records.
1211 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1212
1213 // For implicit modules, write the hash of the PCM as its signature.
1214 if (WritingModule &&
1216 // At this point, we don't know the actual signature of the file or the AST
1217 // block - we're only able to compute those at the end of the serialization
1218 // process. Let's store dummy signatures for now, and replace them with the
1219 // real ones later on.
1220 // The bitstream VBR-encodes record elements, which makes backpatching them
1221 // really difficult. Let's store the signatures as blobs instead - they are
1222 // guaranteed to be word-aligned, and we control their format/encoding.
1223 auto Dummy = ASTFileSignature::createDummy();
1224 SmallString<128> Blob{Dummy.begin(), Dummy.end()};
1225
1226 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1227 Abbrev->Add(BitCodeAbbrevOp(AST_BLOCK_HASH));
1228 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1229 unsigned ASTBlockHashAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1230
1231 Abbrev = std::make_shared<BitCodeAbbrev>();
1232 Abbrev->Add(BitCodeAbbrevOp(SIGNATURE));
1233 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1234 unsigned SignatureAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1235
1236 Record.push_back(AST_BLOCK_HASH);
1237 Stream.EmitRecordWithBlob(ASTBlockHashAbbrev, Record, Blob);
1238 ASTBlockHashOffset = Stream.GetCurrentBitNo() - Blob.size() * 8;
1239 Record.clear();
1240
1241 Record.push_back(SIGNATURE);
1242 Stream.EmitRecordWithBlob(SignatureAbbrev, Record, Blob);
1243 SignatureOffset = Stream.GetCurrentBitNo() - Blob.size() * 8;
1244 Record.clear();
1245 }
1246
1247 const auto &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1248
1249 // Diagnostic options.
1250 const auto &Diags = Context.getDiagnostics();
1251 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1252 if (!HSOpts.ModulesSkipDiagnosticOptions) {
1253#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1254#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1255 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1256#include "clang/Basic/DiagnosticOptions.def"
1257 Record.push_back(DiagOpts.Warnings.size());
1258 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1259 AddString(DiagOpts.Warnings[I], Record);
1260 Record.push_back(DiagOpts.Remarks.size());
1261 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1262 AddString(DiagOpts.Remarks[I], Record);
1263 // Note: we don't serialize the log or serialization file names, because
1264 // they are generally transient files and will almost always be overridden.
1265 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1266 Record.clear();
1267 }
1268
1269 // Header search paths.
1270 if (!HSOpts.ModulesSkipHeaderSearchPaths) {
1271 // Include entries.
1272 Record.push_back(HSOpts.UserEntries.size());
1273 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1274 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1275 AddString(Entry.Path, Record);
1276 Record.push_back(static_cast<unsigned>(Entry.Group));
1277 Record.push_back(Entry.IsFramework);
1278 Record.push_back(Entry.IgnoreSysRoot);
1279 }
1280
1281 // System header prefixes.
1282 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1283 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1284 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1285 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1286 }
1287
1288 // VFS overlay files.
1289 Record.push_back(HSOpts.VFSOverlayFiles.size());
1290 for (StringRef VFSOverlayFile : HSOpts.VFSOverlayFiles)
1291 AddString(VFSOverlayFile, Record);
1292
1293 Stream.EmitRecord(HEADER_SEARCH_PATHS, Record);
1294 }
1295
1296 if (!HSOpts.ModulesSkipPragmaDiagnosticMappings)
1297 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
1298
1299 // Header search entry usage.
1300 {
1301 auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage();
1302 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1303 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_ENTRY_USAGE));
1304 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1305 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Bit vector.
1306 unsigned HSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1307 RecordData::value_type Record[] = {HEADER_SEARCH_ENTRY_USAGE,
1308 HSEntryUsage.size()};
1309 Stream.EmitRecordWithBlob(HSUsageAbbrevCode, Record, bytes(HSEntryUsage));
1310 }
1311
1312 // VFS usage.
1313 {
1314 auto VFSUsage = PP.getHeaderSearchInfo().collectVFSUsageAndClear();
1315 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1316 Abbrev->Add(BitCodeAbbrevOp(VFS_USAGE));
1317 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1318 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Bit vector.
1319 unsigned VFSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1320 RecordData::value_type Record[] = {VFS_USAGE, VFSUsage.size()};
1321 Stream.EmitRecordWithBlob(VFSUsageAbbrevCode, Record, bytes(VFSUsage));
1322 }
1323
1324 // Leave the options block.
1325 Stream.ExitBlock();
1326 UnhashedControlBlockRange.second = Stream.GetCurrentBitNo() >> 3;
1327}
1328
1329/// Write the control block.
1330void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1331 StringRef isysroot) {
1332 using namespace llvm;
1333
1334 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1336
1337 // Metadata
1338 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1339 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1340 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1341 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1342 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1343 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1344 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1345 // Standard C++ module
1346 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1347 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1348 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1349 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1350 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1351 assert((!WritingModule || isysroot.empty()) &&
1352 "writing module as a relocatable PCH?");
1353 {
1354 RecordData::value_type Record[] = {METADATA,
1357 CLANG_VERSION_MAJOR,
1358 CLANG_VERSION_MINOR,
1359 !isysroot.empty(),
1361 IncludeTimestamps,
1362 ASTHasCompilerErrors};
1363 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1365 }
1366
1367 if (WritingModule) {
1368 // Module name
1369 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1370 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1371 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1372 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1373 RecordData::value_type Record[] = {MODULE_NAME};
1374 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1375 }
1376
1377 if (WritingModule && WritingModule->Directory) {
1378 SmallString<128> BaseDir;
1380 // Use the current working directory as the base path for all inputs.
1381 auto CWD =
1383 ".");
1384 BaseDir.assign(CWD->getName());
1385 } else {
1386 BaseDir.assign(WritingModule->Directory->getName());
1387 }
1389
1390 // If the home of the module is the current working directory, then we
1391 // want to pick up the cwd of the build process loading the module, not
1392 // our cwd, when we load this module.
1394 (!PP.getHeaderSearchInfo()
1397 WritingModule->Directory->getName() != StringRef("."))) {
1398 // Module directory.
1399 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1400 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1401 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1402 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1403
1404 RecordData::value_type Record[] = {MODULE_DIRECTORY};
1405 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1406 }
1407
1408 // Write out all other paths relative to the base directory if possible.
1409 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1410 } else if (!isysroot.empty()) {
1411 // Write out paths relative to the sysroot if possible.
1412 BaseDirectory = std::string(isysroot);
1413 }
1414
1415 // Module map file
1416 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1417 Record.clear();
1418
1419 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1420 AddPath(WritingModule->PresumedModuleMapFile.empty()
1421 ? Map.getModuleMapFileForUniquing(WritingModule)
1422 ->getNameAsRequested()
1423 : StringRef(WritingModule->PresumedModuleMapFile),
1424 Record);
1425
1426 // Additional module map files.
1427 if (auto *AdditionalModMaps =
1428 Map.getAdditionalModuleMapFiles(WritingModule)) {
1429 Record.push_back(AdditionalModMaps->size());
1430 SmallVector<FileEntryRef, 1> ModMaps(AdditionalModMaps->begin(),
1431 AdditionalModMaps->end());
1432 llvm::sort(ModMaps, [](FileEntryRef A, FileEntryRef B) {
1433 return A.getName() < B.getName();
1434 });
1435 for (FileEntryRef F : ModMaps)
1436 AddPath(F.getName(), Record);
1437 } else {
1438 Record.push_back(0);
1439 }
1440
1441 Stream.EmitRecord(MODULE_MAP_FILE, Record);
1442 }
1443
1444 // Imports
1445 if (Chain) {
1447 Record.clear();
1448
1449 for (ModuleFile &M : Mgr) {
1450 // Skip modules that weren't directly imported.
1451 if (!M.isDirectlyImported())
1452 continue;
1453
1454 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1455 Record.push_back(M.StandardCXXModule);
1456 AddSourceLocation(M.ImportLoc, Record);
1457
1458 // We don't want to hard code the information about imported modules
1459 // in the C++20 named modules.
1460 if (!M.StandardCXXModule) {
1461 // If we have calculated signature, there is no need to store
1462 // the size or timestamp.
1463 Record.push_back(M.Signature ? 0 : M.File.getSize());
1464 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1465 llvm::append_range(Record, M.Signature);
1466 }
1467
1468 AddString(M.ModuleName, Record);
1469
1470 if (!M.StandardCXXModule)
1471 AddPath(M.FileName, Record);
1472 }
1473 Stream.EmitRecord(IMPORTS, Record);
1474 }
1475
1476 // Write the options block.
1477 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1478
1479 // Language options.
1480 Record.clear();
1481 const LangOptions &LangOpts = Context.getLangOpts();
1482#define LANGOPT(Name, Bits, Default, Description) \
1483 Record.push_back(LangOpts.Name);
1484#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1485 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1486#include "clang/Basic/LangOptions.def"
1487#define SANITIZER(NAME, ID) \
1488 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1489#include "clang/Basic/Sanitizers.def"
1490
1491 Record.push_back(LangOpts.ModuleFeatures.size());
1492 for (StringRef Feature : LangOpts.ModuleFeatures)
1493 AddString(Feature, Record);
1494
1495 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1497
1498 AddString(LangOpts.CurrentModule, Record);
1499
1500 // Comment options.
1501 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1502 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1503 AddString(I, Record);
1504 }
1505 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1506
1507 // OpenMP offloading options.
1508 Record.push_back(LangOpts.OMPTargetTriples.size());
1509 for (auto &T : LangOpts.OMPTargetTriples)
1510 AddString(T.getTriple(), Record);
1511
1512 AddString(LangOpts.OMPHostIRFile, Record);
1513
1514 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1515
1516 // Target options.
1517 Record.clear();
1518 const TargetInfo &Target = Context.getTargetInfo();
1519 const TargetOptions &TargetOpts = Target.getTargetOpts();
1520 AddString(TargetOpts.Triple, Record);
1521 AddString(TargetOpts.CPU, Record);
1522 AddString(TargetOpts.TuneCPU, Record);
1523 AddString(TargetOpts.ABI, Record);
1524 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1525 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1526 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1527 }
1528 Record.push_back(TargetOpts.Features.size());
1529 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1530 AddString(TargetOpts.Features[I], Record);
1531 }
1532 Stream.EmitRecord(TARGET_OPTIONS, Record);
1533
1534 // File system options.
1535 Record.clear();
1536 const FileSystemOptions &FSOpts =
1538 AddString(FSOpts.WorkingDir, Record);
1539 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1540
1541 // Header search options.
1542 Record.clear();
1543 const HeaderSearchOptions &HSOpts =
1545
1546 AddString(HSOpts.Sysroot, Record);
1547 AddString(HSOpts.ResourceDir, Record);
1550 Record.push_back(HSOpts.DisableModuleHash);
1551 Record.push_back(HSOpts.ImplicitModuleMaps);
1552 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1553 Record.push_back(HSOpts.EnablePrebuiltImplicitModules);
1554 Record.push_back(HSOpts.UseBuiltinIncludes);
1555 Record.push_back(HSOpts.UseStandardSystemIncludes);
1556 Record.push_back(HSOpts.UseStandardCXXIncludes);
1557 Record.push_back(HSOpts.UseLibcxx);
1558 // Write out the specific module cache path that contains the module files.
1560 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1561
1562 // Preprocessor options.
1563 Record.clear();
1564 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1565
1566 // If we're building an implicit module with a context hash, the importer is
1567 // guaranteed to have the same macros defined on the command line. Skip
1568 // writing them.
1569 bool SkipMacros = BuildingImplicitModule && !HSOpts.DisableModuleHash;
1570 bool WriteMacros = !SkipMacros;
1571 Record.push_back(WriteMacros);
1572 if (WriteMacros) {
1573 // Macro definitions.
1574 Record.push_back(PPOpts.Macros.size());
1575 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1576 AddString(PPOpts.Macros[I].first, Record);
1577 Record.push_back(PPOpts.Macros[I].second);
1578 }
1579 }
1580
1581 // Includes
1582 Record.push_back(PPOpts.Includes.size());
1583 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1584 AddString(PPOpts.Includes[I], Record);
1585
1586 // Macro includes
1587 Record.push_back(PPOpts.MacroIncludes.size());
1588 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1589 AddString(PPOpts.MacroIncludes[I], Record);
1590
1591 Record.push_back(PPOpts.UsePredefines);
1592 // Detailed record is important since it is used for the module cache hash.
1593 Record.push_back(PPOpts.DetailedRecord);
1595 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1596 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1597
1598 // Leave the options block.
1599 Stream.ExitBlock();
1600
1601 // Original file name and file ID
1602 SourceManager &SM = Context.getSourceManager();
1603 if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID())) {
1604 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1605 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1606 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1607 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1608 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1609
1610 Record.clear();
1611 Record.push_back(ORIGINAL_FILE);
1612 AddFileID(SM.getMainFileID(), Record);
1613 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1614 }
1615
1616 Record.clear();
1617 AddFileID(SM.getMainFileID(), Record);
1618 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1619
1620 WriteInputFiles(Context.SourceMgr,
1622 Stream.ExitBlock();
1623}
1624
1625namespace {
1626
1627/// An input file.
1628struct InputFileEntry {
1630 bool IsSystemFile;
1631 bool IsTransient;
1632 bool BufferOverridden;
1633 bool IsTopLevel;
1634 bool IsModuleMap;
1635 uint32_t ContentHash[2];
1636
1637 InputFileEntry(FileEntryRef File) : File(File) {}
1638};
1639
1640} // namespace
1641
1642void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1643 HeaderSearchOptions &HSOpts) {
1644 using namespace llvm;
1645
1646 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1647
1648 // Create input-file abbreviation.
1649 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1650 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1651 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1652 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1653 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1654 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1655 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1656 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Top-level
1657 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1658 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Name as req. len
1659 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name as req. + name
1660 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1661
1662 // Create input file hash abbreviation.
1663 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1664 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1665 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1666 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1667 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1668
1669 uint64_t InputFilesOffsetBase = Stream.GetCurrentBitNo();
1670
1671 // Get all ContentCache objects for files.
1672 std::vector<InputFileEntry> UserFiles;
1673 std::vector<InputFileEntry> SystemFiles;
1674 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1675 // Get this source location entry.
1676 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1677 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1678
1679 // We only care about file entries that were not overridden.
1680 if (!SLoc->isFile())
1681 continue;
1682 const SrcMgr::FileInfo &File = SLoc->getFile();
1683 const SrcMgr::ContentCache *Cache = &File.getContentCache();
1684 if (!Cache->OrigEntry)
1685 continue;
1686
1687 // Do not emit input files that do not affect current module.
1688 if (!IsSLocAffecting[I])
1689 continue;
1690
1691 InputFileEntry Entry(*Cache->OrigEntry);
1692 Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
1693 Entry.IsTransient = Cache->IsTransient;
1694 Entry.BufferOverridden = Cache->BufferOverridden;
1695 Entry.IsTopLevel = File.getIncludeLoc().isInvalid();
1696 Entry.IsModuleMap = isModuleMap(File.getFileCharacteristic());
1697
1698 auto ContentHash = hash_code(-1);
1699 if (PP->getHeaderSearchInfo()
1702 auto MemBuff = Cache->getBufferIfLoaded();
1703 if (MemBuff)
1704 ContentHash = hash_value(MemBuff->getBuffer());
1705 else
1706 PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1707 << Entry.File.getName();
1708 }
1709 auto CH = llvm::APInt(64, ContentHash);
1710 Entry.ContentHash[0] =
1711 static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1712 Entry.ContentHash[1] =
1713 static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1714
1715 if (Entry.IsSystemFile)
1716 SystemFiles.push_back(Entry);
1717 else
1718 UserFiles.push_back(Entry);
1719 }
1720
1721 // User files go at the front, system files at the back.
1722 auto SortedFiles = llvm::concat<InputFileEntry>(std::move(UserFiles),
1723 std::move(SystemFiles));
1724
1725 unsigned UserFilesNum = 0;
1726 // Write out all of the input files.
1727 std::vector<uint64_t> InputFileOffsets;
1728 for (const auto &Entry : SortedFiles) {
1729 uint32_t &InputFileID = InputFileIDs[Entry.File];
1730 if (InputFileID != 0)
1731 continue; // already recorded this file.
1732
1733 // Record this entry's offset.
1734 InputFileOffsets.push_back(Stream.GetCurrentBitNo() - InputFilesOffsetBase);
1735
1736 InputFileID = InputFileOffsets.size();
1737
1738 if (!Entry.IsSystemFile)
1739 ++UserFilesNum;
1740
1741 // Emit size/modification time for this file.
1742 // And whether this file was overridden.
1743 {
1744 SmallString<128> NameAsRequested = Entry.File.getNameAsRequested();
1745 SmallString<128> Name = Entry.File.getName();
1746
1747 PreparePathForOutput(NameAsRequested);
1749
1750 if (Name == NameAsRequested)
1751 Name.clear();
1752
1753 RecordData::value_type Record[] = {
1754 INPUT_FILE,
1755 InputFileOffsets.size(),
1756 (uint64_t)Entry.File.getSize(),
1757 (uint64_t)getTimestampForOutput(Entry.File),
1758 Entry.BufferOverridden,
1759 Entry.IsTransient,
1760 Entry.IsTopLevel,
1761 Entry.IsModuleMap,
1762 NameAsRequested.size()};
1763
1764 Stream.EmitRecordWithBlob(IFAbbrevCode, Record,
1765 (NameAsRequested + Name).str());
1766 }
1767
1768 // Emit content hash for this file.
1769 {
1770 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1771 Entry.ContentHash[1]};
1772 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1773 }
1774 }
1775
1776 Stream.ExitBlock();
1777
1778 // Create input file offsets abbreviation.
1779 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1780 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1781 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1782 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1783 // input files
1784 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1785 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1786
1787 // Write input file offsets.
1788 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1789 InputFileOffsets.size(), UserFilesNum};
1790 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1791}
1792
1793//===----------------------------------------------------------------------===//
1794// Source Manager Serialization
1795//===----------------------------------------------------------------------===//
1796
1797/// Create an abbreviation for the SLocEntry that refers to a
1798/// file.
1799static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1800 using namespace llvm;
1801
1802 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1803 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1804 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1805 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1806 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1807 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1808 // FileEntry fields.
1809 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1810 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1811 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1812 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1813 return Stream.EmitAbbrev(std::move(Abbrev));
1814}
1815
1816/// Create an abbreviation for the SLocEntry that refers to a
1817/// buffer.
1818static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1819 using namespace llvm;
1820
1821 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1822 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1823 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1824 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1825 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1826 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1827 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1828 return Stream.EmitAbbrev(std::move(Abbrev));
1829}
1830
1831/// Create an abbreviation for the SLocEntry that refers to a
1832/// buffer's blob.
1833static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1834 bool Compressed) {
1835 using namespace llvm;
1836
1837 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1838 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1840 if (Compressed)
1841 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1842 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1843 return Stream.EmitAbbrev(std::move(Abbrev));
1844}
1845
1846/// Create an abbreviation for the SLocEntry that refers to a macro
1847/// expansion.
1848static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1849 using namespace llvm;
1850
1851 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1852 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1853 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1854 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1855 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Start location
1856 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // End location
1857 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
1858 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1859 return Stream.EmitAbbrev(std::move(Abbrev));
1860}
1861
1862/// Emit key length and data length as ULEB-encoded data, and return them as a
1863/// pair.
1864static std::pair<unsigned, unsigned>
1865emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out) {
1866 llvm::encodeULEB128(KeyLen, Out);
1867 llvm::encodeULEB128(DataLen, Out);
1868 return std::make_pair(KeyLen, DataLen);
1869}
1870
1871namespace {
1872
1873 // Trait used for the on-disk hash table of header search information.
1874 class HeaderFileInfoTrait {
1875 ASTWriter &Writer;
1876
1877 // Keep track of the framework names we've used during serialization.
1878 SmallString<128> FrameworkStringData;
1879 llvm::StringMap<unsigned> FrameworkNameOffset;
1880
1881 public:
1882 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1883
1884 struct key_type {
1885 StringRef Filename;
1886 off_t Size;
1887 time_t ModTime;
1888 };
1889 using key_type_ref = const key_type &;
1890
1891 using UnresolvedModule =
1892 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1893
1894 struct data_type {
1895 const HeaderFileInfo &HFI;
1896 bool AlreadyIncluded;
1898 UnresolvedModule Unresolved;
1899 };
1900 using data_type_ref = const data_type &;
1901
1902 using hash_value_type = unsigned;
1903 using offset_type = unsigned;
1904
1905 hash_value_type ComputeHash(key_type_ref key) {
1906 // The hash is based only on size/time of the file, so that the reader can
1907 // match even when symlinking or excess path elements ("foo/../", "../")
1908 // change the form of the name. However, complete path is still the key.
1909 return llvm::hash_combine(key.Size, key.ModTime);
1910 }
1911
1912 std::pair<unsigned, unsigned>
1913 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1914 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1915 unsigned DataLen = 1 + 4 + 4;
1916 for (auto ModInfo : Data.KnownHeaders)
1917 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1918 DataLen += 4;
1919 if (Data.Unresolved.getPointer())
1920 DataLen += 4;
1921 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
1922 }
1923
1924 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1925 using namespace llvm::support;
1926
1927 endian::Writer LE(Out, llvm::endianness::little);
1928 LE.write<uint64_t>(key.Size);
1929 KeyLen -= 8;
1930 LE.write<uint64_t>(key.ModTime);
1931 KeyLen -= 8;
1932 Out.write(key.Filename.data(), KeyLen);
1933 }
1934
1935 void EmitData(raw_ostream &Out, key_type_ref key,
1936 data_type_ref Data, unsigned DataLen) {
1937 using namespace llvm::support;
1938
1939 endian::Writer LE(Out, llvm::endianness::little);
1940 uint64_t Start = Out.tell(); (void)Start;
1941
1942 unsigned char Flags = (Data.AlreadyIncluded << 6)
1943 | (Data.HFI.isImport << 5)
1944 | (Writer.isWritingStdCXXNamedModules() ? 0 :
1945 Data.HFI.isPragmaOnce << 4)
1946 | (Data.HFI.DirInfo << 1)
1947 | Data.HFI.IndexHeaderMapHeader;
1948 LE.write<uint8_t>(Flags);
1949
1950 if (!Data.HFI.ControllingMacro)
1951 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
1952 else
1953 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1954
1955 unsigned Offset = 0;
1956 if (!Data.HFI.Framework.empty()) {
1957 // If this header refers into a framework, save the framework name.
1958 llvm::StringMap<unsigned>::iterator Pos
1959 = FrameworkNameOffset.find(Data.HFI.Framework);
1960 if (Pos == FrameworkNameOffset.end()) {
1961 Offset = FrameworkStringData.size() + 1;
1962 FrameworkStringData.append(Data.HFI.Framework);
1963 FrameworkStringData.push_back(0);
1964
1965 FrameworkNameOffset[Data.HFI.Framework] = Offset;
1966 } else
1967 Offset = Pos->second;
1968 }
1969 LE.write<uint32_t>(Offset);
1970
1971 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1972 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1973 uint32_t Value = (ModID << 3) | (unsigned)Role;
1974 assert((Value >> 3) == ModID && "overflow in header module info");
1975 LE.write<uint32_t>(Value);
1976 }
1977 };
1978
1979 for (auto ModInfo : Data.KnownHeaders)
1980 EmitModule(ModInfo.getModule(), ModInfo.getRole());
1981 if (Data.Unresolved.getPointer())
1982 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
1983
1984 assert(Out.tell() - Start == DataLen && "Wrong data length");
1985 }
1986
1987 const char *strings_begin() const { return FrameworkStringData.begin(); }
1988 const char *strings_end() const { return FrameworkStringData.end(); }
1989 };
1990
1991} // namespace
1992
1993/// Write the header search block for the list of files that
1994///
1995/// \param HS The header search structure to save.
1996void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1997 HeaderFileInfoTrait GeneratorTrait(*this);
1998 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1999 SmallVector<const char *, 4> SavedStrings;
2000 unsigned NumHeaderSearchEntries = 0;
2001
2002 // Find all unresolved headers for the current module. We generally will
2003 // have resolved them before we get here, but not necessarily: we might be
2004 // compiling a preprocessed module, where there is no requirement for the
2005 // original files to exist any more.
2006 const HeaderFileInfo Empty; // So we can take a reference.
2007 if (WritingModule) {
2008 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2009 while (!Worklist.empty()) {
2010 Module *M = Worklist.pop_back_val();
2011 // We don't care about headers in unimportable submodules.
2012 if (M->isUnimportable())
2013 continue;
2014
2015 // Map to disk files where possible, to pick up any missing stat
2016 // information. This also means we don't need to check the unresolved
2017 // headers list when emitting resolved headers in the first loop below.
2018 // FIXME: It'd be preferable to avoid doing this if we were given
2019 // sufficient stat information in the module map.
2020 HS.getModuleMap().resolveHeaderDirectives(M, /*File=*/std::nullopt);
2021
2022 // If the file didn't exist, we can still create a module if we were given
2023 // enough information in the module map.
2024 for (const auto &U : M->MissingHeaders) {
2025 // Check that we were given enough information to build a module
2026 // without this file existing on disk.
2027 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
2028 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2029 << WritingModule->getFullModuleName() << U.Size.has_value()
2030 << U.FileName;
2031 continue;
2032 }
2033
2034 // Form the effective relative pathname for the file.
2036 llvm::sys::path::append(Filename, U.FileName);
2038
2039 StringRef FilenameDup = strdup(Filename.c_str());
2040 SavedStrings.push_back(FilenameDup.data());
2041
2042 HeaderFileInfoTrait::key_type Key = {
2043 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0};
2044 HeaderFileInfoTrait::data_type Data = {
2045 Empty, false, {}, {M, ModuleMap::headerKindToRole(U.Kind)}};
2046 // FIXME: Deal with cases where there are multiple unresolved header
2047 // directives in different submodules for the same header.
2048 Generator.insert(Key, Data, GeneratorTrait);
2049 ++NumHeaderSearchEntries;
2050 }
2051 auto SubmodulesRange = M->submodules();
2052 Worklist.append(SubmodulesRange.begin(), SubmodulesRange.end());
2053 }
2054 }
2055
2057 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
2058
2059 if (FilesByUID.size() > HS.header_file_size())
2060 FilesByUID.resize(HS.header_file_size());
2061
2062 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
2063 OptionalFileEntryRef File = FilesByUID[UID];
2064 if (!File)
2065 continue;
2066
2068 if (!HFI)
2069 continue; // We have no information on this being a header file.
2070 if (!HFI->isCompilingModuleHeader && HFI->isModuleHeader)
2071 continue; // Header file info is tracked by the owning module file.
2072 if (!HFI->isCompilingModuleHeader && !PP->alreadyIncluded(*File))
2073 continue; // Non-modular header not included is not needed.
2074
2075 // Massage the file path into an appropriate form.
2076 StringRef Filename = File->getName();
2077 SmallString<128> FilenameTmp(Filename);
2078 if (PreparePathForOutput(FilenameTmp)) {
2079 // If we performed any translation on the file name at all, we need to
2080 // save this string, since the generator will refer to it later.
2081 Filename = StringRef(strdup(FilenameTmp.c_str()));
2082 SavedStrings.push_back(Filename.data());
2083 }
2084
2085 bool Included = PP->alreadyIncluded(*File);
2086
2087 HeaderFileInfoTrait::key_type Key = {
2089 };
2090 HeaderFileInfoTrait::data_type Data = {
2091 *HFI, Included, HS.getModuleMap().findResolvedModulesForHeader(*File), {}
2092 };
2093 Generator.insert(Key, Data, GeneratorTrait);
2094 ++NumHeaderSearchEntries;
2095 }
2096
2097 // Create the on-disk hash table in a buffer.
2098 SmallString<4096> TableData;
2099 uint32_t BucketOffset;
2100 {
2101 using namespace llvm::support;
2102
2103 llvm::raw_svector_ostream Out(TableData);
2104 // Make sure that no bucket is at offset 0
2105 endian::write<uint32_t>(Out, 0, llvm::endianness::little);
2106 BucketOffset = Generator.Emit(Out, GeneratorTrait);
2107 }
2108
2109 // Create a blob abbreviation
2110 using namespace llvm;
2111
2112 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2113 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2114 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2115 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2116 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2117 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2118 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2119
2120 // Write the header search table
2121 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2122 NumHeaderSearchEntries, TableData.size()};
2123 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
2124 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
2125
2126 // Free all of the strings we had to duplicate.
2127 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
2128 free(const_cast<char *>(SavedStrings[I]));
2129}
2130
2131static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2132 unsigned SLocBufferBlobCompressedAbbrv,
2133 unsigned SLocBufferBlobAbbrv) {
2134 using RecordDataType = ASTWriter::RecordData::value_type;
2135
2136 // Compress the buffer if possible. We expect that almost all PCM
2137 // consumers will not want its contents.
2138 SmallVector<uint8_t, 0> CompressedBuffer;
2139 if (llvm::compression::zstd::isAvailable()) {
2140 llvm::compression::zstd::compress(
2141 llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer, 9);
2142 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2143 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2144 llvm::toStringRef(CompressedBuffer));
2145 return;
2146 }
2147 if (llvm::compression::zlib::isAvailable()) {
2148 llvm::compression::zlib::compress(
2149 llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer);
2150 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2151 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2152 llvm::toStringRef(CompressedBuffer));
2153 return;
2154 }
2155
2156 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2157 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2158}
2159
2160/// Writes the block containing the serialized form of the
2161/// source manager.
2162///
2163/// TODO: We should probably use an on-disk hash table (stored in a
2164/// blob), indexed based on the file name, so that we only create
2165/// entries for files that we actually need. In the common case (no
2166/// errors), we probably won't have to create file entries for any of
2167/// the files in the AST.
2168void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2169 const Preprocessor &PP) {
2171
2172 // Enter the source manager block.
2173 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2174 const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo();
2175
2176 // Abbreviations for the various kinds of source-location entries.
2177 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2178 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2179 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2180 unsigned SLocBufferBlobCompressedAbbrv =
2181 CreateSLocBufferBlobAbbrev(Stream, true);
2182 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2183
2184 // Write out the source location entry table. We skip the first
2185 // entry, which is always the same dummy entry.
2186 std::vector<uint32_t> SLocEntryOffsets;
2187 uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
2188 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2189 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2190 I != N; ++I) {
2191 // Get this source location entry.
2192 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2193 FileID FID = FileID::get(I);
2194 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2195
2196 // Record the offset of this source-location entry.
2197 uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
2198 assert((Offset >> 32) == 0 && "SLocEntry offset too large");
2199
2200 // Figure out which record code to use.
2201 unsigned Code;
2202 if (SLoc->isFile()) {
2204 if (Cache->OrigEntry) {
2205 Code = SM_SLOC_FILE_ENTRY;
2206 } else
2207 Code = SM_SLOC_BUFFER_ENTRY;
2208 } else
2210 Record.clear();
2211 Record.push_back(Code);
2212
2213 if (SLoc->isFile()) {
2214 const SrcMgr::FileInfo &File = SLoc->getFile();
2215 const SrcMgr::ContentCache *Content = &File.getContentCache();
2216 // Do not emit files that were not listed as inputs.
2217 if (!IsSLocAffecting[I])
2218 continue;
2219 SLocEntryOffsets.push_back(Offset);
2220 // Starting offset of this entry within this module, so skip the dummy.
2221 Record.push_back(getAdjustedOffset(SLoc->getOffset()) - 2);
2222 AddSourceLocation(File.getIncludeLoc(), Record);
2223 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2224 Record.push_back(File.hasLineDirectives());
2225
2226 bool EmitBlob = false;
2227 if (Content->OrigEntry) {
2228 assert(Content->OrigEntry == Content->ContentsEntry &&
2229 "Writing to AST an overridden file is not supported");
2230
2231 // The source location entry is a file. Emit input file ID.
2232 assert(InputFileIDs[*Content->OrigEntry] != 0 && "Missed file entry");
2233 Record.push_back(InputFileIDs[*Content->OrigEntry]);
2234
2235 Record.push_back(getAdjustedNumCreatedFIDs(FID));
2236
2237 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2238 if (FDI != FileDeclIDs.end()) {
2239 Record.push_back(FDI->second->FirstDeclIndex);
2240 Record.push_back(FDI->second->DeclIDs.size());
2241 } else {
2242 Record.push_back(0);
2243 Record.push_back(0);
2244 }
2245
2246 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2247
2248 if (Content->BufferOverridden || Content->IsTransient)
2249 EmitBlob = true;
2250 } else {
2251 // The source location entry is a buffer. The blob associated
2252 // with this entry contains the contents of the buffer.
2253
2254 // We add one to the size so that we capture the trailing NULL
2255 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2256 // the reader side).
2257 std::optional<llvm::MemoryBufferRef> Buffer =
2258 Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2259 StringRef Name = Buffer ? Buffer->getBufferIdentifier() : "";
2260 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2261 StringRef(Name.data(), Name.size() + 1));
2262 EmitBlob = true;
2263 }
2264
2265 if (EmitBlob) {
2266 // Include the implicit terminating null character in the on-disk buffer
2267 // if we're writing it uncompressed.
2268 std::optional<llvm::MemoryBufferRef> Buffer =
2269 Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2270 if (!Buffer)
2271 Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", "");
2272 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2273 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2274 SLocBufferBlobAbbrv);
2275 }
2276 } else {
2277 // The source location entry is a macro expansion.
2278 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2279 SLocEntryOffsets.push_back(Offset);
2280 // Starting offset of this entry within this module, so skip the dummy.
2281 Record.push_back(getAdjustedOffset(SLoc->getOffset()) - 2);
2282 LocSeq::State Seq;
2286 ? SourceLocation()
2287 : Expansion.getExpansionLocEnd(),
2288 Record, Seq);
2289 Record.push_back(Expansion.isExpansionTokenRange());
2290
2291 // Compute the token length for this macro expansion.
2292 SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset();
2293 if (I + 1 != N)
2294 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2295 Record.push_back(getAdjustedOffset(NextOffset - SLoc->getOffset()) - 1);
2296 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2297 }
2298 }
2299
2300 Stream.ExitBlock();
2301
2302 if (SLocEntryOffsets.empty())
2303 return;
2304
2305 // Write the source-location offsets table into the AST block. This
2306 // table is used for lazily loading source-location information.
2307 using namespace llvm;
2308
2309 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2310 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2311 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2312 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2313 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2314 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2315 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2316 {
2317 RecordData::value_type Record[] = {
2318 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2319 getAdjustedOffset(SourceMgr.getNextLocalOffset()) - 1 /* skip dummy */,
2320 SLocEntryOffsetsBase - SourceManagerBlockOffset};
2321 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2322 bytes(SLocEntryOffsets));
2323 }
2324
2325 // Write the line table. It depends on remapping working, so it must come
2326 // after the source location offsets.
2327 if (SourceMgr.hasLineTable()) {
2328 LineTableInfo &LineTable = SourceMgr.getLineTable();
2329
2330 Record.clear();
2331
2332 // Emit the needed file names.
2333 llvm::DenseMap<int, int> FilenameMap;
2334 FilenameMap[-1] = -1; // For unspecified filenames.
2335 for (const auto &L : LineTable) {
2336 if (L.first.ID < 0)
2337 continue;
2338 for (auto &LE : L.second) {
2339 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2340 FilenameMap.size() - 1)).second)
2341 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2342 }
2343 }
2344 Record.push_back(0);
2345
2346 // Emit the line entries
2347 for (const auto &L : LineTable) {
2348 // Only emit entries for local files.
2349 if (L.first.ID < 0)
2350 continue;
2351
2352 AddFileID(L.first, Record);
2353
2354 // Emit the line entries
2355 Record.push_back(L.second.size());
2356 for (const auto &LE : L.second) {
2357 Record.push_back(LE.FileOffset);
2358 Record.push_back(LE.LineNo);
2359 Record.push_back(FilenameMap[LE.FilenameID]);
2360 Record.push_back((unsigned)LE.FileKind);
2361 Record.push_back(LE.IncludeOffset);
2362 }
2363 }
2364
2365 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2366 }
2367}
2368
2369//===----------------------------------------------------------------------===//
2370// Preprocessor Serialization
2371//===----------------------------------------------------------------------===//
2372
2373static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2374 const Preprocessor &PP) {
2375 if (MacroInfo *MI = MD->getMacroInfo())
2376 if (MI->isBuiltinMacro())
2377 return true;
2378
2379 if (IsModule) {
2380 SourceLocation Loc = MD->getLocation();
2381 if (Loc.isInvalid())
2382 return true;
2383 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2384 return true;
2385 }
2386
2387 return false;
2388}
2389
2390/// Writes the block containing the serialized form of the
2391/// preprocessor.
2392void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2393 uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2394
2396 if (PPRec)
2397 WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
2398
2400 RecordData ModuleMacroRecord;
2401
2402 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2403 if (PP.getCounterValue() != 0) {
2404 RecordData::value_type Record[] = {PP.getCounterValue()};
2405 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2406 }
2407
2408 // If we have a recorded #pragma assume_nonnull, remember it so it can be
2409 // replayed when the preamble terminates into the main file.
2410 SourceLocation AssumeNonNullLoc =
2412 if (AssumeNonNullLoc.isValid()) {
2413 assert(PP.isRecordingPreamble());
2414 AddSourceLocation(AssumeNonNullLoc, Record);
2415 Stream.EmitRecord(PP_ASSUME_NONNULL_LOC, Record);
2416 Record.clear();
2417 }
2418
2419 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2420 assert(!IsModule);
2421 auto SkipInfo = PP.getPreambleSkipInfo();
2422 if (SkipInfo) {
2423 Record.push_back(true);
2424 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2425 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2426 Record.push_back(SkipInfo->FoundNonSkipPortion);
2427 Record.push_back(SkipInfo->FoundElse);
2428 AddSourceLocation(SkipInfo->ElseLoc, Record);
2429 } else {
2430 Record.push_back(false);
2431 }
2432 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2433 AddSourceLocation(Cond.IfLoc, Record);
2434 Record.push_back(Cond.WasSkipping);
2435 Record.push_back(Cond.FoundNonSkip);
2436 Record.push_back(Cond.FoundElse);
2437 }
2438 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2439 Record.clear();
2440 }
2441
2442 // Enter the preprocessor block.
2443 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2444
2445 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2446 // FIXME: Include a location for the use, and say which one was used.
2447 if (PP.SawDateOrTime())
2448 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2449
2450 // Loop over all the macro directives that are live at the end of the file,
2451 // emitting each to the PP section.
2452
2453 // Construct the list of identifiers with macro directives that need to be
2454 // serialized.
2456 // It is meaningless to emit macros for named modules. It only wastes times
2457 // and spaces.
2459 for (auto &Id : PP.getIdentifierTable())
2460 if (Id.second->hadMacroDefinition() &&
2461 (!Id.second->isFromAST() ||
2462 Id.second->hasChangedSinceDeserialization()))
2463 MacroIdentifiers.push_back(Id.second);
2464 // Sort the set of macro definitions that need to be serialized by the
2465 // name of the macro, to provide a stable ordering.
2466 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
2467
2468 // Emit the macro directives as a list and associate the offset with the
2469 // identifier they belong to.
2470 for (const IdentifierInfo *Name : MacroIdentifiers) {
2472 uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2473 assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
2474
2475 // Write out any exported module macros.
2476 bool EmittedModuleMacros = false;
2477 // C+=20 Header Units are compiled module interfaces, but they preserve
2478 // macros that are live (i.e. have a defined value) at the end of the
2479 // compilation. So when writing a header unit, we preserve only the final
2480 // value of each macro (and discard any that are undefined). Header units
2481 // do not have sub-modules (although they might import other header units).
2482 // PCH files, conversely, retain the history of each macro's define/undef
2483 // and of leaf macros in sub modules.
2484 if (IsModule && WritingModule->isHeaderUnit()) {
2485 // This is for the main TU when it is a C++20 header unit.
2486 // We preserve the final state of defined macros, and we do not emit ones
2487 // that are undefined.
2488 if (!MD || shouldIgnoreMacro(MD, IsModule, PP) ||
2490 continue;
2492 Record.push_back(MD->getKind());
2493 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2494 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2495 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2496 Record.push_back(VisMD->isPublic());
2497 }
2498 ModuleMacroRecord.push_back(getSubmoduleID(WritingModule));
2499 ModuleMacroRecord.push_back(getMacroRef(MD->getMacroInfo(), Name));
2500 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2501 ModuleMacroRecord.clear();
2502 EmittedModuleMacros = true;
2503 } else {
2504 // Emit the macro directives in reverse source order.
2505 for (; MD; MD = MD->getPrevious()) {
2506 // Once we hit an ignored macro, we're done: the rest of the chain
2507 // will all be ignored macros.
2508 if (shouldIgnoreMacro(MD, IsModule, PP))
2509 break;
2511 Record.push_back(MD->getKind());
2512 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2513 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2514 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2515 Record.push_back(VisMD->isPublic());
2516 }
2517 }
2518
2519 // We write out exported module macros for PCH as well.
2520 auto Leafs = PP.getLeafModuleMacros(Name);
2521 SmallVector<ModuleMacro *, 8> Worklist(Leafs.begin(), Leafs.end());
2522 llvm::DenseMap<ModuleMacro *, unsigned> Visits;
2523 while (!Worklist.empty()) {
2524 auto *Macro = Worklist.pop_back_val();
2525
2526 // Emit a record indicating this submodule exports this macro.
2527 ModuleMacroRecord.push_back(getSubmoduleID(Macro->getOwningModule()));
2528 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2529 for (auto *M : Macro->overrides())
2530 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2531
2532 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2533 ModuleMacroRecord.clear();
2534
2535 // Enqueue overridden macros once we've visited all their ancestors.
2536 for (auto *M : Macro->overrides())
2537 if (++Visits[M] == M->getNumOverridingMacros())
2538 Worklist.push_back(M);
2539
2540 EmittedModuleMacros = true;
2541 }
2542 }
2543 if (Record.empty() && !EmittedModuleMacros)
2544 continue;
2545
2546 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2547 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2548 Record.clear();
2549 }
2550
2551 /// Offsets of each of the macros into the bitstream, indexed by
2552 /// the local macro ID
2553 ///
2554 /// For each identifier that is associated with a macro, this map
2555 /// provides the offset into the bitstream where that macro is
2556 /// defined.
2557 std::vector<uint32_t> MacroOffsets;
2558
2559 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2560 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2561 MacroInfo *MI = MacroInfosToEmit[I].MI;
2562 MacroID ID = MacroInfosToEmit[I].ID;
2563
2564 if (ID < FirstMacroID) {
2565 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2566 continue;
2567 }
2568
2569 // Record the local offset of this macro.
2570 unsigned Index = ID - FirstMacroID;
2571 if (Index >= MacroOffsets.size())
2572 MacroOffsets.resize(Index + 1);
2573
2574 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2575 assert((Offset >> 32) == 0 && "Macro offset too large");
2576 MacroOffsets[Index] = Offset;
2577
2578 AddIdentifierRef(Name, Record);
2581 Record.push_back(MI->isUsed());
2582 Record.push_back(MI->isUsedForHeaderGuard());
2583 Record.push_back(MI->getNumTokens());
2584 unsigned Code;
2585 if (MI->isObjectLike()) {
2586 Code = PP_MACRO_OBJECT_LIKE;
2587 } else {
2589
2590 Record.push_back(MI->isC99Varargs());
2591 Record.push_back(MI->isGNUVarargs());
2592 Record.push_back(MI->hasCommaPasting());
2593 Record.push_back(MI->getNumParams());
2594 for (const IdentifierInfo *Param : MI->params())
2595 AddIdentifierRef(Param, Record);
2596 }
2597
2598 // If we have a detailed preprocessing record, record the macro definition
2599 // ID that corresponds to this macro.
2600 if (PPRec)
2601 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2602
2603 Stream.EmitRecord(Code, Record);
2604 Record.clear();
2605
2606 // Emit the tokens array.
2607 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2608 // Note that we know that the preprocessor does not have any annotation
2609 // tokens in it because they are created by the parser, and thus can't
2610 // be in a macro definition.
2611 const Token &Tok = MI->getReplacementToken(TokNo);
2612 AddToken(Tok, Record);
2613 Stream.EmitRecord(PP_TOKEN, Record);
2614 Record.clear();
2615 }
2616 ++NumMacros;
2617 }
2618
2619 Stream.ExitBlock();
2620
2621 // Write the offsets table for macro IDs.
2622 using namespace llvm;
2623
2624 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2625 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2626 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2627 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2628 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2629 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2630
2631 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2632 {
2633 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2634 FirstMacroID - NUM_PREDEF_MACRO_IDS,
2635 MacroOffsetsBase - ASTBlockStartOffset};
2636 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2637 }
2638}
2639
2640void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2641 uint64_t MacroOffsetsBase) {
2642 if (PPRec.local_begin() == PPRec.local_end())
2643 return;
2644
2645 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2646
2647 // Enter the preprocessor block.
2648 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2649
2650 // If the preprocessor has a preprocessing record, emit it.
2651 unsigned NumPreprocessingRecords = 0;
2652 using namespace llvm;
2653
2654 // Set up the abbreviation for
2655 unsigned InclusionAbbrev = 0;
2656 {
2657 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2658 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2659 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2660 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2661 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2662 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2663 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2664 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2665 }
2666
2667 unsigned FirstPreprocessorEntityID
2668 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2670 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2673 EEnd = PPRec.local_end();
2674 E != EEnd;
2675 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2676 Record.clear();
2677
2678 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2679 assert((Offset >> 32) == 0 && "Preprocessed entity offset too large");
2680 PreprocessedEntityOffsets.push_back(
2681 PPEntityOffset(getAdjustedRange((*E)->getSourceRange()), Offset));
2682
2683 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2684 // Record this macro definition's ID.
2685 MacroDefinitions[MD] = NextPreprocessorEntityID;
2686
2687 AddIdentifierRef(MD->getName(), Record);
2688 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2689 continue;
2690 }
2691
2692 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2693 Record.push_back(ME->isBuiltinMacro());
2694 if (ME->isBuiltinMacro())
2695 AddIdentifierRef(ME->getName(), Record);
2696 else
2697 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2698 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2699 continue;
2700 }
2701
2702 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2704 Record.push_back(ID->getFileName().size());
2705 Record.push_back(ID->wasInQuotes());
2706 Record.push_back(static_cast<unsigned>(ID->getKind()));
2707 Record.push_back(ID->importedModule());
2708 SmallString<64> Buffer;
2709 Buffer += ID->getFileName();
2710 // Check that the FileEntry is not null because it was not resolved and
2711 // we create a PCH even with compiler errors.
2712 if (ID->getFile())
2713 Buffer += ID->getFile()->getName();
2714 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2715 continue;
2716 }
2717
2718 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2719 }
2720 Stream.ExitBlock();
2721
2722 // Write the offsets table for the preprocessing record.
2723 if (NumPreprocessingRecords > 0) {
2724 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2725
2726 // Write the offsets table for identifier IDs.
2727 using namespace llvm;
2728
2729 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2730 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2731 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2732 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2733 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2734
2735 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2736 FirstPreprocessorEntityID -
2738 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2739 bytes(PreprocessedEntityOffsets));
2740 }
2741
2742 // Write the skipped region table for the preprocessing record.
2743 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2744 if (SkippedRanges.size() > 0) {
2745 std::vector<PPSkippedRange> SerializedSkippedRanges;
2746 SerializedSkippedRanges.reserve(SkippedRanges.size());
2747 for (auto const& Range : SkippedRanges)
2748 SerializedSkippedRanges.emplace_back(Range);
2749
2750 using namespace llvm;
2751 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2752 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2753 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2754 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2755
2756 Record.clear();
2757 Record.push_back(PPD_SKIPPED_RANGES);
2758 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2759 bytes(SerializedSkippedRanges));
2760 }
2761}
2762
2764 if (!Mod)
2765 return 0;
2766
2767 auto Known = SubmoduleIDs.find(Mod);
2768 if (Known != SubmoduleIDs.end())
2769 return Known->second;
2770
2771 auto *Top = Mod->getTopLevelModule();
2772 if (Top != WritingModule &&
2773 (getLangOpts().CompilingPCH ||
2774 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2775 return 0;
2776
2777 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2778}
2779
2780unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2781 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2782 // FIXME: This can easily happen, if we have a reference to a submodule that
2783 // did not result in us loading a module file for that submodule. For
2784 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2785 // assert((ID || !Mod) &&
2786 // "asked for module ID for non-local, non-imported module");
2787 return ID;
2788}
2789
2790/// Compute the number of modules within the given tree (including the
2791/// given module).
2792static unsigned getNumberOfModules(Module *Mod) {
2793 unsigned ChildModules = 0;
2794 for (auto *Submodule : Mod->submodules())
2795 ChildModules += getNumberOfModules(Submodule);
2796
2797 return ChildModules + 1;
2798}
2799
2800void ASTWriter::WriteSubmodules(Module *WritingModule) {
2801 // Enter the submodule description block.
2802 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2803
2804 // Write the abbreviations needed for the submodules block.
2805 using namespace llvm;
2806
2807 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2808 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2809 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2810 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2811 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Kind
2812 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Definition location
2813 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2814 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2815 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2816 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2817 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2818 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2819 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2820 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2821 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2822 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NamedModuleHasN...
2823 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2824 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2825
2826 Abbrev = std::make_shared<BitCodeAbbrev>();
2827 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2828 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2829 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2830
2831 Abbrev = std::make_shared<BitCodeAbbrev>();
2832 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2833 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2834 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2835
2836 Abbrev = std::make_shared<BitCodeAbbrev>();
2837 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2838 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2839 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2840
2841 Abbrev = std::make_shared<BitCodeAbbrev>();
2842 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2843 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2844 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2845
2846 Abbrev = std::make_shared<BitCodeAbbrev>();
2847 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2848 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2849 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2850 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2851
2852 Abbrev = std::make_shared<BitCodeAbbrev>();
2853 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2854 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2855 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2856
2857 Abbrev = std::make_shared<BitCodeAbbrev>();
2858 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2859 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2860 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2861
2862 Abbrev = std::make_shared<BitCodeAbbrev>();
2863 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2864 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2865 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2866
2867 Abbrev = std::make_shared<BitCodeAbbrev>();
2868 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2869 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2870 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2871
2872 Abbrev = std::make_shared<BitCodeAbbrev>();
2873 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2874 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2875 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2876 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2877
2878 Abbrev = std::make_shared<BitCodeAbbrev>();
2879 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2880 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2881 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2882
2883 Abbrev = std::make_shared<BitCodeAbbrev>();
2884 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2885 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2886 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2887 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2888
2889 Abbrev = std::make_shared<BitCodeAbbrev>();
2890 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2891 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2892 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2893
2894 // Write the submodule metadata block.
2895 RecordData::value_type Record[] = {
2896 getNumberOfModules(WritingModule),
2897 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2898 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2899
2900 // Write all of the submodules.
2901 std::queue<Module *> Q;
2902 Q.push(WritingModule);
2903 while (!Q.empty()) {
2904 Module *Mod = Q.front();
2905 Q.pop();
2906 unsigned ID = getSubmoduleID(Mod);
2907
2908 uint64_t ParentID = 0;
2909 if (Mod->Parent) {
2910 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2911 ParentID = SubmoduleIDs[Mod->Parent];
2912 }
2913
2914 uint64_t DefinitionLoc =
2915 SourceLocationEncoding::encode(getAdjustedLocation(Mod->DefinitionLoc));
2916
2917 // Emit the definition of the block.
2918 {
2919 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2920 ID,
2921 ParentID,
2922 (RecordData::value_type)Mod->Kind,
2923 DefinitionLoc,
2924 Mod->IsFramework,
2925 Mod->IsExplicit,
2926 Mod->IsSystem,
2927 Mod->IsExternC,
2928 Mod->InferSubmodules,
2932 Mod->ModuleMapIsPrivate,
2933 Mod->NamedModuleHasInit};
2934 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2935 }
2936
2937 // Emit the requirements.
2938 for (const auto &R : Mod->Requirements) {
2939 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2940 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2941 }
2942
2943 // Emit the umbrella header, if there is one.
2944 if (std::optional<Module::Header> UmbrellaHeader =
2946 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2947 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2948 UmbrellaHeader->NameAsWritten);
2949 } else if (std::optional<Module::DirectoryName> UmbrellaDir =
2950 Mod->getUmbrellaDirAsWritten()) {
2951 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2952 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2953 UmbrellaDir->NameAsWritten);
2954 }
2955
2956 // Emit the headers.
2957 struct {
2958 unsigned RecordKind;
2959 unsigned Abbrev;
2960 Module::HeaderKind HeaderKind;
2961 } HeaderLists[] = {
2962 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2963 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2964 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2965 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2967 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2968 };
2969 for (auto &HL : HeaderLists) {
2970 RecordData::value_type Record[] = {HL.RecordKind};
2971 for (auto &H : Mod->Headers[HL.HeaderKind])
2972 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2973 }
2974
2975 // Emit the top headers.
2976 {
2977 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2978 for (FileEntryRef H : Mod->getTopHeaders(PP->getFileManager())) {
2979 SmallString<128> HeaderName(H.getName());
2980 PreparePathForOutput(HeaderName);
2981 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, HeaderName);
2982 }
2983 }
2984
2985 // Emit the imports.
2986 if (!Mod->Imports.empty()) {
2988 for (auto *I : Mod->Imports)
2989 Record.push_back(getSubmoduleID(I));
2990 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2991 }
2992
2993 // Emit the modules affecting compilation that were not imported.
2994 if (!Mod->AffectingClangModules.empty()) {
2996 for (auto *I : Mod->AffectingClangModules)
2997 Record.push_back(getSubmoduleID(I));
2998 Stream.EmitRecord(SUBMODULE_AFFECTING_MODULES, Record);
2999 }
3000
3001 // Emit the exports.
3002 if (!Mod->Exports.empty()) {
3004 for (const auto &E : Mod->Exports) {
3005 // FIXME: This may fail; we don't require that all exported modules
3006 // are local or imported.
3007 Record.push_back(getSubmoduleID(E.getPointer()));
3008 Record.push_back(E.getInt());
3009 }
3010 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
3011 }
3012
3013 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
3014 // Might be unnecessary as use declarations are only used to build the
3015 // module itself.
3016
3017 // TODO: Consider serializing undeclared uses of modules.
3018
3019 // Emit the link libraries.
3020 for (const auto &LL : Mod->LinkLibraries) {
3021 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
3022 LL.IsFramework};
3023 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
3024 }
3025
3026 // Emit the conflicts.
3027 for (const auto &C : Mod->Conflicts) {
3028 // FIXME: This may fail; we don't require that all conflicting modules
3029 // are local or imported.
3030 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
3031 getSubmoduleID(C.Other)};
3032 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
3033 }
3034
3035 // Emit the configuration macros.
3036 for (const auto &CM : Mod->ConfigMacros) {
3037 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
3038 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
3039 }
3040
3041 // Emit the reachable initializers.
3042 // The initializer may only be unreachable in reduced BMI.
3043 RecordData Inits;
3044 for (Decl *D : Context->getModuleInitializers(Mod))
3045 if (wasDeclEmitted(D))
3046 AddDeclRef(D, Inits);
3047 if (!Inits.empty())
3048 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
3049
3050 // Emit the name of the re-exported module, if any.
3051 if (!Mod->ExportAsModule.empty()) {
3052 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
3053 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
3054 }
3055
3056 // Queue up the submodules of this module.
3057 for (auto *M : Mod->submodules())
3058 Q.push(M);
3059 }
3060
3061 Stream.ExitBlock();
3062
3063 assert((NextSubmoduleID - FirstSubmoduleID ==
3064 getNumberOfModules(WritingModule)) &&
3065 "Wrong # of submodules; found a reference to a non-local, "
3066 "non-imported submodule?");
3067}
3068
3069void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3070 bool isModule) {
3071 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3072 DiagStateIDMap;
3073 unsigned CurrID = 0;
3075
3076 auto EncodeDiagStateFlags =
3077 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3078 unsigned Result = (unsigned)DS->ExtBehavior;
3079 for (unsigned Val :
3080 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3081 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3082 (unsigned)DS->SuppressSystemWarnings})
3083 Result = (Result << 1) | Val;
3084 return Result;
3085 };
3086
3087 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3088 Record.push_back(Flags);
3089
3090 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3091 bool IncludeNonPragmaStates) {
3092 // Ensure that the diagnostic state wasn't modified since it was created.
3093 // We will not correctly round-trip this information otherwise.
3094 assert(Flags == EncodeDiagStateFlags(State) &&
3095 "diag state flags vary in single AST file");
3096
3097 // If we ever serialize non-pragma mappings outside the initial state, the
3098 // code below will need to consider more than getDefaultMapping.
3099 assert(!IncludeNonPragmaStates ||
3100 State == Diag.DiagStatesByLoc.FirstDiagState);
3101
3102 unsigned &DiagStateID = DiagStateIDMap[State];
3103 Record.push_back(DiagStateID);
3104
3105 if (DiagStateID == 0) {
3106 DiagStateID = ++CurrID;
3108
3109 // Add a placeholder for the number of mappings.
3110 auto SizeIdx = Record.size();
3111 Record.emplace_back();
3112 for (const auto &I : *State) {
3113 // Maybe skip non-pragmas.
3114 if (!I.second.isPragma() && !IncludeNonPragmaStates)
3115 continue;
3116 // Skip default mappings. We have a mapping for every diagnostic ever
3117 // emitted, regardless of whether it was customized.
3118 if (!I.second.isPragma() &&
3119 I.second == DiagnosticIDs::getDefaultMapping(I.first))
3120 continue;
3121 Mappings.push_back(I);
3122 }
3123
3124 // Sort by diag::kind for deterministic output.
3125 llvm::sort(Mappings, [](const auto &LHS, const auto &RHS) {
3126 return LHS.first < RHS.first;
3127 });
3128
3129 for (const auto &I : Mappings) {
3130 Record.push_back(I.first);
3131 Record.push_back(I.second.serialize());
3132 }
3133 // Update the placeholder.
3134 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
3135 }
3136 };
3137
3138 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3139
3140 // Reserve a spot for the number of locations with state transitions.
3141 auto NumLocationsIdx = Record.size();
3142 Record.emplace_back();
3143
3144 // Emit the state transitions.
3145 unsigned NumLocations = 0;
3146 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3147 if (!FileIDAndFile.first.isValid() ||
3148 !FileIDAndFile.second.HasLocalTransitions)
3149 continue;
3150 ++NumLocations;
3151
3152 AddFileID(FileIDAndFile.first, Record);
3153
3154 Record.push_back(FileIDAndFile.second.StateTransitions.size());
3155 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3156 Record.push_back(getAdjustedOffset(StatePoint.Offset));
3157 AddDiagState(StatePoint.State, false);
3158 }
3159 }
3160
3161 // Backpatch the number of locations.
3162 Record[NumLocationsIdx] = NumLocations;
3163
3164 // Emit CurDiagStateLoc. Do it last in order to match source order.
3165 //
3166 // This also protects against a hypothetical corner case with simulating
3167 // -Werror settings for implicit modules in the ASTReader, where reading
3168 // CurDiagState out of context could change whether warning pragmas are
3169 // treated as errors.
3170 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3171 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3172
3173 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3174}
3175
3176//===----------------------------------------------------------------------===//
3177// Type Serialization
3178//===----------------------------------------------------------------------===//
3179
3180/// Write the representation of a type to the AST stream.
3181void ASTWriter::WriteType(QualType T) {
3182 TypeIdx &IdxRef = TypeIdxs[T];
3183 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3184 IdxRef = TypeIdx(NextTypeID++);
3185 TypeIdx Idx = IdxRef;
3186
3187 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
3188
3189 // Emit the type's representation.
3190 uint64_t Offset = ASTTypeWriter(*this).write(T) - DeclTypesBlockStartOffset;
3191
3192 // Record the offset for this type.
3193 unsigned Index = Idx.getIndex() - FirstTypeID;
3194 if (TypeOffsets.size() == Index)
3195 TypeOffsets.emplace_back(Offset);
3196 else if (TypeOffsets.size() < Index) {
3197 TypeOffsets.resize(Index + 1);
3198 TypeOffsets[Index].setBitOffset(Offset);
3199 } else {
3200 llvm_unreachable("Types emitted in wrong order");
3201 }
3202}
3203
3204//===----------------------------------------------------------------------===//
3205// Declaration Serialization
3206//===----------------------------------------------------------------------===//
3207
3208/// Write the block containing all of the declaration IDs
3209/// lexically declared within the given DeclContext.
3210///
3211/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3212/// bitstream, or 0 if no block was written.
3213uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3214 DeclContext *DC) {
3215 if (DC->decls_empty())
3216 return 0;
3217
3218 // In reduced BMI, we don't care the declarations in functions.
3219 if (GeneratingReducedBMI && DC->isFunctionOrMethod())
3220 return 0;
3221
3222 uint64_t Offset = Stream.GetCurrentBitNo();
3223 SmallVector<DeclID, 128> KindDeclPairs;
3224 for (const auto *D : DC->decls()) {
3225 if (DoneWritingDeclsAndTypes && !wasDeclEmitted(D))
3226 continue;
3227
3228 KindDeclPairs.push_back(D->getKind());
3229 KindDeclPairs.push_back(GetDeclRef(D).get());
3230 }
3231
3232 ++NumLexicalDeclContexts;
3233 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3234 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3235 bytes(KindDeclPairs));
3236 return Offset;
3237}
3238
3239void ASTWriter::WriteTypeDeclOffsets() {
3240 using namespace llvm;
3241
3242 // Write the type offsets array
3243 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3244 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3245 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3246 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3247 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3248 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3249 {
3250 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3251 FirstTypeID - NUM_PREDEF_TYPE_IDS};
3252 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3253 }
3254
3255 // Write the declaration offsets array
3256 Abbrev = std::make_shared<BitCodeAbbrev>();
3257 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3258 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3259 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3260 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3261 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3262 {
3263 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3264 FirstDeclID.get() - NUM_PREDEF_DECL_IDS};
3265 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3266 }
3267}
3268
3269void ASTWriter::WriteFileDeclIDsMap() {
3270 using namespace llvm;
3271
3273 SortedFileDeclIDs.reserve(FileDeclIDs.size());
3274 for (const auto &P : FileDeclIDs)
3275 SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
3276 llvm::sort(SortedFileDeclIDs, llvm::less_first());
3277
3278 // Join the vectors of DeclIDs from all files.
3279 SmallVector<DeclID, 256> FileGroupedDeclIDs;
3280 for (auto &FileDeclEntry : SortedFileDeclIDs) {
3281 DeclIDInFileInfo &Info = *FileDeclEntry.second;
3282 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3283 llvm::stable_sort(Info.DeclIDs);
3284 for (auto &LocDeclEntry : Info.DeclIDs)
3285 FileGroupedDeclIDs.push_back(LocDeclEntry.second.get());
3286 }
3287
3288 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3289 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3290 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3291 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3292 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3293 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3294 FileGroupedDeclIDs.size()};
3295 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3296}
3297
3298void ASTWriter::WriteComments() {
3299 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3300 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
3302 return;
3303
3304 // Don't write comments to BMI to reduce the size of BMI.
3305 // If language services (e.g., clangd) want such abilities,
3306 // we can offer a special option then.
3308 return;
3309
3311 for (const auto &FO : Context->Comments.OrderedComments) {
3312 for (const auto &OC : FO.second) {
3313 const RawComment *I = OC.second;
3314 Record.clear();
3316 Record.push_back(I->getKind());
3317 Record.push_back(I->isTrailingComment());
3318 Record.push_back(I->isAlmostTrailingComment());
3319 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3320 }
3321 }
3322}
3323
3324//===----------------------------------------------------------------------===//
3325// Global Method Pool and Selector Serialization
3326//===----------------------------------------------------------------------===//
3327
3328namespace {
3329
3330// Trait used for the on-disk hash table used in the method pool.
3331class ASTMethodPoolTrait {
3332 ASTWriter &Writer;
3333
3334public:
3335 using key_type = Selector;
3336 using key_type_ref = key_type;
3337
3338 struct data_type {
3339 SelectorID ID;
3340 ObjCMethodList Instance, Factory;
3341 };
3342 using data_type_ref = const data_type &;
3343
3344 using hash_value_type = unsigned;
3345 using offset_type = unsigned;
3346
3347 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3348
3349 static hash_value_type ComputeHash(Selector Sel) {
3350 return serialization::ComputeHash(Sel);
3351 }
3352
3353 std::pair<unsigned, unsigned>
3354 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3355 data_type_ref Methods) {
3356 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
3357 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3358 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3359 Method = Method->getNext())
3360 if (ShouldWriteMethodListNode(Method))
3361 DataLen += sizeof(DeclID);
3362 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3363 Method = Method->getNext())
3364 if (ShouldWriteMethodListNode(Method))
3365 DataLen += sizeof(DeclID);
3366 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3367 }
3368
3369 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3370 using namespace llvm::support;
3371
3372 endian::Writer LE(Out, llvm::endianness::little);
3373 uint64_t Start = Out.tell();
3374 assert((Start >> 32) == 0 && "Selector key offset too large");
3375 Writer.SetSelectorOffset(Sel, Start);
3376 unsigned N = Sel.getNumArgs();
3377 LE.write<uint16_t>(N);
3378 if (N == 0)
3379 N = 1;
3380 for (unsigned I = 0; I != N; ++I)
3381 LE.write<uint32_t>(
3383 }
3384
3385 void EmitData(raw_ostream& Out, key_type_ref,
3386 data_type_ref Methods, unsigned DataLen) {
3387 using namespace llvm::support;
3388
3389 endian::Writer LE(Out, llvm::endianness::little);
3390 uint64_t Start = Out.tell(); (void)Start;
3391 LE.write<uint32_t>(Methods.ID);
3392 unsigned NumInstanceMethods = 0;
3393 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3394 Method = Method->getNext())
3395 if (ShouldWriteMethodListNode(Method))
3396 ++NumInstanceMethods;
3397
3398 unsigned NumFactoryMethods = 0;
3399 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3400 Method = Method->getNext())
3401 if (ShouldWriteMethodListNode(Method))
3402 ++NumFactoryMethods;
3403
3404 unsigned InstanceBits = Methods.Instance.getBits();
3405 assert(InstanceBits < 4);
3406 unsigned InstanceHasMoreThanOneDeclBit =
3407 Methods.Instance.hasMoreThanOneDecl();
3408 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3409 (InstanceHasMoreThanOneDeclBit << 2) |
3410 InstanceBits;
3411 unsigned FactoryBits = Methods.Factory.getBits();
3412 assert(FactoryBits < 4);
3413 unsigned FactoryHasMoreThanOneDeclBit =
3414 Methods.Factory.hasMoreThanOneDecl();
3415 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3416 (FactoryHasMoreThanOneDeclBit << 2) |
3417 FactoryBits;
3418 LE.write<uint16_t>(FullInstanceBits);
3419 LE.write<uint16_t>(FullFactoryBits);
3420 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3421 Method = Method->getNext())
3422 if (ShouldWriteMethodListNode(Method))
3423 LE.write<DeclID>((DeclID)Writer.getDeclID(Method->getMethod()));
3424 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3425 Method = Method->getNext())
3426 if (ShouldWriteMethodListNode(Method))
3427 LE.write<DeclID>((DeclID)Writer.getDeclID(Method->getMethod()));
3428
3429 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3430 }
3431
3432private:
3433 static bool ShouldWriteMethodListNode(const ObjCMethodList *Node) {
3434 return (Node->getMethod() && !Node->getMethod()->isFromASTFile());
3435 }
3436};
3437
3438} // namespace
3439
3440/// Write ObjC data: selectors and the method pool.
3441///
3442/// The method pool contains both instance and factory methods, stored
3443/// in an on-disk hash table indexed by the selector. The hash table also
3444/// contains an empty entry for every other selector known to Sema.
3445void ASTWriter::WriteSelectors(Sema &SemaRef) {
3446 using namespace llvm;
3447
3448 // Do we have to do anything at all?
3449 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3450 return;
3451 unsigned NumTableEntries = 0;
3452 // Create and write out the blob that contains selectors and the method pool.
3453 {
3454 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3455 ASTMethodPoolTrait Trait(*this);
3456
3457 // Create the on-disk hash table representation. We walk through every
3458 // selector we've seen and look it up in the method pool.
3459 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3460 for (auto &SelectorAndID : SelectorIDs) {
3461 Selector S = SelectorAndID.first;
3462 SelectorID ID = SelectorAndID.second;
3464 ASTMethodPoolTrait::data_type Data = {
3465 ID,
3468 };
3469 if (F != SemaRef.MethodPool.end()) {
3470 Data.Instance = F->second.first;
3471 Data.Factory = F->second.second;
3472 }
3473 // Only write this selector if it's not in an existing AST or something
3474 // changed.
3475 if (Chain && ID < FirstSelectorID) {
3476 // Selector already exists. Did it change?
3477 bool changed = false;
3478 for (ObjCMethodList *M = &Data.Instance; M && M->getMethod();
3479 M = M->getNext()) {
3480 if (!M->getMethod()->isFromASTFile()) {
3481 changed = true;
3482 Data.Instance = *M;
3483 break;
3484 }
3485 }
3486 for (ObjCMethodList *M = &Data.Factory; M && M->getMethod();
3487 M = M->getNext()) {
3488 if (!M->getMethod()->isFromASTFile()) {
3489 changed = true;
3490 Data.Factory = *M;
3491 break;
3492 }
3493 }
3494 if (!changed)
3495 continue;
3496 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3497 // A new method pool entry.
3498 ++NumTableEntries;
3499 }
3500 Generator.insert(S, Data, Trait);
3501 }
3502
3503 // Create the on-disk hash table in a buffer.
3504 SmallString<4096> MethodPool;
3505 uint32_t BucketOffset;
3506 {
3507 using namespace llvm::support;
3508
3509 ASTMethodPoolTrait Trait(*this);
3510 llvm::raw_svector_ostream Out(MethodPool);
3511 // Make sure that no bucket is at offset 0
3512 endian::write<uint32_t>(Out, 0, llvm::endianness::little);
3513 BucketOffset = Generator.Emit(Out, Trait);
3514 }
3515
3516 // Create a blob abbreviation
3517 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3518 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3519 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3520 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3521 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3522 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3523
3524 // Write the method pool
3525 {
3526 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3527 NumTableEntries};
3528 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3529 }
3530
3531 // Create a blob abbreviation for the selector table offsets.
3532 Abbrev = std::make_shared<BitCodeAbbrev>();
3533 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3534 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3535 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3536 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3537 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3538
3539 // Write the selector offsets table.
3540 {
3541 RecordData::value_type Record[] = {
3542 SELECTOR_OFFSETS, SelectorOffsets.size(),
3543 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3544 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3545 bytes(SelectorOffsets));
3546 }
3547 }
3548}
3549
3550/// Write the selectors referenced in @selector expression into AST file.
3551void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3552 using namespace llvm;
3553
3554 if (SemaRef.ReferencedSelectors.empty())
3555 return;
3556
3558 ASTRecordWriter Writer(*this, Record);
3559
3560 // Note: this writes out all references even for a dependent AST. But it is
3561 // very tricky to fix, and given that @selector shouldn't really appear in
3562 // headers, probably not worth it. It's not a correctness issue.
3563 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3564 Selector Sel = SelectorAndLocation.first;
3565 SourceLocation Loc = SelectorAndLocation.second;
3566 Writer.AddSelectorRef(Sel);
3567 Writer.AddSourceLocation(Loc);
3568 }
3569 Writer.Emit(REFERENCED_SELECTOR_POOL);
3570}
3571
3572//===----------------------------------------------------------------------===//
3573// Identifier Table Serialization
3574//===----------------------------------------------------------------------===//
3575
3576/// Determine the declaration that should be put into the name lookup table to
3577/// represent the given declaration in this module. This is usually D itself,
3578/// but if D was imported and merged into a local declaration, we want the most
3579/// recent local declaration instead. The chosen declaration will be the most
3580/// recent declaration in any module that imports this one.
3582 NamedDecl *D) {
3583 if (!LangOpts.Modules || !D->isFromASTFile())
3584 return D;
3585
3586 if (Decl *Redecl = D->getPreviousDecl()) {
3587 // For Redeclarable decls, a prior declaration might be local.
3588 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3589 // If we find a local decl, we're done.
3590 if (!Redecl->isFromASTFile()) {
3591 // Exception: in very rare cases (for injected-class-names), not all
3592 // redeclarations are in the same semantic context. Skip ones in a
3593 // different context. They don't go in this lookup table at all.
3594 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3596 continue;
3597 return cast<NamedDecl>(Redecl);
3598 }
3599
3600 // If we find a decl from a (chained-)PCH stop since we won't find a
3601 // local one.
3602 if (Redecl->getOwningModuleID() == 0)
3603 break;
3604 }
3605 } else if (Decl *First = D->getCanonicalDecl()) {
3606 // For Mergeable decls, the first decl might be local.
3607 if (!First->isFromASTFile())
3608 return cast<NamedDecl>(First);
3609 }
3610
3611 // All declarations are imported. Our most recent declaration will also be
3612 // the most recent one in anyone who imports us.
3613 return D;
3614}
3615
3616namespace {
3617
3618class ASTIdentifierTableTrait {
3619 ASTWriter &Writer;
3620 Preprocessor &PP;
3621 IdentifierResolver &IdResolver;
3622 bool IsModule;
3623 bool NeedDecls;
3624 ASTWriter::RecordData *InterestingIdentifierOffsets;
3625
3626 /// Determines whether this is an "interesting" identifier that needs a
3627 /// full IdentifierInfo structure written into the hash table. Notably, this
3628 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3629 /// to check that.
3630 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3631 bool IsInteresting =
3632 II->getNotableIdentifierID() !=
3633 tok::NotableIdentifierKind::not_notable ||
3634 II->getBuiltinID() != Builtin::ID::NotBuiltin ||
3635 II->getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
3636 if (MacroOffset || II->isPoisoned() || (!IsModule && IsInteresting) ||
3638 (NeedDecls && II->getFETokenInfo()))
3639 return true;
3640
3641 return false;
3642 }
3643
3644public:
3645 using key_type = const IdentifierInfo *;
3646 using key_type_ref = key_type;
3647
3648 using data_type = IdentID;
3649 using data_type_ref = data_type;
3650
3651 using hash_value_type = unsigned;
3652 using offset_type = unsigned;
3653
3654 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3655 IdentifierResolver &IdResolver, bool IsModule,
3656 ASTWriter::RecordData *InterestingIdentifierOffsets)
3657 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3658 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3659 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3660
3661 bool needDecls() const { return NeedDecls; }
3662
3663 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3664 return llvm::djbHash(II->getName());
3665 }
3666
3667 bool isInterestingIdentifier(const IdentifierInfo *II) {
3668 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3669 return isInterestingIdentifier(II, MacroOffset);
3670 }
3671
3672 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3673 return isInterestingIdentifier(II, 0);
3674 }
3675
3676 std::pair<unsigned, unsigned>
3677 EmitKeyDataLength(raw_ostream &Out, const IdentifierInfo *II, IdentID ID) {
3678 // Record the location of the identifier data. This is used when generating
3679 // the mapping from persistent IDs to strings.
3680 Writer.SetIdentifierOffset(II, Out.tell());
3681
3682 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3683
3684 // Emit the offset of the key/data length information to the interesting
3685 // identifiers table if necessary.
3686 if (InterestingIdentifierOffsets &&
3687 isInterestingIdentifier(II, MacroOffset))
3688 InterestingIdentifierOffsets->push_back(Out.tell());
3689
3690 unsigned KeyLen = II->getLength() + 1;
3691 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3692 if (isInterestingIdentifier(II, MacroOffset)) {
3693 DataLen += 2; // 2 bytes for builtin ID
3694 DataLen += 2; // 2 bytes for flags
3695 if (MacroOffset)
3696 DataLen += 4; // MacroDirectives offset.
3697
3698 if (NeedDecls)
3699 DataLen += std::distance(IdResolver.begin(II), IdResolver.end()) *
3700 sizeof(DeclID);
3701 }
3702 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3703 }
3704
3705 void EmitKey(raw_ostream &Out, const IdentifierInfo *II, unsigned KeyLen) {
3706 Out.write(II->getNameStart(), KeyLen);
3707 }
3708
3709 void EmitData(raw_ostream &Out, const IdentifierInfo *II, IdentID ID,
3710 unsigned) {
3711 using namespace llvm::support;
3712
3713 endian::Writer LE(Out, llvm::endianness::little);
3714
3715 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3716 if (!isInterestingIdentifier(II, MacroOffset)) {
3717 LE.write<uint32_t>(ID << 1);
3718 return;
3719 }
3720
3721 LE.write<uint32_t>((ID << 1) | 0x01);
3722 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3723 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3724 LE.write<uint16_t>(Bits);
3725 Bits = 0;
3726 bool HadMacroDefinition = MacroOffset != 0;
3727 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3728 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3729 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3730 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3731 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3732 LE.write<uint16_t>(Bits);
3733
3734 if (HadMacroDefinition)
3735 LE.write<uint32_t>(MacroOffset);
3736
3737 if (NeedDecls) {
3738 // Emit the declaration IDs in reverse order, because the
3739 // IdentifierResolver provides the declarations as they would be
3740 // visible (e.g., the function "stat" would come before the struct
3741 // "stat"), but the ASTReader adds declarations to the end of the list
3742 // (so we need to see the struct "stat" before the function "stat").
3743 // Only emit declarations that aren't from a chained PCH, though.
3744 SmallVector<NamedDecl *, 16> Decls(IdResolver.decls(II));
3745 for (NamedDecl *D : llvm::reverse(Decls))
3746 LE.write<DeclID>((DeclID)Writer.getDeclID(
3748 }
3749 }
3750};
3751
3752} // namespace
3753
3754/// Write the identifier table into the AST file.
3755///
3756/// The identifier table consists of a blob containing string data
3757/// (the actual identifiers themselves) and a separate "offsets" index
3758/// that maps identifier IDs to locations within the blob.
3759void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3760 IdentifierResolver &IdResolver,
3761 bool IsModule) {
3762 using namespace llvm;
3763
3764 RecordData InterestingIdents;
3765
3766 // Create and write out the blob that contains the identifier
3767 // strings.
3768 {
3769 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3770 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule,
3771 IsModule ? &InterestingIdents : nullptr);
3772
3773 // Look for any identifiers that were named while processing the
3774 // headers, but are otherwise not needed. We add these to the hash
3775 // table to enable checking of the predefines buffer in the case
3776 // where the user adds new macro definitions when building the AST
3777 // file.
3779 for (const auto &ID : PP.getIdentifierTable())
3780 if (Trait.isInterestingNonMacroIdentifier(ID.second))
3781 IIs.push_back(ID.second);
3782 // Sort the identifiers lexicographically before getting the references so
3783 // that their order is stable.
3784 llvm::sort(IIs, llvm::deref<std::less<>>());
3785 for (const IdentifierInfo *II : IIs)
3786 getIdentifierRef(II);
3787
3788 // Create the on-disk hash table representation. We only store offsets
3789 // for identifiers that appear here for the first time.
3790 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3791 for (auto IdentIDPair : IdentifierIDs) {
3792 const IdentifierInfo *II = IdentIDPair.first;
3793 IdentID ID = IdentIDPair.second;
3794 assert(II && "NULL identifier in identifier table");
3795
3796 // Write out identifiers if either the ID is local or the identifier has
3797 // changed since it was loaded.
3798 if (ID >= FirstIdentID || !Chain || !II->isFromAST() ||
3800 (Trait.needDecls() &&
3802 Generator.insert(II, ID, Trait);
3803 }
3804
3805 // Create the on-disk hash table in a buffer.
3807 uint32_t BucketOffset;
3808 {
3809 using namespace llvm::support;
3810
3811 llvm::raw_svector_ostream Out(IdentifierTable);
3812 // Make sure that no bucket is at offset 0
3813 endian::write<uint32_t>(Out, 0, llvm::endianness::little);
3814 BucketOffset = Generator.Emit(Out, Trait);
3815 }
3816
3817 // Create a blob abbreviation
3818 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3819 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3820 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3821 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3822 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3823
3824 // Write the identifier table
3825 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3826 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3827 }
3828
3829 // Write the offsets table for identifier IDs.
3830 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3831 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3832 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3833 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3834 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3835 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3836
3837#ifndef NDEBUG
3838 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3839 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3840#endif
3841
3842 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3843 IdentifierOffsets.size(),
3844 FirstIdentID - NUM_PREDEF_IDENT_IDS};
3845 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3846 bytes(IdentifierOffsets));
3847
3848 // In C++, write the list of interesting identifiers (those that are
3849 // defined as macros, poisoned, or similar unusual things).
3850 if (!InterestingIdents.empty())
3851 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3852}
3853
3854//===----------------------------------------------------------------------===//
3855// DeclContext's Name Lookup Table Serialization
3856//===----------------------------------------------------------------------===//
3857
3858namespace {
3859
3860// Trait used for the on-disk hash table used in the method pool.
3861class ASTDeclContextNameLookupTrait {
3862 ASTWriter &Writer;
3864
3865public:
3866 using key_type = DeclarationNameKey;
3867 using key_type_ref = key_type;
3868
3869 /// A start and end index into DeclIDs, representing a sequence of decls.
3870 using data_type = std::pair<unsigned, unsigned>;
3871 using data_type_ref = const data_type &;
3872
3873 using hash_value_type = unsigned;
3874 using offset_type = unsigned;
3875
3876 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3877
3878 template<typename Coll>
3879 data_type getData(const Coll &Decls) {
3880 unsigned Start = DeclIDs.size();
3881 for (NamedDecl *D : Decls) {
3882 NamedDecl *DeclForLocalLookup =
3884
3885 if (Writer.getDoneWritingDeclsAndTypes() &&
3886 !Writer.wasDeclEmitted(DeclForLocalLookup))
3887 continue;
3888
3889 DeclIDs.push_back(Writer.GetDeclRef(DeclForLocalLookup));
3890 }
3891 return std::make_pair(Start, DeclIDs.size());
3892 }
3893
3894 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3895 unsigned Start = DeclIDs.size();
3896 DeclIDs.insert(
3897 DeclIDs.end(),
3900 return std::make_pair(Start, DeclIDs.size());
3901 }
3902
3903 static bool EqualKey(key_type_ref a, key_type_ref b) {
3904 return a == b;
3905 }
3906
3907 hash_value_type ComputeHash(DeclarationNameKey Name) {
3908 return Name.getHash();
3909 }
3910
3911 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3912 assert(Writer.hasChain() &&
3913 "have reference to loaded module file but no chain?");
3914
3915 using namespace llvm::support;
3916
3917 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F),
3918 llvm::endianness::little);
3919 }
3920
3921 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3922 DeclarationNameKey Name,
3923 data_type_ref Lookup) {
3924 unsigned KeyLen = 1;
3925 switch (Name.getKind()) {
3932 KeyLen += 4;
3933 break;
3935 KeyLen += 1;
3936 break;
3941 break;
3942 }
3943
3944 // length of DeclIDs.
3945 unsigned DataLen = sizeof(DeclID) * (Lookup.second - Lookup.first);
3946
3947 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3948 }
3949
3950 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3951 using namespace llvm::support;
3952
3953 endian::Writer LE(Out, llvm::endianness::little);
3954 LE.write<uint8_t>(Name.getKind());
3955 switch (Name.getKind()) {
3959 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3960 return;
3964 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3965 return;
3967 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3968 "Invalid operator?");
3969 LE.write<uint8_t>(Name.getOperatorKind());
3970 return;
3975 return;
3976 }
3977
3978 llvm_unreachable("Invalid name kind?");
3979 }
3980
3981 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3982 unsigned DataLen) {
3983 using namespace llvm::support;
3984
3985 endian::Writer LE(Out, llvm::endianness::little);
3986 uint64_t Start = Out.tell(); (void)Start;
3987 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3988 LE.write<DeclID>((DeclID)DeclIDs[I]);
3989 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3990 }
3991};
3992
3993} // namespace
3994
3995bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3996 DeclContext *DC) {
3997 return Result.hasExternalDecls() &&
3998 DC->hasNeedToReconcileExternalVisibleStorage();
3999}
4000
4001bool ASTWriter::isLookupResultEntirelyExternalOrUnreachable(
4003 for (auto *D : Result.getLookupResult()) {
4004 auto *LocalD = getDeclForLocalLookup(getLangOpts(), D);
4005 if (LocalD->isFromASTFile())
4006 continue;
4007
4008 // We can only be sure whether the local declaration is reachable
4009 // after we done writing the declarations and types.
4010 if (DoneWritingDeclsAndTypes && !wasDeclEmitted(LocalD))
4011 continue;
4012
4013 return false;
4014 }
4015
4016 return true;
4017}
4018
4019void
4020ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
4021 llvm::SmallVectorImpl<char> &LookupTable) {
4022 assert(!ConstDC->hasLazyLocalLexicalLookups() &&
4023 !ConstDC->hasLazyExternalLexicalLookups() &&
4024 "must call buildLookups first");
4025
4026 // FIXME: We need to build the lookups table, which is logically const.
4027 auto *DC = const_cast<DeclContext*>(ConstDC);
4028 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
4029
4030 // Create the on-disk hash table representation.
4032 ASTDeclContextNameLookupTrait> Generator;
4033 ASTDeclContextNameLookupTrait Trait(*this);
4034
4035 // The first step is to collect the declaration names which we need to
4036 // serialize into the name lookup table, and to collect them in a stable
4037 // order.
4039
4040 // We also build up small sets of the constructor and conversion function
4041 // names which are visible.
4042 llvm::SmallPtrSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
4043
4044 for (auto &Lookup : *DC->buildLookup()) {
4045 auto &Name = Lookup.first;
4046 auto &Result = Lookup.second;
4047
4048 // If there are no local declarations in our lookup result, we
4049 // don't need to write an entry for the name at all. If we can't
4050 // write out a lookup set without performing more deserialization,
4051 // just skip this entry.
4052 //
4053 // Also in reduced BMI, we'd like to avoid writing unreachable
4054 // declarations in GMF, so we need to avoid writing declarations
4055 // that entirely external or unreachable.
4056 //
4057 // FIMXE: It looks sufficient to test
4058 // isLookupResultEntirelyExternalOrUnreachable here. But due to bug we have
4059 // to test isLookupResultExternal here. See
4060 // https://github.com/llvm/llvm-project/issues/61065 for details.
4061 if ((GeneratingReducedBMI || isLookupResultExternal(Result, DC)) &&
4062 isLookupResultEntirelyExternalOrUnreachable(Result, DC))
4063 continue;
4064
4065 // We also skip empty results. If any of the results could be external and
4066 // the currently available results are empty, then all of the results are
4067 // external and we skip it above. So the only way we get here with an empty
4068 // results is when no results could have been external *and* we have
4069 // external results.
4070 //
4071 // FIXME: While we might want to start emitting on-disk entries for negative
4072 // lookups into a decl context as an optimization, today we *have* to skip
4073 // them because there are names with empty lookup results in decl contexts
4074 // which we can't emit in any stable ordering: we lookup constructors and
4075 // conversion functions in the enclosing namespace scope creating empty
4076 // results for them. This in almost certainly a bug in Clang's name lookup,
4077 // but that is likely to be hard or impossible to fix and so we tolerate it
4078 // here by omitting lookups with empty results.
4079 if (Lookup.second.getLookupResult().empty())
4080 continue;
4081
4082 switch (Lookup.first.getNameKind()) {
4083 default:
4084 Names.push_back(Lookup.first);
4085 break;
4086
4088 assert(isa<CXXRecordDecl>(DC) &&
4089 "Cannot have a constructor name outside of a class!");
4090 ConstructorNameSet.insert(Name);
4091 break;
4092
4094 assert(isa<CXXRecordDecl>(DC) &&
4095 "Cannot have a conversion function name outside of a class!");
4096 ConversionNameSet.insert(Name);
4097 break;
4098 }
4099 }
4100
4101 // Sort the names into a stable order.
4102 llvm::sort(Names);
4103
4104 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
4105 // We need to establish an ordering of constructor and conversion function
4106 // names, and they don't have an intrinsic ordering.
4107
4108 // First we try the easy case by forming the current context's constructor
4109 // name and adding that name first. This is a very useful optimization to
4110 // avoid walking the lexical declarations in many cases, and it also
4111 // handles the only case where a constructor name can come from some other
4112 // lexical context -- when that name is an implicit constructor merged from
4113 // another declaration in the redecl chain. Any non-implicit constructor or
4114 // conversion function which doesn't occur in all the lexical contexts
4115 // would be an ODR violation.
4116 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
4117 Context->getCanonicalType(Context->getRecordType(D)));
4118 if (ConstructorNameSet.erase(ImplicitCtorName))
4119 Names.push_back(ImplicitCtorName);
4120
4121 // If we still have constructors or conversion functions, we walk all the
4122 // names in the decl and add the constructors and conversion functions
4123 // which are visible in the order they lexically occur within the context.
4124 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
4125 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
4126 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4127 auto Name = ChildND->getDeclName();
4128 switch (Name.getNameKind()) {
4129 default:
4130 continue;
4131
4133 if (ConstructorNameSet.erase(Name))
4134 Names.push_back(Name);
4135 break;
4136
4138 if (ConversionNameSet.erase(Name))
4139 Names.push_back(Name);
4140 break;
4141 }
4142
4143 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
4144 break;
4145 }
4146
4147 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
4148 "constructors by walking all the "
4149 "lexical members of the context.");
4150 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
4151 "conversion functions by walking all "
4152 "the lexical members of the context.");
4153 }
4154
4155 // Next we need to do a lookup with each name into this decl context to fully
4156 // populate any results from external sources. We don't actually use the
4157 // results of these lookups because we only want to use the results after all
4158 // results have been loaded and the pointers into them will be stable.
4159 for (auto &Name : Names)
4160 DC->lookup(Name);
4161
4162 // Now we need to insert the results for each name into the hash table. For
4163 // constructor names and conversion function names, we actually need to merge
4164 // all of the results for them into one list of results each and insert
4165 // those.
4166 SmallVector<NamedDecl *, 8> ConstructorDecls;
4167 SmallVector<NamedDecl *, 8> ConversionDecls;
4168
4169 // Now loop over the names, either inserting them or appending for the two
4170 // special cases.
4171 for (auto &Name : Names) {
4173
4174 switch (Name.getNameKind()) {
4175 default:
4176 Generator.insert(Name, Trait.getData(Result), Trait);
4177 break;
4178
4180 ConstructorDecls.append(Result.begin(), Result.end());
4181 break;
4182
4184 ConversionDecls.append(Result.begin(), Result.end());
4185 break;
4186 }
4187 }
4188
4189 // Handle our two special cases if we ended up having any. We arbitrarily use
4190 // the first declaration's name here because the name itself isn't part of
4191 // the key, only the kind of name is used.
4192 if (!ConstructorDecls.empty())
4193 Generator.insert(ConstructorDecls.front()->getDeclName(),
4194 Trait.getData(ConstructorDecls), Trait);
4195 if (!ConversionDecls.empty())
4196 Generator.insert(ConversionDecls.front()->getDeclName(),
4197 Trait.getData(ConversionDecls), Trait);
4198
4199 // Create the on-disk hash table. Also emit the existing imported and
4200 // merged table if there is one.
4201 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4202 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4203}
4204
4205/// Write the block containing all of the declaration IDs
4206/// visible from the given DeclContext.
4207///
4208/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4209/// bitstream, or 0 if no block was written.
4210uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4211 DeclContext *DC) {
4212 // If we imported a key declaration of this namespace, write the visible
4213 // lookup results as an update record for it rather than including them
4214 // on this declaration. We will only look at key declarations on reload.
4215 if (isa<NamespaceDecl>(DC) && Chain &&
4216 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4217 // Only do this once, for the first local declaration of the namespace.
4218 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4219 Prev = Prev->getPreviousDecl())
4220 if (!Prev->isFromASTFile())
4221 return 0;
4222
4223 // Note that we need to emit an update record for the primary context.
4224 UpdatedDeclContexts.insert(DC->getPrimaryContext());
4225
4226 // Make sure all visible decls are written. They will be recorded later. We
4227 // do this using a side data structure so we can sort the names into
4228 // a deterministic order.
4231 LookupResults;
4232 if (Map) {
4233 LookupResults.reserve(Map->size());
4234 for (auto &Entry : *Map)
4235 LookupResults.push_back(
4236 std::make_pair(Entry.first, Entry.second.getLookupResult()));
4237 }
4238
4239 llvm::sort(LookupResults, llvm::less_first());
4240 for (auto &NameAndResult : LookupResults) {
4241 DeclarationName Name = NameAndResult.first;
4242 DeclContext::lookup_result Result = NameAndResult.second;
4243 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4244 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4245 // We have to work around a name lookup bug here where negative lookup
4246 // results for these names get cached in namespace lookup tables (these
4247 // names should never be looked up in a namespace).
4248 assert(Result.empty() && "Cannot have a constructor or conversion "
4249 "function name in a namespace!");
4250 continue;
4251 }
4252
4253 for (NamedDecl *ND : Result) {
4254 if (ND->isFromASTFile())
4255 continue;
4256
4257 if (DoneWritingDeclsAndTypes && !wasDeclEmitted(ND))
4258 continue;
4259
4260 GetDeclRef(ND);
4261 }
4262 }
4263
4264 return 0;
4265 }
4266
4267 if (DC->getPrimaryContext() != DC)
4268 return 0;
4269
4270 // Skip contexts which don't support name lookup.
4271 if (!DC->isLookupContext())
4272 return 0;
4273
4274 // If not in C++, we perform name lookup for the translation unit via the
4275 // IdentifierInfo chains, don't bother to build a visible-declarations table.
4276 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4277 return 0;
4278
4279 // Serialize the contents of the mapping used for lookup. Note that,
4280 // although we have two very different code paths, the serialized
4281 // representation is the same for both cases: a declaration name,
4282 // followed by a size, followed by references to the visible
4283 // declarations that have that name.
4284 uint64_t Offset = Stream.GetCurrentBitNo();
4285 StoredDeclsMap *Map = DC->buildLookup();
4286 if (!Map || Map->empty())
4287 return 0;
4288
4289 // Create the on-disk hash table in a buffer.
4290 SmallString<4096> LookupTable;
4291 GenerateNameLookupTable(DC, LookupTable);
4292
4293 // Write the lookup table
4294 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4295 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4296 LookupTable);
4297 ++NumVisibleDeclContexts;
4298 return Offset;
4299}
4300
4301/// Write an UPDATE_VISIBLE block for the given context.
4302///
4303/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4304/// DeclContext in a dependent AST file. As such, they only exist for the TU
4305/// (in C++), for namespaces, and for classes with forward-declared unscoped
4306/// enumeration members (in C++11).
4307void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4308 StoredDeclsMap *Map = DC->getLookupPtr();
4309 if (!Map || Map->empty())
4310 return;
4311
4312 // Create the on-disk hash table in a buffer.
4313 SmallString<4096> LookupTable;
4314 GenerateNameLookupTable(DC, LookupTable);
4315
4316 // If we're updating a namespace, select a key declaration as the key for the
4317 // update record; those are the only ones that will be checked on reload.
4318 if (isa<NamespaceDecl>(DC))
4319 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4320
4321 // Write the lookup table
4322 RecordData::value_type Record[] = {UPDATE_VISIBLE,
4323 getDeclID(cast<Decl>(DC)).get()};
4324 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4325}
4326
4327/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4328void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) {
4329 RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
4330 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4331}
4332
4333/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4334void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4335 if (!SemaRef.Context.getLangOpts().OpenCL)
4336 return;
4337
4338 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4340 for (const auto &I:Opts.OptMap) {
4341 AddString(I.getKey(), Record);
4342 auto V = I.getValue();
4343 Record.push_back(V.Supported ? 1 : 0);
4344 Record.push_back(V.Enabled ? 1 : 0);
4345 Record.push_back(V.WithPragma ? 1 : 0);
4346 Record.push_back(V.Avail);
4347 Record.push_back(V.Core);
4348 Record.push_back(V.Opt);
4349 }
4350 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4351}
4352void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4353 if (SemaRef.CUDA().ForceHostDeviceDepth > 0) {
4354 RecordData::value_type Record[] = {SemaRef.CUDA().ForceHostDeviceDepth};
4355 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4356 }
4357}
4358
4359void ASTWriter::WriteObjCCategories() {
4361 RecordData Categories;
4362
4363 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4364 unsigned Size = 0;
4365 unsigned StartIndex = Categories.size();
4366
4367 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4368
4369 // Allocate space for the size.
4370 Categories.push_back(0);
4371
4372 // Add the categories.
4374 Cat = Class->known_categories_begin(),
4375 CatEnd = Class->known_categories_end();
4376 Cat != CatEnd; ++Cat, ++Size) {
4377 assert(getDeclID(*Cat).isValid() && "Bogus category");
4378 AddDeclRef(*Cat, Categories);
4379 }
4380
4381 // Update the size.
4382 Categories[StartIndex] = Size;
4383
4384 // Record this interface -> category map.
4385 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4386 CategoriesMap.push_back(CatInfo);
4387 }
4388
4389 // Sort the categories map by the definition ID, since the reader will be
4390 // performing binary searches on this information.
4391 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4392
4393 // Emit the categories map.
4394 using namespace llvm;
4395
4396 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4397 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4398 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4399 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4400 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4401
4402 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4403 Stream.EmitRecordWithBlob(AbbrevID, Record,
4404 reinterpret_cast<char *>(CategoriesMap.data()),
4405 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4406
4407 // Emit the category lists.
4408 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4409}
4410
4411void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4413
4414 if (LPTMap.empty())
4415 return;
4416
4418 for (auto &LPTMapEntry : LPTMap) {
4419 const FunctionDecl *FD = LPTMapEntry.first;
4420 LateParsedTemplate &LPT = *LPTMapEntry.second;
4421 AddDeclRef(FD, Record);
4422 AddDeclRef(LPT.D, Record);
4423 Record.push_back(LPT.FPO.getAsOpaqueInt());
4424 Record.push_back(LPT.Toks.size());
4425
4426 for (const auto &Tok : LPT.Toks) {
4427 AddToken(Tok, Record);
4428 }
4429 }
4430 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4431}
4432
4433/// Write the state of 'pragma clang optimize' at the end of the module.
4434void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4436 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4437 AddSourceLocation(PragmaLoc, Record);
4438 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4439}
4440
4441/// Write the state of 'pragma ms_struct' at the end of the module.
4442void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4444 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4445 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4446}
4447
4448/// Write the state of 'pragma pointers_to_members' at the end of the
4449//module.
4450void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4454 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4455}
4456
4457/// Write the state of 'pragma align/pack' at the end of the module.
4458void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4459 // Don't serialize pragma align/pack state for modules, since it should only
4460 // take effect on a per-submodule basis.
4461 if (WritingModule)
4462 return;
4463
4465 AddAlignPackInfo(SemaRef.AlignPackStack.CurrentValue, Record);
4466 AddSourceLocation(SemaRef.AlignPackStack.CurrentPragmaLocation, Record);
4467 Record.push_back(SemaRef.AlignPackStack.Stack.size());
4468 for (const auto &StackEntry : SemaRef.AlignPackStack.Stack) {
4469 AddAlignPackInfo(StackEntry.Value, Record);
4470 AddSourceLocation(StackEntry.PragmaLocation, Record);
4471 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4472 AddString(StackEntry.StackSlotLabel, Record);
4473 }
4474 Stream.EmitRecord(ALIGN_PACK_PRAGMA_OPTIONS, Record);
4475}
4476
4477/// Write the state of 'pragma float_control' at the end of the module.
4478void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
4479 // Don't serialize pragma float_control state for modules,
4480 // since it should only take effect on a per-submodule basis.
4481 if (WritingModule)
4482 return;
4483
4485 Record.push_back(SemaRef.FpPragmaStack.CurrentValue.getAsOpaqueInt());
4486 AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
4487 Record.push_back(SemaRef.FpPragmaStack.Stack.size());
4488 for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
4489 Record.push_back(StackEntry.Value.getAsOpaqueInt());
4490 AddSourceLocation(StackEntry.PragmaLocation, Record);
4491 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4492 AddString(StackEntry.StackSlotLabel, Record);
4493 }
4494 Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
4495}
4496
4497void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4498 ModuleFileExtensionWriter &Writer) {
4499 // Enter the extension block.
4500 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4501
4502 // Emit the metadata record abbreviation.
4503 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4504 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4505 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4506 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4507 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4508 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4509 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4510 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4511
4512 // Emit the metadata record.
4514 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4515 Record.push_back(EXTENSION_METADATA);
4516 Record.push_back(Metadata.MajorVersion);
4517 Record.push_back(Metadata.MinorVersion);
4518 Record.push_back(Metadata.BlockName.size());
4519 Record.push_back(Metadata.UserInfo.size());
4520 SmallString<64> Buffer;
4521 Buffer += Metadata.BlockName;
4522 Buffer += Metadata.UserInfo;
4523 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4524
4525 // Emit the contents of the extension block.
4526 Writer.writeExtensionContents(SemaRef, Stream);
4527
4528 // Exit the extension block.
4529 Stream.ExitBlock();
4530}
4531
4532//===----------------------------------------------------------------------===//
4533// General Serialization Routines
4534//===----------------------------------------------------------------------===//
4535
4537 auto &Record = *this;
4538 // FIXME: Clang can't handle the serialization/deserialization of
4539 // preferred_name properly now. See
4540 // https://github.com/llvm/llvm-project/issues/56490 for example.
4541 if (!A || (isa<PreferredNameAttr>(A) &&
4542 Writer->isWritingStdCXXNamedModules()))
4543 return Record.push_back(0);
4544
4545 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4546
4547 Record.AddIdentifierRef(A->getAttrName());
4548 Record.AddIdentifierRef(A->getScopeName());
4549 Record.AddSourceRange(A->getRange());
4550 Record.AddSourceLocation(A->getScopeLoc());
4551 Record.push_back(A->getParsedKind());
4552 Record.push_back(A->getSyntax());
4553 Record.push_back(A->getAttributeSpellingListIndexRaw());
4554 Record.push_back(A->isRegularKeywordAttribute());
4555
4556#include "clang/Serialization/AttrPCHWrite.inc"
4557}
4558
4559/// Emit the list of attributes to the specified record.
4561 push_back(Attrs.size());
4562 for (const auto *A : Attrs)
4563 AddAttr(A);
4564}
4565
4568 // FIXME: Should translate token kind to a stable encoding.
4569 Record.push_back(Tok.getKind());
4570 // FIXME: Should translate token flags to a stable encoding.
4571 Record.push_back(Tok.getFlags());
4572
4573 if (Tok.isAnnotation()) {
4575 switch (Tok.getKind()) {
4576 case tok::annot_pragma_loop_hint: {
4577 auto *Info = static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
4578 AddToken(Info->PragmaName, Record);
4579 AddToken(Info->Option, Record);
4580 Record.push_back(Info->Toks.size());
4581 for (const auto &T : Info->Toks)
4582 AddToken(T, Record);
4583 break;
4584 }
4585 case tok::annot_pragma_pack: {
4586 auto *Info =
4587 static_cast<Sema::PragmaPackInfo *>(Tok.getAnnotationValue());
4588 Record.push_back(static_cast<unsigned>(Info->Action));
4589 AddString(Info->SlotLabel, Record);
4590 AddToken(Info->Alignment, Record);
4591 break;
4592 }
4593 // Some annotation tokens do not use the PtrData field.
4594 case tok::annot_pragma_openmp:
4595 case tok::annot_pragma_openmp_end:
4596 case tok::annot_pragma_unused:
4597 case tok::annot_pragma_openacc:
4598 case tok::annot_pragma_openacc_end:
4599 break;
4600 default:
4601 llvm_unreachable("missing serialization code for annotation token");
4602 }
4603 } else {
4604 Record.push_back(Tok.getLength());
4605 // FIXME: When reading literal tokens, reconstruct the literal pointer if it
4606 // is needed.
4608 }
4609}
4610
4612 Record.push_back(Str.size());
4613 Record.insert(Record.end(), Str.begin(), Str.end());
4614}
4615
4617 assert(Context && "should have context when outputting path");
4618
4619 // Leave special file names as they are.
4620 StringRef PathStr(Path.data(), Path.size());
4621 if (PathStr == "<built-in>" || PathStr == "<command line>")
4622 return false;
4623
4624 bool Changed =
4626
4627 // Remove a prefix to make the path relative, if relevant.
4628 const char *PathBegin = Path.data();
4629 const char *PathPtr =
4630 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4631 if (PathPtr != PathBegin) {
4632 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4633 Changed = true;
4634 }
4635
4636 return Changed;
4637}
4638
4640 SmallString<128> FilePath(Path);
4641 PreparePathForOutput(FilePath);
4642 AddString(FilePath, Record);
4643}
4644
4646 StringRef Path) {
4647 SmallString<128> FilePath(Path);
4648 PreparePathForOutput(FilePath);
4649 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4650}
4651
4652void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4654 Record.push_back(Version.getMajor());
4655 if (std::optional<unsigned> Minor = Version.getMinor())
4656 Record.push_back(*Minor + 1);
4657 else
4658 Record.push_back(0);
4659 if (std::optional<unsigned> Subminor = Version.getSubminor())
4660 Record.push_back(*Subminor + 1);
4661 else
4662 Record.push_back(0);
4663}
4664
4665/// Note that the identifier II occurs at the given offset
4666/// within the identifier table.
4667void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4668 IdentID ID = IdentifierIDs[II];
4669 // Only store offsets new to this AST file. Other identifier names are looked
4670 // up earlier in the chain and thus don't need an offset.
4671 if (ID >= FirstIdentID)
4672 IdentifierOffsets[ID - FirstIdentID] = Offset;
4673}
4674
4675/// Note that the selector Sel occurs at the given offset
4676/// within the method pool/selector table.
4677void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4678 unsigned ID = SelectorIDs[Sel];
4679 assert(ID && "Unknown selector");
4680 // Don't record offsets for selectors that are also available in a different
4681 // file.
4682 if (ID < FirstSelectorID)
4683 return;
4684 SelectorOffsets[ID - FirstSelectorID] = Offset;
4685}
4686
4687ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4688 SmallVectorImpl<char> &Buffer,
4689 InMemoryModuleCache &ModuleCache,
4690 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4691 bool IncludeTimestamps, bool BuildingImplicitModule,
4692 bool GeneratingReducedBMI)
4693 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
4694 IncludeTimestamps(IncludeTimestamps),
4695 BuildingImplicitModule(BuildingImplicitModule),
4696 GeneratingReducedBMI(GeneratingReducedBMI) {
4697 for (const auto &Ext : Extensions) {
4698 if (auto Writer = Ext->createExtensionWriter(*this))
4699 ModuleFileExtensionWriters.push_back(std::move(Writer));
4700 }
4701}
4702
4703ASTWriter::~ASTWriter() = default;
4704
4706 assert(WritingAST && "can't determine lang opts when not writing AST");
4707 return Context->getLangOpts();
4708}
4709
4711 return IncludeTimestamps ? E->getModificationTime() : 0;
4712}
4713
4714ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, StringRef OutputFile,
4715 Module *WritingModule, StringRef isysroot,
4716 bool ShouldCacheASTInMemory) {
4717 llvm::TimeTraceScope scope("WriteAST", OutputFile);
4718 WritingAST = true;
4719
4720 ASTHasCompilerErrors =
4722
4723 // Emit the file header.
4724 Stream.Emit((unsigned)'C', 8);
4725 Stream.Emit((unsigned)'P', 8);
4726 Stream.Emit((unsigned)'C', 8);
4727 Stream.Emit((unsigned)'H', 8);
4728
4729 WriteBlockInfoBlock();
4730
4731 Context = &SemaRef.Context;
4732 PP = &SemaRef.PP;
4733 this->WritingModule = WritingModule;
4734 ASTFileSignature Signature = WriteASTCore(SemaRef, isysroot, WritingModule);
4735 Context = nullptr;
4736 PP = nullptr;
4737 this->WritingModule = nullptr;
4738 this->BaseDirectory.clear();
4739
4740 WritingAST = false;
4741 if (ShouldCacheASTInMemory) {
4742 // Construct MemoryBuffer and update buffer manager.
4743 ModuleCache.addBuiltPCM(OutputFile,
4744 llvm::MemoryBuffer::getMemBufferCopy(
4745 StringRef(Buffer.begin(), Buffer.size())));
4746 }
4747 return Signature;
4748}
4749
4750template<typename Vector>
4751static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec) {
4752 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4753 I != E; ++I) {
4754 Writer.GetDeclRef(*I);
4755 }
4756}
4757
4758template <typename Vector>
4761 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4762 I != E; ++I) {
4763 Writer.AddEmittedDeclRef(*I, Record);
4764 }
4765}
4766
4767void ASTWriter::computeNonAffectingInputFiles() {
4768 SourceManager &SrcMgr = PP->getSourceManager();
4769 unsigned N = SrcMgr.local_sloc_entry_size();
4770
4771 IsSLocAffecting.resize(N, true);
4772
4773 if (!WritingModule)
4774 return;
4775
4776 auto AffectingModuleMaps = GetAffectingModuleMaps(*PP, WritingModule);
4777
4778 unsigned FileIDAdjustment = 0;
4779 unsigned OffsetAdjustment = 0;
4780
4781 NonAffectingFileIDAdjustments.reserve(N);
4782 NonAffectingOffsetAdjustments.reserve(N);
4783
4784 NonAffectingFileIDAdjustments.push_back(FileIDAdjustment);
4785 NonAffectingOffsetAdjustments.push_back(OffsetAdjustment);
4786
4787 for (unsigned I = 1; I != N; ++I) {
4788 const SrcMgr::SLocEntry *SLoc = &SrcMgr.getLocalSLocEntry(I);
4789 FileID FID = FileID::get(I);
4790 assert(&SrcMgr.getSLocEntry(FID) == SLoc);
4791
4792 if (!SLoc->isFile())
4793 continue;
4794 const SrcMgr::FileInfo &File = SLoc->getFile();
4795 const SrcMgr::ContentCache *Cache = &File.getContentCache();
4796 if (!Cache->OrigEntry)
4797 continue;
4798
4799 // Don't prune anything other than module maps.
4800 if (!isModuleMap(File.getFileCharacteristic()))
4801 continue;
4802
4803 // Don't prune module maps if all are guaranteed to be affecting.
4804 if (!AffectingModuleMaps)
4805 continue;
4806
4807 // Don't prune module maps that are affecting.
4808 if (llvm::is_contained(*AffectingModuleMaps, *Cache->OrigEntry))
4809 continue;
4810
4811 IsSLocAffecting[I] = false;
4812
4813 FileIDAdjustment += 1;
4814 // Even empty files take up one element in the offset table.
4815 OffsetAdjustment += SrcMgr.getFileIDSize(FID) + 1;
4816
4817 // If the previous file was non-affecting as well, just extend its entry
4818 // with our information.
4819 if (!NonAffectingFileIDs.empty() &&
4820 NonAffectingFileIDs.back().ID == FID.ID - 1) {
4821 NonAffectingFileIDs.back() = FID;
4822 NonAffectingRanges.back().setEnd(SrcMgr.getLocForEndOfFile(FID));
4823 NonAffectingFileIDAdjustments.back() = FileIDAdjustment;
4824 NonAffectingOffsetAdjustments.back() = OffsetAdjustment;
4825 continue;
4826 }
4827
4828 NonAffectingFileIDs.push_back(FID);
4829 NonAffectingRanges.emplace_back(SrcMgr.getLocForStartOfFile(FID),
4830 SrcMgr.getLocForEndOfFile(FID));
4831 NonAffectingFileIDAdjustments.push_back(FileIDAdjustment);
4832 NonAffectingOffsetAdjustments.push_back(OffsetAdjustment);
4833 }
4834
4836 return;
4837
4838 FileManager &FileMgr = PP->getFileManager();
4839 FileMgr.trackVFSUsage(true);
4840 // Lookup the paths in the VFS to trigger `-ivfsoverlay` usage tracking.
4841 for (StringRef Path :
4843 FileMgr.getVirtualFileSystem().exists(Path);
4844 for (unsigned I = 1; I != N; ++I) {
4845 if (IsSLocAffecting[I]) {
4846 const SrcMgr::SLocEntry *SLoc = &SrcMgr.getLocalSLocEntry(I);
4847 if (!SLoc->isFile())
4848 continue;
4849 const SrcMgr::FileInfo &File = SLoc->getFile();
4850 const SrcMgr::ContentCache *Cache = &File.getContentCache();
4851 if (!Cache->OrigEntry)
4852 continue;
4853 FileMgr.getVirtualFileSystem().exists(
4854 Cache->OrigEntry->getNameAsRequested());
4855 }
4856 }
4857 FileMgr.trackVFSUsage(false);
4858}
4859
4860void ASTWriter::PrepareWritingSpecialDecls(Sema &SemaRef) {
4861 ASTContext &Context = SemaRef.Context;
4862
4863 bool isModule = WritingModule != nullptr;
4864
4865 // Set up predefined declaration IDs.
4866 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4867 if (D) {
4868 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4869 DeclIDs[D] = ID;
4870 }
4871 };
4872 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4874 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4875 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4876 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4877 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4879 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4880 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4881 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4883 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4884 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4885 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4887 RegisterPredefDecl(Context.MSGuidTagDecl,
4889 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4890 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4892 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4894 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4896 RegisterPredefDecl(Context.TypePackElementDecl,
4898
4899 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4900
4901 // Force all top level declarations to be emitted.
4902 //
4903 // We start emitting top level declarations from the module purview to
4904 // implement the eliding unreachable declaration feature.
4905 for (const auto *D : TU->noload_decls()) {
4906 if (D->isFromASTFile())
4907 continue;
4908
4909 if (GeneratingReducedBMI) {
4911 continue;
4912
4913 // Don't force emitting static entities.
4914 //
4915 // Technically, all static entities shouldn't be in reduced BMI. The
4916 // language also specifies that the program exposes TU-local entities
4917 // is ill-formed. However, in practice, there are a lot of projects
4918 // uses `static inline` in the headers. So we can't get rid of all
4919 // static entities in reduced BMI now.
4920 if (auto *ND = dyn_cast<NamedDecl>(D);
4921 ND && ND->getFormalLinkage() == Linkage::Internal)
4922 continue;
4923 }
4924
4925 GetDeclRef(D);
4926 }
4927
4928 if (GeneratingReducedBMI)
4929 return;
4930
4931 // Writing all of the tentative definitions in this file, in
4932 // TentativeDefinitions order. Generally, this record will be empty for
4933 // headers.
4934 RecordData TentativeDefinitions;
4936
4937 // Writing all of the file scoped decls in this file.
4938 if (!isModule)
4940
4941 // Writing all of the delegating constructors we still need
4942 // to resolve.
4943 if (!isModule)
4945
4946 // Writing all of the ext_vector declarations.
4947 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls);
4948
4949 // Writing all of the VTable uses information.
4950 if (!SemaRef.VTableUses.empty())
4951 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I)
4952 GetDeclRef(SemaRef.VTableUses[I].first);
4953
4954 // Writing all of the UnusedLocalTypedefNameCandidates.
4955 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4956 GetDeclRef(TD);
4957
4958 // Writing all of pending implicit instantiations.
4959 for (const auto &I : SemaRef.PendingInstantiations)
4960 GetDeclRef(I.first);
4961 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4962 "There are local ones at end of translation unit!");
4963
4964 // Writing some declaration references.
4965 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4966 GetDeclRef(SemaRef.getStdNamespace());
4967 GetDeclRef(SemaRef.getStdBadAlloc());
4968 GetDeclRef(SemaRef.getStdAlignValT());
4969 }
4970
4971 if (Context.getcudaConfigureCallDecl())
4973
4974 // Writing all of the known namespaces.
4975 for (const auto &I : SemaRef.KnownNamespaces)
4976 if (!I.second)
4977 GetDeclRef(I.first);
4978
4979 // Writing all used, undefined objects that require definitions.
4981 SemaRef.getUndefinedButUsed(Undefined);
4982 for (const auto &I : Undefined)
4983 GetDeclRef(I.first);
4984
4985 // Writing all delete-expressions that we would like to
4986 // analyze later in AST.
4987 if (!isModule)
4988 for (const auto &DeleteExprsInfo :
4990 GetDeclRef(DeleteExprsInfo.first);
4991
4992 // Make sure visible decls, added to DeclContexts previously loaded from
4993 // an AST file, are registered for serialization. Likewise for template
4994 // specializations added to imported templates.
4995 for (const auto *I : DeclsToEmitEvenIfUnreferenced)
4996 GetDeclRef(I);
4997 DeclsToEmitEvenIfUnreferenced.clear();
4998
4999 // Make sure all decls associated with an identifier are registered for
5000 // serialization, if we're storing decls with identifiers.
5001 if (!WritingModule || !getLangOpts().CPlusPlus) {
5003 for (const auto &ID : SemaRef.PP.getIdentifierTable()) {
5004 const IdentifierInfo *II = ID.second;
5005 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
5006 IIs.push_back(II);
5007 }
5008 // Sort the identifiers to visit based on their name.
5009 llvm::sort(IIs, llvm::deref<std::less<>>());
5010 for (const IdentifierInfo *II : IIs)
5011 for (const Decl *D : SemaRef.IdResolver.decls(II))
5012 GetDeclRef(D);
5013 }
5014
5015 // Write all of the DeclsToCheckForDeferredDiags.
5016 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
5017 GetDeclRef(D);
5018}
5019
5020void ASTWriter::WriteSpecialDeclRecords(Sema &SemaRef) {
5021 ASTContext &Context = SemaRef.Context;
5022
5023 bool isModule = WritingModule != nullptr;
5024
5025 // Write the record containing external, unnamed definitions.
5026 if (!EagerlyDeserializedDecls.empty())
5027 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
5028
5029 if (!ModularCodegenDecls.empty())
5030 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
5031
5032 // Write the record containing tentative definitions.
5033 RecordData TentativeDefinitions;
5035 TentativeDefinitions);
5036 if (!TentativeDefinitions.empty())
5037 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
5038
5039 // Write the record containing unused file scoped decls.
5040 RecordData UnusedFileScopedDecls;
5041 if (!isModule)
5043 UnusedFileScopedDecls);
5044 if (!UnusedFileScopedDecls.empty())
5045 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
5046
5047 // Write the record containing ext_vector type names.
5048 RecordData ExtVectorDecls;
5049 AddLazyVectorEmiitedDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
5050 if (!ExtVectorDecls.empty())
5051 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
5052
5053 // Write the record containing VTable uses information.
5054 RecordData VTableUses;
5055 if (!SemaRef.VTableUses.empty()) {
5056 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
5057 CXXRecordDecl *D = SemaRef.VTableUses[I].first;
5058 if (!wasDeclEmitted(D))
5059 continue;
5060
5061 AddDeclRef(D, VTableUses);
5062 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
5063 VTableUses.push_back(SemaRef.VTablesUsed[D]);
5064 }
5065 Stream.EmitRecord(VTABLE_USES, VTableUses);
5066 }
5067
5068 // Write the record containing potentially unused local typedefs.
5069 RecordData UnusedLocalTypedefNameCandidates;
5070 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
5071 AddEmittedDeclRef(TD, UnusedLocalTypedefNameCandidates);
5072 if (!UnusedLocalTypedefNameCandidates.empty())
5073 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
5074 UnusedLocalTypedefNameCandidates);
5075
5076 // Write the record containing pending implicit instantiations.
5077 RecordData PendingInstantiations;
5078 for (const auto &I : SemaRef.PendingInstantiations) {
5079 if (!wasDeclEmitted(I.first))
5080 continue;
5081
5082 AddDeclRef(I.first, PendingInstantiations);
5083 AddSourceLocation(I.second, PendingInstantiations);
5084 }
5085 if (!PendingInstantiations.empty())
5086 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
5087
5088 // Write the record containing declaration references of Sema.
5089 RecordData SemaDeclRefs;
5090 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
5091 auto AddEmittedDeclRefOrZero = [this, &SemaDeclRefs](Decl *D) {
5092 if (!D || !wasDeclEmitted(D))
5093 SemaDeclRefs.push_back(0);
5094 else
5095 AddDeclRef(D, SemaDeclRefs);
5096 };
5097
5098 AddEmittedDeclRefOrZero(SemaRef.getStdNamespace());
5099 AddEmittedDeclRefOrZero(SemaRef.getStdBadAlloc());
5100 AddEmittedDeclRefOrZero(SemaRef.getStdAlignValT());
5101 }
5102 if (!SemaDeclRefs.empty())
5103 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
5104
5105 // Write the record containing decls to be checked for deferred diags.
5106 RecordData DeclsToCheckForDeferredDiags;
5107 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
5108 if (wasDeclEmitted(D))
5109 AddDeclRef(D, DeclsToCheckForDeferredDiags);
5110 if (!DeclsToCheckForDeferredDiags.empty())
5111 Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
5112 DeclsToCheckForDeferredDiags);
5113
5114 // Write the record containing CUDA-specific declaration references.
5115 RecordData CUDASpecialDeclRefs;
5116 if (auto *CudaCallDecl = Context.getcudaConfigureCallDecl();
5117 CudaCallDecl && wasDeclEmitted(CudaCallDecl)) {
5118 AddDeclRef(CudaCallDecl, CUDASpecialDeclRefs);
5119 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
5120 }
5121
5122 // Write the delegating constructors.
5123 RecordData DelegatingCtorDecls;
5124 if (!isModule)
5126 DelegatingCtorDecls);
5127 if (!DelegatingCtorDecls.empty())
5128 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
5129
5130 // Write the known namespaces.
5131 RecordData KnownNamespaces;
5132 for (const auto &I : SemaRef.KnownNamespaces) {
5133 if (!I.second && wasDeclEmitted(I.first))
5134 AddDeclRef(I.first, KnownNamespaces);
5135 }
5136 if (!KnownNamespaces.empty())
5137 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
5138
5139 // Write the undefined internal functions and variables, and inline functions.
5140 RecordData UndefinedButUsed;
5142 SemaRef.getUndefinedButUsed(Undefined);
5143 for (const auto &I : Undefined) {
5144 if (!wasDeclEmitted(I.first))
5145 continue;
5146
5147 AddDeclRef(I.first, UndefinedButUsed);
5148 AddSourceLocation(I.second, UndefinedButUsed);
5149 }
5150 if (!UndefinedButUsed.empty())
5151 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
5152
5153 // Write all delete-expressions that we would like to
5154 // analyze later in AST.
5155 RecordData DeleteExprsToAnalyze;
5156 if (!isModule) {
5157 for (const auto &DeleteExprsInfo :
5159 if (!wasDeclEmitted(DeleteExprsInfo.first))
5160 continue;
5161
5162 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
5163 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
5164 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
5165 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
5166 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
5167 }
5168 }
5169 }
5170 if (!DeleteExprsToAnalyze.empty())
5171 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
5172}
5173
5174ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
5175 Module *WritingModule) {
5176 using namespace llvm;
5177
5178 bool isModule = WritingModule != nullptr;
5179
5180 // Make sure that the AST reader knows to finalize itself.
5181 if (Chain)
5182 Chain->finalizeForWriting();
5183
5184 ASTContext &Context = SemaRef.Context;
5185 Preprocessor &PP = SemaRef.PP;
5186
5187 // This needs to be done very early, since everything that writes
5188 // SourceLocations or FileIDs depends on it.
5189 computeNonAffectingInputFiles();
5190
5191 writeUnhashedControlBlock(PP, Context);
5192
5193 // Write the set of weak, undeclared identifiers. We always write the
5194 // entire table, since later PCH files in a PCH chain are only interested in
5195 // the results at the end of the chain.
5196 RecordData WeakUndeclaredIdentifiers;
5197 for (const auto &WeakUndeclaredIdentifierList :
5198 SemaRef.WeakUndeclaredIdentifiers) {
5199 const IdentifierInfo *const II = WeakUndeclaredIdentifierList.first;
5200 for (const auto &WI : WeakUndeclaredIdentifierList.second) {
5201 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
5202 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
5203 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
5204 }
5205 }
5206
5207 PrepareWritingSpecialDecls(SemaRef);
5208
5209 // Write the control block
5210 WriteControlBlock(PP, Context, isysroot);
5211
5212 // Write the remaining AST contents.
5213 Stream.FlushToWord();
5214 ASTBlockRange.first = Stream.GetCurrentBitNo() >> 3;
5215 Stream.EnterSubblock(AST_BLOCK_ID, 5);
5216 ASTBlockStartOffset = Stream.GetCurrentBitNo();
5217
5218 // This is so that older clang versions, before the introduction
5219 // of the control block, can read and reject the newer PCH format.
5220 {
5222 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
5223 }
5224
5225 // For method pool in the module, if it contains an entry for a selector,
5226 // the entry should be complete, containing everything introduced by that
5227 // module and all modules it imports. It's possible that the entry is out of
5228 // date, so we need to pull in the new content here.
5229
5230 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
5231 // safe, we copy all selectors out.
5233 for (auto &SelectorAndID : SelectorIDs)
5234 AllSelectors.push_back(SelectorAndID.first);
5235 for (auto &Selector : AllSelectors)
5237
5238 // Form the record of special types.
5239 RecordData SpecialTypes;
5240 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
5241 AddTypeRef(Context.getFILEType(), SpecialTypes);
5242 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
5243 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
5244 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
5245 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
5246 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
5247 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
5248
5249 if (Chain) {
5250 // Write the mapping information describing our module dependencies and how
5251 // each of those modules were mapped into our own offset/ID space, so that
5252 // the reader can build the appropriate mapping to its own offset/ID space.
5253 // The map consists solely of a blob with the following format:
5254 // *(module-kind:i8
5255 // module-name-len:i16 module-name:len*i8
5256 // source-location-offset:i32
5257 // identifier-id:i32
5258 // preprocessed-entity-id:i32
5259 // macro-definition-id:i32
5260 // submodule-id:i32
5261 // selector-id:i32
5262 // declaration-id:i32
5263 // c++-base-specifiers-id:i32
5264 // type-id:i32)
5265 //
5266 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule,
5267 // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the
5268 // module name. Otherwise, it is the module file name.
5269 auto Abbrev = std::make_shared<BitCodeAbbrev>();
5270 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
5271 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
5272 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
5273 SmallString<2048> Buffer;
5274 {
5275 llvm::raw_svector_ostream Out(Buffer);
5276 for (ModuleFile &M : Chain->ModuleMgr) {
5277 using namespace llvm::support;
5278
5279 endian::Writer LE(Out, llvm::endianness::little);
5280 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
5281 StringRef Name = M.isModule() ? M.ModuleName : M.FileName;
5282 LE.write<uint16_t>(Name.size());
5283 Out.write(Name.data(), Name.size());
5284
5285 // Note: if a base ID was uint max, it would not be possible to load
5286 // another module after it or have more than one entity inside it.
5287 uint32_t None = std::numeric_limits<uint32_t>::max();
5288
5289 auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) {
5290 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
5291 if (ShouldWrite)
5292 LE.write<uint32_t>(BaseID);
5293 else
5294 LE.write<uint32_t>(None);
5295 };
5296
5297 // These values should be unique within a chain, since they will be read
5298 // as keys into ContinuousRangeMaps.
5299 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
5300 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
5301 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
5302 writeBaseIDOrNone(M.BasePreprocessedEntityID,
5304 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
5305 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
5306 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
5307 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
5308 }
5309 }
5310 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
5311 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
5312 Buffer.data(), Buffer.size());
5313 }
5314
5315 WriteDeclAndTypes(Context);
5316
5317 WriteFileDeclIDsMap();
5318 WriteSourceManagerBlock(Context.getSourceManager(), PP);
5319 WriteComments();
5320 WritePreprocessor(PP, isModule);
5321 WriteHeaderSearch(PP.getHeaderSearchInfo());
5322 WriteSelectors(SemaRef);
5323 WriteReferencedSelectorsPool(SemaRef);
5324 WriteLateParsedTemplates(SemaRef);
5325 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
5326 WriteFPPragmaOptions(SemaRef.CurFPFeatureOverrides());
5327 WriteOpenCLExtensions(SemaRef);
5328 WriteCUDAPragmas(SemaRef);
5329
5330 // If we're emitting a module, write out the submodule information.
5331 if (WritingModule)
5332 WriteSubmodules(WritingModule);
5333
5334 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
5335
5336 WriteSpecialDeclRecords(SemaRef);
5337
5338 // Write the record containing weak undeclared identifiers.
5339 if (!WeakUndeclaredIdentifiers.empty())
5340 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
5341 WeakUndeclaredIdentifiers);
5342
5343 if (!WritingModule) {
5344 // Write the submodules that were imported, if any.
5345 struct ModuleInfo {
5346 uint64_t ID;
5347 Module *M;
5348 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
5349 };
5351 for (const auto *I : Context.local_imports()) {
5352 assert(SubmoduleIDs.contains(I->getImportedModule()));
5353 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
5354 I->getImportedModule()));
5355 }
5356
5357 if (!Imports.empty()) {
5358 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
5359 return A.ID < B.ID;
5360 };
5361 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
5362 return A.ID == B.ID;
5363 };
5364
5365 // Sort and deduplicate module IDs.
5366 llvm::sort(Imports, Cmp);
5367 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
5368 Imports.end());
5369
5370 RecordData ImportedModules;
5371 for (const auto &Import : Imports) {
5372 ImportedModules.push_back(Import.ID);
5373 // FIXME: If the module has macros imported then later has declarations
5374 // imported, this location won't be the right one as a location for the
5375 // declaration imports.
5376 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
5377 }
5378
5379 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5380 }
5381 }
5382
5383 WriteObjCCategories();
5384 if(!WritingModule) {
5385 WriteOptimizePragmaOptions(SemaRef);
5386 WriteMSStructPragmaOptions(SemaRef);
5387 WriteMSPointersToMembersPragmaOptions(SemaRef);
5388 }
5389 WritePackPragmaOptions(SemaRef);
5390 WriteFloatControlPragmaOptions(SemaRef);
5391
5392 // Some simple statistics
5393 RecordData::value_type Record[] = {
5394 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
5395 Stream.EmitRecord(STATISTICS, Record);
5396 Stream.ExitBlock();
5397 Stream.FlushToWord();
5398 ASTBlockRange.second = Stream.GetCurrentBitNo() >> 3;
5399
5400 // Write the module file extension blocks.
5401 for (const auto &ExtWriter : ModuleFileExtensionWriters)
5402 WriteModuleFileExtension(SemaRef, *ExtWriter);
5403
5404 return backpatchSignature();
5405}
5406
5407void ASTWriter::EnteringModulePurview() {
5408 // In C++20 named modules, all entities before entering the module purview
5409 // lives in the GMF.
5410 if (GeneratingReducedBMI)
5411 DeclUpdatesFromGMF.swap(DeclUpdates);
5412}
5413
5414// Add update records for all mangling numbers and static local numbers.
5415// These aren't really update records, but this is a convenient way of
5416// tagging this rare extra data onto the declarations.
5417void ASTWriter::AddedManglingNumber(const Decl *D, unsigned Number) {
5418 if (D->isFromASTFile())
5419 return;
5420
5421 DeclUpdates[D].push_back(DeclUpdate(UPD_MANGLING_NUMBER, Number));
5422}
5423void ASTWriter::AddedStaticLocalNumbers(const Decl *D, unsigned Number) {
5424 if (D->isFromASTFile())
5425 return;
5426
5427 DeclUpdates[D].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER, Number));
5428}
5429
5430void ASTWriter::AddedAnonymousNamespace(const TranslationUnitDecl *TU,
5431 NamespaceDecl *AnonNamespace) {
5432 // If the translation unit has an anonymous namespace, and we don't already
5433 // have an update block for it, write it as an update block.
5434 // FIXME: Why do we not do this if there's already an update block?
5435 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
5436 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
5437 if (Record.empty())
5438 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
5439 }
5440}
5441
5442void ASTWriter::WriteDeclAndTypes(ASTContext &Context) {
5443 // Keep writing types, declarations, and declaration update records
5444 // until we've emitted all of them.
5445 RecordData DeclUpdatesOffsetsRecord;
5446 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
5447 DeclTypesBlockStartOffset = Stream.GetCurrentBitNo();
5448 WriteTypeAbbrevs();
5449 WriteDeclAbbrevs();
5450 do {
5451 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
5452 while (!DeclTypesToEmit.empty()) {
5453 DeclOrType DOT = DeclTypesToEmit.front();
5454 DeclTypesToEmit.pop();
5455 if (DOT.isType())
5456 WriteType(DOT.getType());
5457 else
5458 WriteDecl(Context, DOT.getDecl());
5459 }
5460 } while (!DeclUpdates.empty());
5461
5462 DoneWritingDeclsAndTypes = true;
5463
5464 // DelayedNamespace is only meaningful in reduced BMI.
5465 // See the comments of DelayedNamespace for details.
5466 assert(DelayedNamespace.empty() || GeneratingReducedBMI);
5467 RecordData DelayedNamespaceRecord;
5468 for (NamespaceDecl *NS : DelayedNamespace) {
5469 uint64_t LexicalOffset = WriteDeclContextLexicalBlock(Context, NS);
5470 uint64_t VisibleOffset = WriteDeclContextVisibleBlock(Context, NS);
5471
5472 // Write the offset relative to current block.
5473 if (LexicalOffset)
5474 LexicalOffset -= DeclTypesBlockStartOffset;
5475
5476 if (VisibleOffset)
5477 VisibleOffset -= DeclTypesBlockStartOffset;
5478
5479 AddDeclRef(NS, DelayedNamespaceRecord);
5480 DelayedNamespaceRecord.push_back(LexicalOffset);
5481 DelayedNamespaceRecord.push_back(VisibleOffset);
5482 }
5483
5484 // The process of writing lexical and visible block for delayed namespace
5485 // shouldn't introduce any new decls, types or update to emit.
5486 assert(DeclTypesToEmit.empty());
5487 assert(DeclUpdates.empty());
5488
5489 Stream.ExitBlock();
5490
5491 // These things can only be done once we've written out decls and types.
5492 WriteTypeDeclOffsets();
5493 if (!DeclUpdatesOffsetsRecord.empty())
5494 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
5495
5496 if (!DelayedNamespaceRecord.empty())
5498 DelayedNamespaceRecord);
5499
5500 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5501 // Create a lexical update block containing all of the declarations in the
5502 // translation unit that do not come from other AST files.
5503 SmallVector<DeclID, 128> NewGlobalKindDeclPairs;
5504 for (const auto *D : TU->noload_decls()) {
5505 if (D->isFromASTFile())
5506 continue;
5507
5508 // In reduced BMI, skip unreached declarations.
5509 if (!wasDeclEmitted(D))
5510 continue;
5511
5512 NewGlobalKindDeclPairs.push_back(D->getKind());
5513 NewGlobalKindDeclPairs.push_back(GetDeclRef(D).get());
5514 }
5515
5516 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
5517 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
5518 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
5519 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
5520
5521 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
5522 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
5523 bytes(NewGlobalKindDeclPairs));
5524
5525 Abv = std::make_shared<llvm::BitCodeAbbrev>();
5526 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
5527 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5528 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
5529 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
5530
5531 // And a visible updates block for the translation unit.
5532 WriteDeclContextVisibleUpdate(TU);
5533
5534 // If we have any extern "C" names, write out a visible update for them.
5535 if (Context.ExternCContext)
5536 WriteDeclContextVisibleUpdate(Context.ExternCContext);
5537
5538 // Write the visible updates to DeclContexts.
5539 for (auto *DC : UpdatedDeclContexts)
5540 WriteDeclContextVisibleUpdate(DC);
5541}
5542
5543void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
5544 if (DeclUpdates.empty())
5545 return;
5546
5547 DeclUpdateMap LocalUpdates;
5548 LocalUpdates.swap(DeclUpdates);
5549
5550 for (auto &DeclUpdate : LocalUpdates) {
5551 const Decl *D = DeclUpdate.first;
5552
5553 bool HasUpdatedBody = false;
5554 bool HasAddedVarDefinition = false;
5557 for (auto &Update : DeclUpdate.second) {
5559
5560 // An updated body is emitted last, so that the reader doesn't need
5561 // to skip over the lazy body to reach statements for other records.
5563 HasUpdatedBody = true;
5564 else if (Kind == UPD_CXX_ADDED_VAR_DEFINITION)
5565 HasAddedVarDefinition = true;
5566 else
5567 Record.push_back(Kind);
5568
5569 switch (Kind) {
5573 assert(Update.getDecl() && "no decl to add?");
5574 Record.AddDeclRef(Update.getDecl());
5575 break;
5576
5579 break;
5580
5582 // FIXME: Do we need to also save the template specialization kind here?
5583 Record.AddSourceLocation(Update.getLoc());
5584 break;
5585
5587 Record.AddStmt(const_cast<Expr *>(
5588 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
5589 break;
5590
5592 Record.AddStmt(
5593 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5594 break;
5595
5597 auto *RD = cast<CXXRecordDecl>(D);
5598 UpdatedDeclContexts.insert(RD->getPrimaryContext());
5599 Record.push_back(RD->isParamDestroyedInCallee());
5600 Record.push_back(llvm::to_underlying(RD->getArgPassingRestrictions()));
5601 Record.AddCXXDefinitionData(RD);
5602 Record.AddOffset(WriteDeclContextLexicalBlock(
5603 *Context, const_cast<CXXRecordDecl *>(RD)));
5604
5605 // This state is sometimes updated by template instantiation, when we
5606 // switch from the specialization referring to the template declaration
5607 // to it referring to the template definition.
5608 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5609 Record.push_back(MSInfo->getTemplateSpecializationKind());
5610 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
5611 } else {
5612 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5613 Record.push_back(Spec->getTemplateSpecializationKind());
5614 Record.AddSourceLocation(Spec->getPointOfInstantiation());
5615
5616 // The instantiation might have been resolved to a partial
5617 // specialization. If so, record which one.
5618 auto From = Spec->getInstantiatedFrom();
5619 if (auto PartialSpec =
5620 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5621 Record.push_back(true);
5622 Record.AddDeclRef(PartialSpec);
5623 Record.AddTemplateArgumentList(
5624 &Spec->getTemplateInstantiationArgs());
5625 } else {
5626 Record.push_back(false);
5627 }
5628 }
5629 Record.push_back(llvm::to_underlying(RD->getTagKind()));
5630 Record.AddSourceLocation(RD->getLocation());
5631 Record.AddSourceLocation(RD->getBeginLoc());
5632 Record.AddSourceRange(RD->getBraceRange());
5633
5634 // Instantiation may change attributes; write them all out afresh.
5635 Record.push_back(D->hasAttrs());
5636 if (D->hasAttrs())
5637 Record.AddAttributes(D->getAttrs());
5638
5639 // FIXME: Ensure we don't get here for explicit instantiations.
5640 break;
5641 }
5642
5644 Record.AddDeclRef(Update.getDecl());
5645 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
5646 break;
5647
5649 auto prototype =
5650 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
5651 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
5652 break;
5653 }
5654
5656 Record.push_back(GetOrCreateTypeID(Update.getType()));
5657 break;
5658
5660 break;
5661
5664 Record.push_back(Update.getNumber());
5665 break;
5666
5668 Record.AddSourceRange(
5669 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5670 break;
5671
5673 auto *A = D->getAttr<OMPAllocateDeclAttr>();
5674 Record.push_back(A->getAllocatorType());
5675 Record.AddStmt(A->getAllocator());
5676 Record.AddStmt(A->getAlignment());
5677 Record.AddSourceRange(A->getRange());
5678 break;
5679 }
5680
5682 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
5683 Record.AddSourceRange(
5684 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5685 break;
5686
5687 case UPD_DECL_EXPORTED:
5688 Record.push_back(getSubmoduleID(Update.getModule()));
5689 break;
5690
5692 Record.AddAttributes(llvm::ArrayRef(Update.getAttr()));
5693 break;
5694 }
5695 }
5696
5697 // Add a trailing update record, if any. These must go last because we
5698 // lazily load their attached statement.
5699 if (!GeneratingReducedBMI || !CanElideDeclDef(D)) {
5700 if (HasUpdatedBody) {
5701 const auto *Def = cast<FunctionDecl>(D);
5703 Record.push_back(Def->isInlined());
5704 Record.AddSourceLocation(Def->getInnerLocStart());
5705 Record.AddFunctionDefinition(Def);
5706 } else if (HasAddedVarDefinition) {
5707 const auto *VD = cast<VarDecl>(D);
5709 Record.push_back(VD->isInline());
5710 Record.push_back(VD->isInlineSpecified());
5711 Record.AddVarDeclInit(VD);
5712 }
5713 }
5714
5715 AddDeclRef(D, OffsetsRecord);
5716 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5717 }
5718}
5719
5722 uint32_t Raw = Sema::AlignPackInfo::getRawEncoding(Info);
5723 Record.push_back(Raw);
5724}
5725
5726FileID ASTWriter::getAdjustedFileID(FileID FID) const {
5727 if (FID.isInvalid() || PP->getSourceManager().isLoadedFileID(FID) ||
5728 NonAffectingFileIDs.empty())
5729 return FID;
5730 auto It = llvm::lower_bound(NonAffectingFileIDs, FID);
5731 unsigned Idx = std::distance(NonAffectingFileIDs.begin(), It);
5732 unsigned Offset = NonAffectingFileIDAdjustments[Idx];
5733 return FileID::get(FID.getOpaqueValue() - Offset);
5734}
5735
5736unsigned ASTWriter::getAdjustedNumCreatedFIDs(FileID FID) const {
5737 unsigned NumCreatedFIDs = PP->getSourceManager()
5738 .getLocalSLocEntry(FID.ID)
5739 .getFile()
5740 .NumCreatedFIDs;
5741
5742 unsigned AdjustedNumCreatedFIDs = 0;
5743 for (unsigned I = FID.ID, N = I + NumCreatedFIDs; I != N; ++I)
5744 if (IsSLocAffecting[I])
5745 ++AdjustedNumCreatedFIDs;
5746 return AdjustedNumCreatedFIDs;
5747}
5748
5749SourceLocation ASTWriter::getAdjustedLocation(SourceLocation Loc) const {
5750 if (Loc.isInvalid())
5751 return Loc;
5752 return Loc.getLocWithOffset(-getAdjustment(Loc.getOffset()));
5753}
5754
5755SourceRange ASTWriter::getAdjustedRange(SourceRange Range) const {
5756 return SourceRange(getAdjustedLocation(Range.getBegin()),
5757 getAdjustedLocation(Range.getEnd()));
5758}
5759
5761ASTWriter::getAdjustedOffset(SourceLocation::UIntTy Offset) const {
5762 return Offset - getAdjustment(Offset);
5763}
5764
5766ASTWriter::getAdjustment(SourceLocation::UIntTy Offset) const {
5767 if (NonAffectingRanges.empty())
5768 return 0;
5769
5770 if (PP->getSourceManager().isLoadedOffset(Offset))
5771 return 0;
5772
5773 if (Offset > NonAffectingRanges.back().getEnd().getOffset())
5774 return NonAffectingOffsetAdjustments.back();
5775
5776 if (Offset < NonAffectingRanges.front().getBegin().getOffset())
5777 return 0;
5778
5779 auto Contains = [](const SourceRange &Range, SourceLocation::UIntTy Offset) {
5780 return Range.getEnd().getOffset() < Offset;
5781 };
5782
5783 auto It = llvm::lower_bound(NonAffectingRanges, Offset, Contains);
5784 unsigned Idx = std::distance(NonAffectingRanges.begin(), It);
5785 return NonAffectingOffsetAdjustments[Idx];
5786}
5787
5789 Record.push_back(getAdjustedFileID(FID).getOpaqueValue());
5790}
5791
5794 Loc = getAdjustedLocation(Loc);
5795 Record.push_back(SourceLocationEncoding::encode(Loc, Seq));
5796}
5797
5800 AddSourceLocation(Range.getBegin(), Record, Seq);
5801 AddSourceLocation(Range.getEnd(), Record, Seq);
5802}
5803
5804void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5805 AddAPInt(Value.bitcastToAPInt());
5806}
5807
5809 Record.push_back(getIdentifierRef(II));
5810}
5811
5813 if (!II)
5814 return 0;
5815
5816 IdentID &ID = IdentifierIDs[II];
5817 if (ID == 0)
5818 ID = NextIdentID++;
5819 return ID;
5820}
5821
5823 // Don't emit builtin macros like __LINE__ to the AST file unless they
5824 // have been redefined by the header (in which case they are not
5825 // isBuiltinMacro).
5826 if (!MI || MI->isBuiltinMacro())
5827 return 0;
5828
5829 MacroID &ID = MacroIDs[MI];
5830 if (ID == 0) {
5831 ID = NextMacroID++;
5832 MacroInfoToEmitData Info = { Name, MI, ID };
5833 MacroInfosToEmit.push_back(Info);
5834 }
5835 return ID;
5836}
5837
5839 if (!MI || MI->isBuiltinMacro())
5840 return 0;
5841
5842 assert(MacroIDs.contains(MI) && "Macro not emitted!");
5843 return MacroIDs[MI];
5844}
5845
5847 return IdentMacroDirectivesOffsetMap.lookup(Name);
5848}
5849
5851 Record->push_back(Writer->getSelectorRef(SelRef));
5852}
5853
5855 if (Sel.getAsOpaquePtr() == nullptr) {
5856 return 0;
5857 }
5858
5859 SelectorID SID = SelectorIDs[Sel];
5860 if (SID == 0 && Chain) {
5861 // This might trigger a ReadSelector callback, which will set the ID for
5862 // this selector.
5863 Chain->LoadSelector(Sel);
5864 SID = SelectorIDs[Sel];
5865 }
5866 if (SID == 0) {
5867 SID = NextSelectorID++;
5868 SelectorIDs[Sel] = SID;
5869 }
5870 return SID;
5871}
5872
5874 AddDeclRef(Temp->getDestructor());
5875}
5876
5879 switch (Kind) {
5881 AddStmt(Arg.getAsExpr());
5882 break;
5885 break;
5889 break;
5894 break;
5901 // FIXME: Is this right?
5902 break;
5903 }
5904}
5905
5908
5910 bool InfoHasSameExpr
5911 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5912 Record->push_back(InfoHasSameExpr);
5913 if (InfoHasSameExpr)
5914 return; // Avoid storing the same expr twice.
5915 }
5917}
5918
5920 if (!TInfo) {
5922 return;
5923 }
5924
5925 AddTypeRef(TInfo->getType());
5926 AddTypeLoc(TInfo->getTypeLoc());
5927}
5928
5930 LocSeq::State Seq(OuterSeq);
5931 TypeLocWriter TLW(*this, Seq);
5932 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5933 TLW.Visit(TL);
5934}
5935
5937 Record.push_back(GetOrCreateTypeID(T));
5938}
5939
5941 assert(Context);
5942 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5943 if (T.isNull())
5944 return TypeIdx();
5945 assert(!T.getLocalFastQualifiers());
5946
5947 TypeIdx &Idx = TypeIdxs[T];
5948 if (Idx.getIndex() == 0) {
5949 if (DoneWritingDeclsAndTypes) {
5950 assert(0 && "New type seen after serializing all the types to emit!");
5951 return TypeIdx();
5952 }
5953
5954 // We haven't seen this type before. Assign it a new ID and put it
5955 // into the queue of types to emit.
5956 Idx = TypeIdx(NextTypeID++);
5957 DeclTypesToEmit.push(T);
5958 }
5959 return Idx;
5960 });
5961}
5962
5964 assert(Context);
5965 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5966 if (T.isNull())
5967 return TypeIdx();
5968 assert(!T.getLocalFastQualifiers());
5969
5970 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5971 assert(I != TypeIdxs.end() && "Type not emitted!");
5972 return I->second;
5973 });
5974}
5975
5977 if (!wasDeclEmitted(D))
5978 return;
5979
5980 Record.push_back(GetDeclRef(D).get());
5981}
5982
5984 Record.push_back(GetDeclRef(D).get());
5985}
5986
5988 assert(WritingAST && "Cannot request a declaration ID before AST writing");
5989
5990 if (!D) {
5991 return LocalDeclID();
5992 }
5993
5994 // If the DeclUpdate from the GMF gets touched, emit it.
5995 if (auto *Iter = DeclUpdatesFromGMF.find(D);
5996 Iter != DeclUpdatesFromGMF.end()) {
5997 for (DeclUpdate &Update : Iter->second)
5998 DeclUpdates[D].push_back(Update);
5999 DeclUpdatesFromGMF.erase(Iter);
6000 }
6001
6002 // If D comes from an AST file, its declaration ID is already known and
6003 // fixed.
6004 if (D->isFromASTFile())
6005 return LocalDeclID(D->getGlobalID());
6006
6007 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
6008 LocalDeclID &ID = DeclIDs[D];
6009 if (ID.isInvalid()) {
6010 if (DoneWritingDeclsAndTypes) {
6011 assert(0 && "New decl seen after serializing all the decls to emit!");
6012 return LocalDeclID();
6013 }
6014
6015 // We haven't seen this declaration before. Give it a new ID and
6016 // enqueue it in the list of declarations to emit.
6017 ID = NextDeclID++;
6018 DeclTypesToEmit.push(const_cast<Decl *>(D));
6019 }
6020
6021 return ID;
6022}
6023
6025 if (!D)
6026 return LocalDeclID();
6027
6028 // If D comes from an AST file, its declaration ID is already known and
6029 // fixed.
6030 if (D->isFromASTFile())
6031 return LocalDeclID(D->getGlobalID());
6032
6033 assert(DeclIDs.contains(D) && "Declaration not emitted!");
6034 return DeclIDs[D];
6035}
6036
6037bool ASTWriter::wasDeclEmitted(const Decl *D) const {
6038 assert(D);
6039
6040 assert(DoneWritingDeclsAndTypes &&
6041 "wasDeclEmitted should only be called after writing declarations");
6042
6043 if (D->isFromASTFile())
6044 return true;
6045
6046 bool Emitted = DeclIDs.contains(D);
6047 assert((Emitted || GeneratingReducedBMI) &&
6048 "The declaration can only be omitted in reduced BMI.");
6049 return Emitted;
6050}
6051
6052void ASTWriter::associateDeclWithFile(const Decl *D, LocalDeclID ID) {
6053 assert(ID.isValid());
6054 assert(D);
6055
6056 SourceLocation Loc = D->getLocation();
6057 if (Loc.isInvalid())
6058 return;
6059
6060 // We only keep track of the file-level declarations of each file.
6062 return;
6063 // FIXME: ParmVarDecls that are part of a function type of a parameter of
6064 // a function/objc method, should not have TU as lexical context.
6065 // TemplateTemplateParmDecls that are part of an alias template, should not
6066 // have TU as lexical context.
6067 if (isa<ParmVarDecl, TemplateTemplateParmDecl>(D))
6068 return;
6069
6070 SourceManager &SM = Context->getSourceManager();
6071 SourceLocation FileLoc = SM.getFileLoc(Loc);
6072 assert(SM.isLocalSourceLocation(FileLoc));
6073 FileID FID;
6074 unsigned Offset;
6075 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
6076 if (FID.isInvalid())
6077 return;
6078 assert(SM.getSLocEntry(FID).isFile());
6079 assert(IsSLocAffecting[FID.ID]);
6080
6081 std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
6082 if (!Info)
6083 Info = std::make_unique<DeclIDInFileInfo>();
6084
6085 std::pair<unsigned, LocalDeclID> LocDecl(Offset, ID);
6086 LocDeclIDsTy &Decls = Info->DeclIDs;
6087 Decls.push_back(LocDecl);
6088}
6089
6092 "expected an anonymous declaration");
6093
6094 // Number the anonymous declarations within this context, if we've not
6095 // already done so.
6096 auto It = AnonymousDeclarationNumbers.find(D);
6097 if (It == AnonymousDeclarationNumbers.end()) {
6098 auto *DC = D->getLexicalDeclContext();
6099 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
6100 AnonymousDeclarationNumbers[ND] = Number;
6101 });
6102
6103 It = AnonymousDeclarationNumbers.find(D);
6104 assert(It != AnonymousDeclarationNumbers.end() &&
6105 "declaration not found within its lexical context");
6106 }
6107
6108 return It->second;
6109}
6110
6112 DeclarationName Name) {
6113 switch (Name.getNameKind()) {
6118 break;
6119
6122 break;
6123
6126 break;
6127
6134 break;
6135 }
6136}
6137
6139 const DeclarationNameInfo &NameInfo) {
6140 AddDeclarationName(NameInfo.getName());
6141 AddSourceLocation(NameInfo.getLoc());
6142 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
6143}
6144
6147 Record->push_back(Info.NumTemplParamLists);
6148 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
6150}
6151
6153 // Nested name specifiers usually aren't too long. I think that 8 would
6154 // typically accommodate the vast majority.
6156
6157 // Push each of the nested-name-specifiers's onto a stack for
6158 // serialization in reverse order.
6159 while (NNS) {
6160 NestedNames.push_back(NNS);
6161 NNS = NNS.getPrefix();
6162 }
6163
6164 Record->push_back(NestedNames.size());
6165 while(!NestedNames.empty()) {
6166 NNS = NestedNames.pop_back_val();
6169 Record->push_back(Kind);
6170 switch (Kind) {
6174 break;
6175
6179 break;
6180
6184 break;
6185
6189 AddTypeRef(NNS.getTypeLoc().getType());
6190 AddTypeLoc(NNS.getTypeLoc());
6192 break;
6193
6196 break;
6197
6201 break;
6202 }
6203 }
6204}
6205
6207 const TemplateParameterList *TemplateParams) {
6208 assert(TemplateParams && "No TemplateParams!");
6209 AddSourceLocation(TemplateParams->getTemplateLoc());
6210 AddSourceLocation(TemplateParams->getLAngleLoc());
6211 AddSourceLocation(TemplateParams->getRAngleLoc());
6212
6213 Record->push_back(TemplateParams->size());
6214 for (const auto &P : *TemplateParams)
6215 AddDeclRef(P);
6216 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
6217 Record->push_back(true);
6218 AddStmt(const_cast<Expr*>(RequiresClause));
6219 } else {
6220 Record->push_back(false);
6221 }
6222}
6223
6224/// Emit a template argument list.
6226 const TemplateArgumentList *TemplateArgs) {
6227 assert(TemplateArgs && "No TemplateArgs!");
6228 Record->push_back(TemplateArgs->size());
6229 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
6230 AddTemplateArgument(TemplateArgs->get(i));
6231}
6232
6234 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
6235 assert(ASTTemplArgList && "No ASTTemplArgList!");
6236 AddSourceLocation(ASTTemplArgList->LAngleLoc);
6237 AddSourceLocation(ASTTemplArgList->RAngleLoc);
6238 Record->push_back(ASTTemplArgList->NumTemplateArgs);
6239 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
6240 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
6241 AddTemplateArgumentLoc(TemplArgs[i]);
6242}
6243
6245 Record->push_back(Set.size());
6247 I = Set.begin(), E = Set.end(); I != E; ++I) {
6248 AddDeclRef(I.getDecl());
6249 Record->push_back(I.getAccess());
6250 }
6251}
6252
6253// FIXME: Move this out of the main ASTRecordWriter interface.
6255 Record->push_back(Base.isVirtual());
6256 Record->push_back(Base.isBaseOfClass());
6257 Record->push_back(Base.getAccessSpecifierAsWritten());
6258 Record->push_back(Base.getInheritConstructors());
6259 AddTypeSourceInfo(Base.getTypeSourceInfo());
6260 AddSourceRange(Base.getSourceRange());
6261 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
6262 : SourceLocation());
6263}
6264
6268 ASTRecordWriter Writer(W, Record);
6269 Writer.push_back(Bases.size());
6270
6271 for (auto &Base : Bases)
6272 Writer.AddCXXBaseSpecifier(Base);
6273
6275}
6276
6277// FIXME: Move this out of the main ASTRecordWriter interface.
6279 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
6280}
6281
6282static uint64_t
6286 ASTRecordWriter Writer(W, Record);
6287 Writer.push_back(CtorInits.size());
6288
6289 for (auto *Init : CtorInits) {
6290 if (Init->isBaseInitializer()) {
6292 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
6293 Writer.push_back(Init->isBaseVirtual());
6294 } else if (Init->isDelegatingInitializer()) {
6296 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
6297 } else if (Init->isMemberInitializer()){
6299 Writer.AddDeclRef(Init->getMember());
6300 } else {
6302 Writer.AddDeclRef(Init->getIndirectMember());
6303 }
6304
6305 Writer.AddSourceLocation(Init->getMemberLocation());
6306 Writer.AddStmt(Init->getInit());
6307 Writer.AddSourceLocation(Init->getLParenLoc());
6308 Writer.AddSourceLocation(Init->getRParenLoc());
6309 Writer.push_back(Init->isWritten());
6310 if (Init->isWritten())
6311 Writer.push_back(Init->getSourceOrder());
6312 }
6313
6315}
6316
6317// FIXME: Move this out of the main ASTRecordWriter interface.
6320 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
6321}
6322
6324 auto &Data = D->data();
6325
6326 Record->push_back(Data.IsLambda);
6327
6328 BitsPacker DefinitionBits;
6329
6330 bool ShouldSkipCheckingODR = shouldSkipCheckingODR(D);
6331 DefinitionBits.addBit(ShouldSkipCheckingODR);
6332
6333#define FIELD(Name, Width, Merge) \
6334 if (!DefinitionBits.canWriteNextNBits(Width)) { \
6335 Record->push_back(DefinitionBits); \
6336 DefinitionBits.reset(0); \
6337 } \
6338 DefinitionBits.addBits(Data.Name, Width);
6339
6340#include "clang/AST/CXXRecordDeclDefinitionBits.def"
6341#undef FIELD
6342
6343 Record->push_back(DefinitionBits);
6344
6345 // We only perform ODR checks for decls not in GMF.
6346 if (!ShouldSkipCheckingODR)
6347 // getODRHash will compute the ODRHash if it has not been previously
6348 // computed.
6349 Record->push_back(D->getODRHash());
6350
6351 bool ModulesDebugInfo =
6352 Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType();
6353 Record->push_back(ModulesDebugInfo);
6354 if (ModulesDebugInfo)
6355 Writer->AddDeclRef(D, Writer->ModularCodegenDecls);
6356
6357 // IsLambda bit is already saved.
6358
6359 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
6360 Record->push_back(Data.ComputedVisibleConversions);
6361 if (Data.ComputedVisibleConversions)
6362 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
6363 // Data.Definition is the owning decl, no need to write it.
6364
6365 if (!Data.IsLambda) {
6366 Record->push_back(Data.NumBases);
6367 if (Data.NumBases > 0)
6368 AddCXXBaseSpecifiers(Data.bases());
6369
6370 // FIXME: Make VBases lazily computed when needed to avoid storing them.
6371 Record->push_back(Data.NumVBases);
6372 if (Data.NumVBases > 0)
6373 AddCXXBaseSpecifiers(Data.vbases());
6374
6375 AddDeclRef(D->getFirstFriend());
6376 } else {
6377 auto &Lambda = D->getLambdaData();
6378
6379 BitsPacker LambdaBits;
6380 LambdaBits.addBits(Lambda.DependencyKind, /*Width=*/2);
6381 LambdaBits.addBit(Lambda.IsGenericLambda);
6382 LambdaBits.addBits(Lambda.CaptureDefault, /*Width=*/2);
6383 LambdaBits.addBits(Lambda.NumCaptures, /*Width=*/15);
6384 LambdaBits.addBit(Lambda.HasKnownInternalLinkage);
6385 Record->push_back(LambdaBits);
6386
6387 Record->push_back(Lambda.NumExplicitCaptures);
6388 Record->push_back(Lambda.ManglingNumber);
6389 Record->push_back(D->getDeviceLambdaManglingNumber());
6390 // The lambda context declaration and index within the context are provided
6391 // separately, so that they can be used for merging.
6392 AddTypeSourceInfo(Lambda.MethodTyInfo);
6393 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
6394 const LambdaCapture &Capture = Lambda.Captures.front()[I];
6396
6397 BitsPacker CaptureBits;
6398 CaptureBits.addBit(Capture.isImplicit());
6399 CaptureBits.addBits(Capture.getCaptureKind(), /*Width=*/3);
6400 Record->push_back(CaptureBits);
6401
6402 switch (Capture.getCaptureKind()) {
6403 case LCK_StarThis:
6404 case LCK_This:
6405 case LCK_VLAType:
6406 break;
6407 case LCK_ByCopy:
6408 case LCK_ByRef:
6409 ValueDecl *Var =
6410 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
6411 AddDeclRef(Var);
6412 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
6413 : SourceLocation());
6414 break;
6415 }
6416 }
6417 }
6418}
6419
6421 const Expr *Init = VD->getInit();
6422 if (!Init) {
6423 push_back(0);
6424 return;
6425 }
6426
6427 uint64_t Val = 1;
6428 if (EvaluatedStmt *ES = VD->getEvaluatedStmt()) {
6429 Val |= (ES->HasConstantInitialization ? 2 : 0);
6430 Val |= (ES->HasConstantDestruction ? 4 : 0);
6432 // If the evaluated result is constant, emit it.
6433 if (Evaluated && (Evaluated->isInt() || Evaluated->isFloat()))
6434 Val |= 8;
6435 }
6436 push_back(Val);
6437 if (Val & 8) {
6439 }
6440
6442}
6443
6444void ASTWriter::ReaderInitialized(ASTReader *Reader) {
6445 assert(Reader && "Cannot remove chain");
6446 assert((!Chain || Chain == Reader) && "Cannot replace chain");
6447 assert(FirstDeclID == NextDeclID &&
6448 FirstTypeID == NextTypeID &&
6449 FirstIdentID == NextIdentID &&
6450 FirstMacroID == NextMacroID &&
6451 FirstSubmoduleID == NextSubmoduleID &&
6452 FirstSelectorID == NextSelectorID &&
6453 "Setting chain after writing has started.");
6454
6455 Chain = Reader;
6456
6457 // Note, this will get called multiple times, once one the reader starts up
6458 // and again each time it's done reading a PCH or module.
6459 FirstDeclID = LocalDeclID(NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls());
6460 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
6461 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
6462 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
6463 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
6464 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
6465 NextDeclID = FirstDeclID;
6466 NextTypeID = FirstTypeID;
6467 NextIdentID = FirstIdentID;
6468 NextMacroID = FirstMacroID;
6469 NextSelectorID = FirstSelectorID;
6470 NextSubmoduleID = FirstSubmoduleID;
6471}
6472
6473void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
6474 // Always keep the highest ID. See \p TypeRead() for more information.
6475 IdentID &StoredID = IdentifierIDs[II];
6476 if (ID > StoredID)
6477 StoredID = ID;
6478}
6479
6480void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
6481 // Always keep the highest ID. See \p TypeRead() for more information.
6482 MacroID &StoredID = MacroIDs[MI];
6483 if (ID > StoredID)
6484 StoredID = ID;
6485}
6486
6487void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
6488 // Always take the highest-numbered type index. This copes with an interesting
6489 // case for chained AST writing where we schedule writing the type and then,
6490 // later, deserialize the type from another AST. In this case, we want to
6491 // keep the higher-numbered entry so that we can properly write it out to
6492 // the AST file.
6493 TypeIdx &StoredIdx = TypeIdxs[T];
6494 if (Idx.getIndex() >= StoredIdx.getIndex())
6495 StoredIdx = Idx;
6496}
6497
6498void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
6499 // Always keep the highest ID. See \p TypeRead() for more information.
6500 SelectorID &StoredID = SelectorIDs[S];
6501 if (ID > StoredID)
6502 StoredID = ID;
6503}
6504
6505void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
6507 assert(!MacroDefinitions.contains(MD));
6508 MacroDefinitions[MD] = ID;
6509}
6510
6511void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
6512 assert(!SubmoduleIDs.contains(Mod));
6513 SubmoduleIDs[Mod] = ID;
6514}
6515
6516void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
6517 if (Chain && Chain->isProcessingUpdateRecords()) return;
6518 assert(D->isCompleteDefinition());
6519 assert(!WritingAST && "Already writing the AST!");
6520 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6521 // We are interested when a PCH decl is modified.
6522 if (RD->isFromASTFile()) {
6523 // A forward reference was mutated into a definition. Rewrite it.
6524 // FIXME: This happens during template instantiation, should we
6525 // have created a new definition decl instead ?
6526 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
6527 "completed a tag from another module but not by instantiation?");
6528 DeclUpdates[RD].push_back(
6530 }
6531 }
6532}
6533
6534static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
6535 if (D->isFromASTFile())
6536 return true;
6537
6538 // The predefined __va_list_tag struct is imported if we imported any decls.
6539 // FIXME: This is a gross hack.
6540 return D == D->getASTContext().getVaListTagDecl();
6541}
6542
6543void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
6544 if (Chain && Chain->isProcessingUpdateRecords()) return;
6545 assert(DC->isLookupContext() &&
6546 "Should not add lookup results to non-lookup contexts!");
6547
6548 // TU is handled elsewhere.
6549 if (isa<TranslationUnitDecl>(DC))
6550 return;
6551
6552 // Namespaces are handled elsewhere, except for template instantiations of
6553 // FunctionTemplateDecls in namespaces. We are interested in cases where the
6554 // local instantiations are added to an imported context. Only happens when
6555 // adding ADL lookup candidates, for example templated friends.
6556 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
6557 !isa<FunctionTemplateDecl>(D))
6558 return;
6559
6560 // We're only interested in cases where a local declaration is added to an
6561 // imported context.
6562 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
6563 return;
6564
6565 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
6566 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
6567 assert(!WritingAST && "Already writing the AST!");
6568 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
6569 // We're adding a visible declaration to a predefined decl context. Ensure
6570 // that we write out all of its lookup results so we don't get a nasty
6571 // surprise when we try to emit its lookup table.
6572 llvm::append_range(DeclsToEmitEvenIfUnreferenced, DC->decls());
6573 }
6574 DeclsToEmitEvenIfUnreferenced.push_back(D);
6575}
6576
6577void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
6578 if (Chain && Chain->isProcessingUpdateRecords()) return;
6579 assert(D->isImplicit());
6580
6581 // We're only interested in cases where a local declaration is added to an
6582 // imported context.
6583 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
6584 return;
6585
6586 if (!isa<CXXMethodDecl>(D))
6587 return;
6588
6589 // A decl coming from PCH was modified.
6590 assert(RD->isCompleteDefinition());
6591 assert(!WritingAST && "Already writing the AST!");
6592 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
6593}
6594
6595void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
6596 if (Chain && Chain->isProcessingUpdateRecords()) return;
6597 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
6598 if (!Chain) return;
6599 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6600 // If we don't already know the exception specification for this redecl
6601 // chain, add an update record for it.
6602 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
6603 ->getType()
6604 ->castAs<FunctionProtoType>()
6605 ->getExceptionSpecType()))
6606 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
6607 });
6608}
6609
6610void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
6611 if (Chain && Chain->isProcessingUpdateRecords()) return;
6612 assert(!WritingAST && "Already writing the AST!");
6613 if (!Chain) return;
6614 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6615 DeclUpdates[D].push_back(
6616 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
6617 });
6618}
6619
6620void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
6621 const FunctionDecl *Delete,
6622 Expr *ThisArg) {
6623 if (Chain && Chain->isProcessingUpdateRecords()) return;
6624 assert(!WritingAST && "Already writing the AST!");
6625 assert(Delete && "Not given an operator delete");
6626 if (!Chain) return;
6627 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
6628 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
6629 });
6630}
6631
6632void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
6633 if (Chain && Chain->isProcessingUpdateRecords()) return;
6634 assert(!WritingAST && "Already writing the AST!");
6635 if (!D->isFromASTFile())
6636 return; // Declaration not imported from PCH.
6637
6638 // Implicit function decl from a PCH was defined.
6639 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6640}
6641
6642void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
6643 if (Chain && Chain->isProcessingUpdateRecords()) return;
6644 assert(!WritingAST && "Already writing the AST!");
6645 if (!D->isFromASTFile())
6646 return;
6647
6648 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
6649}
6650
6651void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
6652 if (Chain && Chain->isProcessingUpdateRecords()) return;
6653 assert(!WritingAST && "Already writing the AST!");
6654 if (!D->isFromASTFile())
6655 return;
6656
6657 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6658}
6659
6660void ASTWriter::InstantiationRequested(const ValueDecl *D) {
6661 if (Chain && Chain->isProcessingUpdateRecords()) return;
6662 assert(!WritingAST && "Already writing the AST!");
6663 if (!D->isFromASTFile())
6664 return;
6665
6666 // Since the actual instantiation is delayed, this really means that we need
6667 // to update the instantiation location.
6668 SourceLocation POI;
6669 if (auto *VD = dyn_cast<VarDecl>(D))
6670 POI = VD->getPointOfInstantiation();
6671 else
6672 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
6673 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
6674}
6675
6676void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
6677 if (Chain && Chain->isProcessingUpdateRecords()) return;
6678 assert(!WritingAST && "Already writing the AST!");
6679 if (!D->isFromASTFile())
6680 return;
6681
6682 DeclUpdates[D].push_back(
6684}
6685
6686void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
6687 assert(!WritingAST && "Already writing the AST!");
6688 if (!D->isFromASTFile())
6689 return;
6690
6691 DeclUpdates[D].push_back(
6693}
6694
6695void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
6696 const ObjCInterfaceDecl *IFD) {
6697 if (Chain && Chain->isProcessingUpdateRecords()) return;
6698 assert(!WritingAST && "Already writing the AST!");
6699 if (!IFD->isFromASTFile())
6700 return; // Declaration not imported from PCH.
6701
6702 assert(IFD->getDefinition() && "Category on a class without a definition?");
6703 ObjCClassesWithCategories.insert(
6704 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
6705}
6706
6707void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
6708 if (Chain && Chain->isProcessingUpdateRecords()) return;
6709 assert(!WritingAST && "Already writing the AST!");
6710
6711 // If there is *any* declaration of the entity that's not from an AST file,
6712 // we can skip writing the update record. We make sure that isUsed() triggers
6713 // completion of the redeclaration chain of the entity.
6714 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
6715 if (IsLocalDecl(Prev))
6716 return;
6717
6718 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
6719}
6720
6721void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
6722 if (Chain && Chain->isProcessingUpdateRecords()) return;
6723 assert(!WritingAST && "Already writing the AST!");
6724 if (!D->isFromASTFile())
6725 return;
6726
6727 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
6728}
6729
6730void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
6731 if (Chain && Chain->isProcessingUpdateRecords()) return;
6732 assert(!WritingAST && "Already writing the AST!");
6733 if (!D->isFromASTFile())
6734 return;
6735
6736 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
6737}
6738
6739void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6740 const Attr *Attr) {
6741 if (Chain && Chain->isProcessingUpdateRecords()) return;
6742 assert(!WritingAST && "Already writing the AST!");
6743 if (!D->isFromASTFile())
6744 return;
6745
6746 DeclUpdates[D].push_back(
6748}
6749
6750void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
6751 if (Chain && Chain->isProcessingUpdateRecords()) return;
6752 assert(!WritingAST && "Already writing the AST!");
6753 assert(!D->isUnconditionallyVisible() && "expected a hidden declaration");
6754 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
6755}
6756
6757void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6758 const RecordDecl *Record) {
6759 if (Chain && Chain->isProcessingUpdateRecords()) return;
6760 assert(!WritingAST && "Already writing the AST!");
6761 if (!Record->isFromASTFile())
6762 return;
6763 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6764}
6765
6766void ASTWriter::AddedCXXTemplateSpecialization(
6768 assert(!WritingAST && "Already writing the AST!");
6769
6770 if (!TD->getFirstDecl()->isFromASTFile())
6771 return;
6772 if (Chain && Chain->isProcessingUpdateRecords())
6773 return;
6774
6775 DeclsToEmitEvenIfUnreferenced.push_back(D);
6776}
6777
6778void ASTWriter::AddedCXXTemplateSpecialization(
6779 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6780 assert(!WritingAST && "Already writing the AST!");
6781
6782 if (!TD->getFirstDecl()->isFromASTFile())
6783 return;
6784 if (Chain && Chain->isProcessingUpdateRecords())
6785 return;
6786
6787 DeclsToEmitEvenIfUnreferenced.push_back(D);
6788}
6789
6790void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6791 const FunctionDecl *D) {
6792 assert(!WritingAST && "Already writing the AST!");
6793
6794 if (!TD->getFirstDecl()->isFromASTFile())
6795 return;
6796 if (Chain && Chain->isProcessingUpdateRecords())
6797 return;
6798
6799 DeclsToEmitEvenIfUnreferenced.push_back(D);
6800}
6801
6802//===----------------------------------------------------------------------===//
6803//// OMPClause Serialization
6804////===----------------------------------------------------------------------===//
6805
6806namespace {
6807
6808class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
6810
6811public:
6812 OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
6813#define GEN_CLANG_CLAUSE_CLASS
6814#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
6815#include "llvm/Frontend/OpenMP/OMP.inc"
6816 void writeClause(OMPClause *C);
6817 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
6818 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
6819};
6820
6821}
6822
6824 OMPClauseWriter(*this).writeClause(C);
6825}
6826
6827void OMPClauseWriter::writeClause(OMPClause *C) {
6828 Record.push_back(unsigned(C->getClauseKind()));
6829 Visit(C);
6830 Record.AddSourceLocation(C->getBeginLoc());
6831 Record.AddSourceLocation(C->getEndLoc());
6832}
6833
6834void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
6835 Record.push_back(uint64_t(C->getCaptureRegion()));
6836 Record.AddStmt(C->getPreInitStmt());
6837}
6838
6839void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6840 VisitOMPClauseWithPreInit(C);
6841 Record.AddStmt(C->getPostUpdateExpr());
6842}
6843
6844void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6845 VisitOMPClauseWithPreInit(C);
6846 Record.push_back(uint64_t(C->getNameModifier()));
6847 Record.AddSourceLocation(C->getNameModifierLoc());
6848 Record.AddSourceLocation(C->getColonLoc());
6849 Record.AddStmt(C->getCondition());
6850 Record.AddSourceLocation(C->getLParenLoc());
6851}
6852
6853void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
6854 VisitOMPClauseWithPreInit(C);
6855 Record.AddStmt(C->getCondition());
6856 Record.AddSourceLocation(C->getLParenLoc());
6857}
6858
6859void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6860 VisitOMPClauseWithPreInit(C);
6861 Record.AddStmt(C->getNumThreads());
6862 Record.AddSourceLocation(C->getLParenLoc());
6863}
6864
6865void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6866 Record.AddStmt(C->getSafelen());
6867 Record.AddSourceLocation(C->getLParenLoc());
6868}
6869
6870void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6871 Record.AddStmt(C->getSimdlen());
6872 Record.AddSourceLocation(C->getLParenLoc());
6873}
6874
6875void OMPClauseWriter::VisitOMPSizesClause(OMPSizesClause *C) {
6876 Record.push_back(C->getNumSizes());
6877 for (Expr *Size : C->getSizesRefs())
6878 Record.AddStmt(Size);
6879 Record.AddSourceLocation(C->getLParenLoc());
6880}
6881
6882void OMPClauseWriter::VisitOMPFullClause(OMPFullClause *C) {}
6883
6884void OMPClauseWriter::VisitOMPPartialClause(OMPPartialClause *C) {
6885 Record.AddStmt(C->getFactor());
6886 Record.AddSourceLocation(C->getLParenLoc());
6887}
6888
6889void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6890 Record.AddStmt(C->getAllocator());
6891 Record.AddSourceLocation(C->getLParenLoc());
6892}
6893
6894void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6895 Record.AddStmt(C->getNumForLoops());
6896 Record.AddSourceLocation(C->getLParenLoc());
6897}
6898
6899void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) {
6900 Record.AddStmt(C->getEventHandler());
6901 Record.AddSourceLocation(C->getLParenLoc());
6902}
6903
6904void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
6905 Record.push_back(unsigned(C->getDefaultKind()));
6906 Record.AddSourceLocation(C->getLParenLoc());
6907 Record.AddSourceLocation(C->getDefaultKindKwLoc());
6908}
6909
6910void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
6911 Record.push_back(unsigned(C->getProcBindKind()));
6912 Record.AddSourceLocation(C->getLParenLoc());
6913 Record.AddSourceLocation(C->getProcBindKindKwLoc());
6914}
6915
6916void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6917 VisitOMPClauseWithPreInit(C);
6918 Record.push_back(C->getScheduleKind());
6919 Record.push_back(C->getFirstScheduleModifier());
6920 Record.push_back(C->getSecondScheduleModifier());
6921 Record.AddStmt(C->getChunkSize());
6922 Record.AddSourceLocation(C->getLParenLoc());
6923 Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6924 Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6925 Record.AddSourceLocation(C->getScheduleKindLoc());
6926 Record.AddSourceLocation(C->getCommaLoc());
6927}
6928
6929void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6930 Record.push_back(C->getLoopNumIterations().size());
6931 Record.AddStmt(C->getNumForLoops());
6932 for (Expr *NumIter : C->getLoopNumIterations())
6933 Record.AddStmt(NumIter);
6934 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
6935 Record.AddStmt(C->getLoopCounter(I));
6936 Record.AddSourceLocation(C->getLParenLoc());
6937}
6938
6939void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6940
6941void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6942
6943void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6944
6945void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6946
6947void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6948
6949void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) {
6950 Record.push_back(C->isExtended() ? 1 : 0);
6951 if (C->isExtended()) {
6952 Record.AddSourceLocation(C->getLParenLoc());
6953 Record.AddSourceLocation(C->getArgumentLoc());
6954 Record.writeEnum(C->getDependencyKind());
6955 }
6956}
6957
6958void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6959
6960void OMPClauseWriter::VisitOMPCompareClause(OMPCompareClause *) {}
6961
6962// Save the parameter of fail clause.
6963void OMPClauseWriter::VisitOMPFailClause(OMPFailClause *C) {
6964 Record.AddSourceLocation(C->getLParenLoc());
6965 Record.AddSourceLocation(C->getFailParameterLoc());
6966 Record.writeEnum(C->getFailParameter());
6967}
6968
6969void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6970
6971void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
6972
6973void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {}
6974
6975void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {}
6976
6977void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
6978
6979void OMPClauseWriter::VisitOMPWeakClause(OMPWeakClause *) {}
6980
6981void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6982
6983void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6984
6985void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6986
6987void OMPClauseWriter::VisitOMPInitClause(OMPInitClause *C) {
6988 Record.push_back(C->varlist_size());
6989 for (Expr *VE : C->varlists())
6990 Record.AddStmt(VE);
6991 Record.writeBool(C->getIsTarget());
6992 Record.writeBool(C->getIsTargetSync());
6993 Record.AddSourceLocation(C->getLParenLoc());
6994 Record.AddSourceLocation(C->getVarLoc());
6995}
6996
6997void OMPClauseWriter::VisitOMPUseClause(OMPUseClause *C) {
6998 Record.AddStmt(C->getInteropVar());
6999 Record.AddSourceLocation(C->getLParenLoc());
7000 Record.AddSourceLocation(C->getVarLoc());
7001}
7002
7003void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *C) {
7004 Record.AddStmt(C->getInteropVar());
7005 Record.AddSourceLocation(C->getLParenLoc());
7006 Record.AddSourceLocation(C->getVarLoc());
7007}
7008
7009void OMPClauseWriter::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
7010 VisitOMPClauseWithPreInit(C);
7011 Record.AddStmt(C->getCondition());
7012 Record.AddSourceLocation(C->getLParenLoc());
7013}
7014
7015void OMPClauseWriter::VisitOMPNocontextClause(OMPNocontextClause *C) {
7016 VisitOMPClauseWithPreInit(C);
7017 Record.AddStmt(C->getCondition());
7018 Record.AddSourceLocation(C->getLParenLoc());
7019}
7020
7021void OMPClauseWriter::VisitOMPFilterClause(OMPFilterClause *C) {
7022 VisitOMPClauseWithPreInit(C);
7023 Record.AddStmt(C->getThreadID());
7024 Record.AddSourceLocation(C->getLParenLoc());
7025}
7026
7027void OMPClauseWriter::VisitOMPAlignClause(OMPAlignClause *C) {
7028 Record.AddStmt(C->getAlignment());
7029 Record.AddSourceLocation(C->getLParenLoc());
7030}
7031
7032void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
7033 Record.push_back(C->varlist_size());
7034 Record.AddSourceLocation(C->getLParenLoc());
7035 for (auto *VE : C->varlists()) {
7036 Record.AddStmt(VE);
7037 }
7038 for (auto *VE : C->private_copies()) {
7039 Record.AddStmt(VE);
7040 }
7041}
7042
7043void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
7044 Record.push_back(C->varlist_size());
7045 VisitOMPClauseWithPreInit(C);
7046 Record.AddSourceLocation(C->getLParenLoc());
7047 for (auto *VE : C->varlists()) {
7048 Record.AddStmt(VE);
7049 }
7050 for (auto *VE : C->private_copies()) {
7051 Record.AddStmt(VE);
7052 }
7053 for (auto *VE : C->inits()) {
7054 Record.AddStmt(VE);
7055 }
7056}
7057
7058void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
7059 Record.push_back(C->varlist_size());
7060 VisitOMPClauseWithPostUpdate(C);
7061 Record.AddSourceLocation(C->getLParenLoc());
7062 Record.writeEnum(C->getKind());
7063 Record.AddSourceLocation(C->getKindLoc());
7064 Record.AddSourceLocation(C->getColonLoc());
7065 for (auto *VE : C->varlists())
7066 Record.AddStmt(VE);
7067 for (auto *E : C->private_copies())
7068 Record.AddStmt(E);
7069 for (auto *E : C->source_exprs())
7070 Record.AddStmt(E);
7071 for (auto *E : C->destination_exprs())
7072 Record.AddStmt(E);
7073 for (auto *E : C->assignment_ops())
7074 Record.AddStmt(E);
7075}
7076
7077void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
7078 Record.push_back(C->varlist_size());
7079 Record.AddSourceLocation(C->getLParenLoc());
7080 for (auto *VE : C->varlists())
7081 Record.AddStmt(VE);
7082}
7083
7084void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
7085 Record.push_back(C->varlist_size());
7086 Record.writeEnum(C->getModifier());
7087 VisitOMPClauseWithPostUpdate(C);
7088 Record.AddSourceLocation(C->getLParenLoc());
7089 Record.AddSourceLocation(C->getModifierLoc());
7090 Record.AddSourceLocation(C->getColonLoc());
7091 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
7092 Record.AddDeclarationNameInfo(C->getNameInfo());
7093 for (auto *VE : C->varlists())
7094 Record.AddStmt(VE);
7095 for (auto *VE : C->privates())
7096 Record.AddStmt(VE);
7097 for (auto *E : C->lhs_exprs())
7098 Record.AddStmt(E);
7099 for (auto *E : C->rhs_exprs())
7100 Record.AddStmt(E);
7101 for (auto *E : C->reduction_ops())
7102 Record.AddStmt(E);
7103 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
7104 for (auto *E : C->copy_ops())
7105 Record.AddStmt(E);
7106 for (auto *E : C->copy_array_temps())
7107 Record.AddStmt(E);
7108 for (auto *E : C->copy_array_elems())
7109 Record.AddStmt(E);
7110 }
7111}
7112
7113void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
7114 Record.push_back(C->varlist_size());
7115 VisitOMPClauseWithPostUpdate(C);
7116 Record.AddSourceLocation(C->getLParenLoc());
7117 Record.AddSourceLocation(C->getColonLoc());
7118 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
7119 Record.AddDeclarationNameInfo(C->getNameInfo());
7120 for (auto *VE : C->varlists())
7121 Record.AddStmt(VE);
7122 for (auto *VE : C->privates())
7123 Record.AddStmt(VE);
7124 for (auto *E : C->lhs_exprs())
7125 Record.AddStmt(E);
7126 for (auto *E : C->rhs_exprs())
7127 Record.AddStmt(E);
7128 for (auto *E : C->reduction_ops())
7129 Record.AddStmt(E);
7130}
7131
7132void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
7133 Record.push_back(C->varlist_size());
7134 VisitOMPClauseWithPostUpdate(C);
7135 Record.AddSourceLocation(C->getLParenLoc());
7136 Record.AddSourceLocation(C->getColonLoc());
7137 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
7138 Record.AddDeclarationNameInfo(C->getNameInfo());
7139 for (auto *VE : C->varlists())
7140 Record.AddStmt(VE);
7141 for (auto *VE : C->privates())
7142 Record.AddStmt(VE);
7143 for (auto *E : C->lhs_exprs())
7144 Record.AddStmt(E);
7145 for (auto *E : C->rhs_exprs())
7146 Record.AddStmt(E);
7147 for (auto *E : C->reduction_ops())
7148 Record.AddStmt(E);
7149 for (auto *E : C->taskgroup_descriptors())
7150 Record.AddStmt(E);
7151}
7152
7153void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
7154 Record.push_back(C->varlist_size());
7155 VisitOMPClauseWithPostUpdate(C);
7156 Record.AddSourceLocation(C->getLParenLoc());
7157 Record.AddSourceLocation(C->getColonLoc());
7158 Record.push_back(C->getModifier());
7159 Record.AddSourceLocation(C->getModifierLoc());
7160 for (auto *VE : C->varlists()) {
7161 Record.AddStmt(VE);
7162 }
7163 for (auto *VE : C->privates()) {
7164 Record.AddStmt(VE);
7165 }
7166 for (auto *VE : C->inits()) {
7167 Record.AddStmt(VE);
7168 }
7169 for (auto *VE : C->updates()) {
7170 Record.AddStmt(VE);
7171 }
7172 for (auto *VE : C->finals()) {
7173 Record.AddStmt(VE);
7174 }
7175 Record.AddStmt(C->getStep());
7176 Record.AddStmt(C->getCalcStep());
7177 for (auto *VE : C->used_expressions())
7178 Record.AddStmt(VE);
7179}
7180
7181void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
7182 Record.push_back(C->varlist_size());
7183 Record.AddSourceLocation(C->getLParenLoc());
7184 Record.AddSourceLocation(C->getColonLoc());
7185 for (auto *VE : C->varlists())
7186 Record.AddStmt(VE);
7187 Record.AddStmt(C->getAlignment());
7188}
7189
7190void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
7191 Record.push_back(C->varlist_size());
7192 Record.AddSourceLocation(C->getLParenLoc());
7193 for (auto *VE : C->varlists())
7194 Record.AddStmt(VE);
7195 for (auto *E : C->source_exprs())
7196 Record.AddStmt(E);
7197 for (auto *E : C->destination_exprs())
7198 Record.AddStmt(E);
7199 for (auto *E : C->assignment_ops())
7200 Record.AddStmt(E);
7201}
7202
7203void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
7204 Record.push_back(C->varlist_size());
7205 Record.AddSourceLocation(C->getLParenLoc());
7206 for (auto *VE : C->varlists())
7207 Record.AddStmt(VE);
7208 for (auto *E : C->source_exprs())
7209 Record.AddStmt(E);
7210 for (auto *E : C->destination_exprs())
7211 Record.AddStmt(E);
7212 for (auto *E : C->assignment_ops())
7213 Record.AddStmt(E);
7214}
7215
7216void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
7217 Record.push_back(C->varlist_size());
7218 Record.AddSourceLocation(C->getLParenLoc());
7219 for (auto *VE : C->varlists())
7220 Record.AddStmt(VE);
7221}
7222
7223void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) {
7224 Record.AddStmt(C->getDepobj());
7225 Record.AddSourceLocation(C->getLParenLoc());
7226}
7227
7228void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
7229 Record.push_back(C->varlist_size());
7230 Record.push_back(C->getNumLoops());
7231 Record.AddSourceLocation(C->getLParenLoc());
7232 Record.AddStmt(C->getModifier());
7233 Record.push_back(C->getDependencyKind());
7234 Record.AddSourceLocation(C->getDependencyLoc());
7235 Record.AddSourceLocation(C->getColonLoc());
7236 Record.AddSourceLocation(C->getOmpAllMemoryLoc());
7237 for (auto *VE : C->varlists())
7238 Record.AddStmt(VE);
7239 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
7240 Record.AddStmt(C->getLoopData(I));
7241}
7242
7243void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
7244 VisitOMPClauseWithPreInit(C);
7245 Record.writeEnum(C->getModifier());
7246 Record.AddStmt(C->getDevice());
7247 Record.AddSourceLocation(C->getModifierLoc());
7248 Record.AddSourceLocation(C->getLParenLoc());
7249}
7250
7251void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
7252 Record.push_back(C->varlist_size());
7253 Record.push_back(C->getUniqueDeclarationsNum());
7254 Record.push_back(C->getTotalComponentListNum());
7255 Record.push_back(C->getTotalComponentsNum());
7256 Record.AddSourceLocation(C->getLParenLoc());
7257 bool HasIteratorModifier = false;
7258 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
7259 Record.push_back(C->getMapTypeModifier(I));
7260 Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
7261 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
7262 HasIteratorModifier = true;
7263 }
7264 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
7265 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
7266 Record.push_back(C->getMapType());
7267 Record.AddSourceLocation(C->getMapLoc());
7268 Record.AddSourceLocation(C->getColonLoc());
7269 for (auto *E : C->varlists())
7270 Record.AddStmt(E);
7271 for (auto *E : C->mapperlists())
7272 Record.AddStmt(E);
7273 if (HasIteratorModifier)
7274 Record.AddStmt(C->getIteratorModifier());
7275 for (auto *D : C->all_decls())
7276 Record.AddDeclRef(D);
7277 for (auto N : C->all_num_lists())
7278 Record.push_back(N);
7279 for (auto N : C->all_lists_sizes())
7280 Record.push_back(N);
7281 for (auto &M : C->all_components()) {
7282 Record.AddStmt(M.getAssociatedExpression());
7283 Record.AddDeclRef(M.getAssociatedDeclaration());
7284 }
7285}
7286
7287void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
7288 Record.push_back(C->varlist_size());
7289 Record.AddSourceLocation(C->getLParenLoc());
7290 Record.AddSourceLocation(C->getColonLoc());
7291 Record.AddStmt(C->getAllocator());
7292 for (auto *VE : C->varlists())
7293 Record.AddStmt(VE);
7294}
7295
7296void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
7297 VisitOMPClauseWithPreInit(C);
7298 Record.AddStmt(C->getNumTeams());
7299 Record.AddSourceLocation(C->getLParenLoc());
7300}
7301
7302void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
7303 VisitOMPClauseWithPreInit(C);
7304 Record.AddStmt(C->getThreadLimit());
7305 Record.AddSourceLocation(C->getLParenLoc());
7306}
7307
7308void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
7309 VisitOMPClauseWithPreInit(C);
7310 Record.AddStmt(C->getPriority());
7311 Record.AddSourceLocation(C->getLParenLoc());
7312}
7313
7314void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
7315 VisitOMPClauseWithPreInit(C);
7316 Record.writeEnum(C->getModifier());
7317 Record.AddStmt(C->getGrainsize());
7318 Record.AddSourceLocation(C->getModifierLoc());
7319 Record.AddSourceLocation(C->getLParenLoc());
7320}
7321
7322void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
7323 VisitOMPClauseWithPreInit(C);
7324 Record.writeEnum(C->getModifier());
7325 Record.AddStmt(C->getNumTasks());
7326 Record.AddSourceLocation(C->getModifierLoc());
7327 Record.AddSourceLocation(C->getLParenLoc());
7328}
7329
7330void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
7331 Record.AddStmt(C->getHint());
7332 Record.AddSourceLocation(C->getLParenLoc());
7333}
7334
7335void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
7336 VisitOMPClauseWithPreInit(C);
7337 Record.push_back(C->getDistScheduleKind());
7338 Record.AddStmt(C->getChunkSize());
7339 Record.AddSourceLocation(C->getLParenLoc());
7340 Record.AddSourceLocation(C->getDistScheduleKindLoc());
7341 Record.AddSourceLocation(C->getCommaLoc());
7342}
7343
7344void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
7345 Record.push_back(C->getDefaultmapKind());
7346 Record.push_back(C->getDefaultmapModifier());
7347 Record.AddSourceLocation(C->getLParenLoc());
7348 Record.AddSourceLocation(C->getDefaultmapModifierLoc());
7349 Record.AddSourceLocation(C->getDefaultmapKindLoc());
7350}
7351
7352void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
7353 Record.push_back(C->varlist_size());
7354 Record.push_back(C->getUniqueDeclarationsNum());
7355 Record.push_back(C->getTotalComponentListNum());
7356 Record.push_back(C->getTotalComponentsNum());
7357 Record.AddSourceLocation(C->getLParenLoc());
7358 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
7359 Record.push_back(C->getMotionModifier(I));
7360 Record.AddSourceLocation(C->getMotionModifierLoc(I));
7361 }
7362 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
7363 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
7364 Record.AddSourceLocation(C->getColonLoc());
7365 for (auto *E : C->varlists())
7366 Record.AddStmt(E);
7367 for (auto *E : C->mapperlists())
7368 Record.AddStmt(E);
7369 for (auto *D : C->all_decls())
7370 Record.AddDeclRef(D);
7371 for (auto N : C->all_num_lists())
7372 Record.push_back(N);
7373 for (auto N : C->all_lists_sizes())
7374 Record.push_back(N);
7375 for (auto &M : C->all_components()) {
7376 Record.AddStmt(M.getAssociatedExpression());
7377 Record.writeBool(M.isNonContiguous());
7378 Record.AddDeclRef(M.getAssociatedDeclaration());
7379 }
7380}
7381
7382void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
7383 Record.push_back(C->varlist_size());
7384 Record.push_back(C->getUniqueDeclarationsNum());
7385 Record.push_back(C->getTotalComponentListNum());
7386 Record.push_back(C->getTotalComponentsNum());
7387 Record.AddSourceLocation(C->getLParenLoc());
7388 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
7389 Record.push_back(C->getMotionModifier(I));
7390 Record.AddSourceLocation(C->getMotionModifierLoc(I));
7391 }
7392 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
7393 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
7394 Record.AddSourceLocation(C->getColonLoc());
7395 for (auto *E : C->varlists())
7396 Record.AddStmt(E);
7397 for (auto *E : C->mapperlists())
7398 Record.AddStmt(E);
7399 for (auto *D : C->all_decls())
7400 Record.AddDeclRef(D);
7401 for (auto N : C->all_num_lists())
7402 Record.push_back(N);
7403 for (auto N : C->all_lists_sizes())
7404 Record.push_back(N);
7405 for (auto &M : C->all_components()) {
7406 Record.AddStmt(M.getAssociatedExpression());
7407 Record.writeBool(M.isNonContiguous());
7408 Record.AddDeclRef(M.getAssociatedDeclaration());
7409 }
7410}
7411
7412void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
7413 Record.push_back(C->varlist_size());
7414 Record.push_back(C->getUniqueDeclarationsNum());
7415 Record.push_back(C->getTotalComponentListNum());
7416 Record.push_back(C->getTotalComponentsNum());
7417 Record.AddSourceLocation(C->getLParenLoc());
7418 for (auto *E : C->varlists())
7419 Record.AddStmt(E);
7420 for (auto *VE : C->private_copies())
7421 Record.AddStmt(VE);
7422 for (auto *VE : C->inits())
7423 Record.AddStmt(VE);
7424 for (auto *D : C->all_decls())
7425 Record.AddDeclRef(D);
7426 for (auto N : C->all_num_lists())
7427 Record.push_back(N);
7428 for (auto N : C->all_lists_sizes())
7429 Record.push_back(N);
7430 for (auto &M : C->all_components()) {
7431 Record.AddStmt(M.getAssociatedExpression());
7432 Record.AddDeclRef(M.getAssociatedDeclaration());
7433 }
7434}
7435
7436void OMPClauseWriter::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
7437 Record.push_back(C->varlist_size());
7438 Record.push_back(C->getUniqueDeclarationsNum());
7439 Record.push_back(C->getTotalComponentListNum());
7440 Record.push_back(C->getTotalComponentsNum());
7441 Record.AddSourceLocation(C->getLParenLoc());
7442 for (auto *E : C->varlists())
7443 Record.AddStmt(E);
7444 for (auto *D : C->all_decls())
7445 Record.AddDeclRef(D);
7446 for (auto N : C->all_num_lists())
7447 Record.push_back(N);
7448 for (auto N : C->all_lists_sizes())
7449 Record.push_back(N);
7450 for (auto &M : C->all_components()) {
7451 Record.AddStmt(M.getAssociatedExpression());
7452 Record.AddDeclRef(M.getAssociatedDeclaration());
7453 }
7454}
7455
7456void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
7457 Record.push_back(C->varlist_size());
7458 Record.push_back(C->getUniqueDeclarationsNum());
7459 Record.push_back(C->getTotalComponentListNum());
7460 Record.push_back(C->getTotalComponentsNum());
7461 Record.AddSourceLocation(C->getLParenLoc());
7462 for (auto *E : C->varlists())
7463 Record.AddStmt(E);
7464 for (auto *D : C->all_decls())
7465 Record.AddDeclRef(D);
7466 for (auto N : C->all_num_lists())
7467 Record.push_back(N);
7468 for (auto N : C->all_lists_sizes())
7469 Record.push_back(N);
7470 for (auto &M : C->all_components()) {
7471 Record.AddStmt(M.getAssociatedExpression());
7472 Record.AddDeclRef(M.getAssociatedDeclaration());
7473 }
7474}
7475
7476void OMPClauseWriter::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
7477 Record.push_back(C->varlist_size());
7478 Record.push_back(C->getUniqueDeclarationsNum());
7479 Record.push_back(C->getTotalComponentListNum());
7480 Record.push_back(C->getTotalComponentsNum());
7481 Record.AddSourceLocation(C->getLParenLoc());
7482 for (auto *E : C->varlists())
7483 Record.AddStmt(E);
7484 for (auto *D : C->all_decls())
7485 Record.AddDeclRef(D);
7486 for (auto N : C->all_num_lists())
7487 Record.push_back(N);
7488 for (auto N : C->all_lists_sizes())
7489 Record.push_back(N);
7490 for (auto &M : C->all_components()) {
7491 Record.AddStmt(M.getAssociatedExpression());
7492 Record.AddDeclRef(M.getAssociatedDeclaration());
7493 }
7494}
7495
7496void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
7497
7498void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
7500
7501void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
7502
7503void
7504OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
7505}
7506
7507void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
7509 Record.push_back(C->getAtomicDefaultMemOrderKind());
7510 Record.AddSourceLocation(C->getLParenLoc());
7511 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
7512}
7513
7514void OMPClauseWriter::VisitOMPAtClause(OMPAtClause *C) {
7515 Record.push_back(C->getAtKind());
7516 Record.AddSourceLocation(C->getLParenLoc());
7517 Record.AddSourceLocation(C->getAtKindKwLoc());
7518}
7519
7520void OMPClauseWriter::VisitOMPSeverityClause(OMPSeverityClause *C) {
7521 Record.push_back(C->getSeverityKind());
7522 Record.AddSourceLocation(C->getLParenLoc());
7523 Record.AddSourceLocation(C->getSeverityKindKwLoc());
7524}
7525
7526void OMPClauseWriter::VisitOMPMessageClause(OMPMessageClause *C) {
7527 Record.AddStmt(C->getMessageString());
7528 Record.AddSourceLocation(C->getLParenLoc());
7529}
7530
7531void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
7532 Record.push_back(C->varlist_size());
7533 Record.AddSourceLocation(C->getLParenLoc());
7534 for (auto *VE : C->varlists())
7535 Record.AddStmt(VE);
7536 for (auto *E : C->private_refs())
7537 Record.AddStmt(E);
7538}
7539
7540void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
7541 Record.push_back(C->varlist_size());
7542 Record.AddSourceLocation(C->getLParenLoc());
7543 for (auto *VE : C->varlists())
7544 Record.AddStmt(VE);
7545}
7546
7547void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
7548 Record.push_back(C->varlist_size());
7549 Record.AddSourceLocation(C->getLParenLoc());
7550 for (auto *VE : C->varlists())
7551 Record.AddStmt(VE);
7552}
7553
7554void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) {
7555 Record.writeEnum(C->getKind());
7556 Record.writeEnum(C->getModifier());
7557 Record.AddSourceLocation(C->getLParenLoc());
7558 Record.AddSourceLocation(C->getKindKwLoc());
7559 Record.AddSourceLocation(C->getModifierKwLoc());
7560}
7561
7562void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
7563 Record.push_back(C->getNumberOfAllocators());
7564 Record.AddSourceLocation(C->getLParenLoc());
7565 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
7566 OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I);
7567 Record.AddStmt(Data.Allocator);
7568 Record.AddStmt(Data.AllocatorTraits);
7569 Record.AddSourceLocation(Data.LParenLoc);
7570 Record.AddSourceLocation(Data.RParenLoc);
7571 }
7572}
7573
7574void OMPClauseWriter::VisitOMPAffinityClause(OMPAffinityClause *C) {
7575 Record.push_back(C->varlist_size());
7576 Record.AddSourceLocation(C->getLParenLoc());
7577 Record.AddStmt(C->getModifier());
7578 Record.AddSourceLocation(C->getColonLoc());
7579 for (Expr *E : C->varlists())
7580 Record.AddStmt(E);
7581}
7582
7583void OMPClauseWriter::VisitOMPBindClause(OMPBindClause *C) {
7584 Record.writeEnum(C->getBindKind());
7585 Record.AddSourceLocation(C->getLParenLoc());
7586 Record.AddSourceLocation(C->getBindKindLoc());
7587}
7588
7589void OMPClauseWriter::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
7590 VisitOMPClauseWithPreInit(C);
7591 Record.AddStmt(C->getSize());
7592 Record.AddSourceLocation(C->getLParenLoc());
7593}
7594
7595void OMPClauseWriter::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
7596 Record.push_back(C->varlist_size());
7597 Record.push_back(C->getNumLoops());
7598 Record.AddSourceLocation(C->getLParenLoc());
7599 Record.push_back(C->getDependenceType());
7600 Record.AddSourceLocation(C->getDependenceLoc());
7601 Record.AddSourceLocation(C->getColonLoc());
7602 for (auto *VE : C->varlists())
7603 Record.AddStmt(VE);
7604 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
7605 Record.AddStmt(C->getLoopData(I));
7606}
7607
7608void OMPClauseWriter::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
7609 Record.AddAttributes(C->getAttrs());
7610 Record.AddSourceLocation(C->getBeginLoc());
7611 Record.AddSourceLocation(C->getLParenLoc());
7612 Record.AddSourceLocation(C->getEndLoc());
7613}
7614
7615void OMPClauseWriter::VisitOMPXBareClause(OMPXBareClause *C) {}
7616
7618 writeUInt32(TI->Sets.size());
7619 for (const auto &Set : TI->Sets) {
7620 writeEnum(Set.Kind);
7621 writeUInt32(Set.Selectors.size());
7622 for (const auto &Selector : Set.Selectors) {
7623 writeEnum(Selector.Kind);
7624 writeBool(Selector.ScoreOrCondition);
7625 if (Selector.ScoreOrCondition)
7626 writeExprRef(Selector.ScoreOrCondition);
7627 writeUInt32(Selector.Properties.size());
7628 for (const auto &Property : Selector.Properties)
7629 writeEnum(Property.Kind);
7630 }
7631 }
7632}
7633
7635 if (!Data)
7636 return;
7637 writeUInt32(Data->getNumClauses());
7638 writeUInt32(Data->getNumChildren());
7639 writeBool(Data->hasAssociatedStmt());
7640 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
7641 writeOMPClause(Data->getClauses()[I]);
7642 if (Data->hasAssociatedStmt())
7643 AddStmt(Data->getAssociatedStmt());
7644 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
7645 AddStmt(Data->getChildren()[I]);
7646}
7647
7649 writeEnum(C->getClauseKind());
7650 writeSourceLocation(C->getBeginLoc());
7651 writeSourceLocation(C->getEndLoc());
7652
7653 switch (C->getClauseKind()) {
7655 const auto *DC = cast<OpenACCDefaultClause>(C);
7656 writeSourceLocation(DC->getLParenLoc());
7657 writeEnum(DC->getDefaultClauseKind());
7658 return;
7659 }
7660 case OpenACCClauseKind::If: {
7661 const auto *IC = cast<OpenACCIfClause>(C);
7662 writeSourceLocation(IC->getLParenLoc());
7663 AddStmt(const_cast<Expr *>(IC->getConditionExpr()));
7664 return;
7665 }
7667 const auto *SC = cast<OpenACCIfClause>(C);
7668 writeSourceLocation(SC->getLParenLoc());
7669 writeBool(SC->hasConditionExpr());
7670 if (SC->hasConditionExpr())
7671 AddStmt(const_cast<Expr *>(SC->getConditionExpr()));
7672 return;
7673 }
7675 const auto *NGC = cast<OpenACCNumGangsClause>(C);
7676 writeSourceLocation(NGC->getLParenLoc());
7677 writeUInt32(NGC->getIntExprs().size());
7678 for (Expr *E : NGC->getIntExprs())
7679 AddStmt(E);
7680 return;
7681 }
7683 const auto *NWC = cast<OpenACCNumWorkersClause>(C);
7684 writeSourceLocation(NWC->getLParenLoc());
7685 AddStmt(const_cast<Expr *>(NWC->getIntExpr()));
7686 return;
7687 }
7689 const auto *NWC = cast<OpenACCVectorLengthClause>(C);
7690 writeSourceLocation(NWC->getLParenLoc());
7691 AddStmt(const_cast<Expr *>(NWC->getIntExpr()));
7692 return;
7693 }
7731 llvm_unreachable("Clause serialization not yet implemented");
7732 }
7733 llvm_unreachable("Invalid Clause Kind");
7734}
7735
7738 for (const OpenACCClause *Clause : Clauses)
7739 writeOpenACCClause(Clause);
7740}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3284
int Id
Definition: ASTDiff.cpp:190
DynTypedNode Node
StringRef P
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
Definition: ASTReader.cpp:989
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...
Definition: ASTWriter.cpp:3581
static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a buffer.
Definition: ASTWriter.cpp:1818
static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec)
Definition: ASTWriter.cpp:4751
static void AddLazyVectorEmiitedDecls(ASTWriter &Writer, Vector &Vec, ASTWriter::RecordData &Record)
Definition: ASTWriter.cpp:4759
#define RECORD(X)
static uint64_t EmitCXXCtorInitializers(ASTWriter &W, ArrayRef< CXXCtorInitializer * > CtorInits)
Definition: ASTWriter.cpp:6283
static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a macro expansion.
Definition: ASTWriter.cpp:1848
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:126
static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream, bool Compressed)
Create an abbreviation for the SLocEntry that refers to a buffer's blob.
Definition: ASTWriter.cpp:1833
static const char * adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir)
Adjusts the given filename to only write out the portion of the filename that is not part of the syst...
Definition: ASTWriter.cpp:1120
static unsigned getNumberOfModules(Module *Mod)
Compute the number of modules within the given tree (including the given module).
Definition: ASTWriter.cpp:2792
static bool isImportedDeclContext(ASTReader *Chain, const Decl *D)
Definition: ASTWriter.cpp:6534
static TypeCode getTypeCodeForTypeClass(Type::TypeClass id)
Definition: ASTWriter.cpp:154
static void AddStmtsExprs(llvm::BitstreamWriter &Stream, ASTWriter::RecordDataImpl &Record)
Definition: ASTWriter.cpp:695
static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob, unsigned SLocBufferBlobCompressedAbbrv, unsigned SLocBufferBlobAbbrv)
Definition: ASTWriter.cpp:2131
static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W, ArrayRef< CXXBaseSpecifier > Bases)
Definition: ASTWriter.cpp:6265
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.
Definition: ASTWriter.cpp:1865
static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule, const Preprocessor &PP)
Definition: ASTWriter.cpp:2373
static bool cleanPathForOutput(FileManager &FileMgr, SmallVectorImpl< char > &Path)
Prepares a path for being written to an AST file by converting it to an absolute path and removing ne...
Definition: ASTWriter.cpp:1103
static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a file.
Definition: ASTWriter.cpp:1799
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:82
Defines the Diagnostic-related interfaces.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::FileManager interface and associated types.
Defines the clang::FileSystemOptions interface.
StringRef Filename
Definition: Format.cpp:2971
unsigned Iter
Definition: HTMLLogger.cpp:154
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
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:48
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.
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.
const char * Data
Defines the clang::TargetOptions class.
#define BLOCK(DERIVED, BASE)
Definition: Template.h:621
C Language Family Type Representation.
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 b
do v
Definition: arm_acle.h:83
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
SourceManager & getSourceManager()
Definition: ASTContext.h:705
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
QualType getRawCFConstantStringType() const
Get the structure type used to representation CFStrings, or NULL if it hasn't yet been built.
Definition: ASTContext.h:1839
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:1992
QualType getRecordType(const RecordDecl *Decl) const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2574
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:1956
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:805
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:1968
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:1980
TagDecl * MSGuidTagDecl
Definition: ASTContext.h:1156
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
FunctionDecl * getcudaConfigureCallDecl()
Definition: ASTContext.h:1424
DiagnosticsEngine & getDiagnostics() const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
import_range local_imports() const
Definition: ASTContext.h:1031
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:366
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1773
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
Definition: ASTReader.cpp:8030
unsigned getTotalNumSubmodules() const
Returns the number of submodules known.
Definition: ASTReader.h:1868
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:5242
unsigned getTotalNumIdentifiers() const
Returns the number of identifiers found in the chain.
Definition: ASTReader.h:1848
void forEachImportedKeyDecl(const Decl *D, Fn Visit)
Run a callback on each imported key declaration of D.
Definition: ASTReader.h:1348
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:1873
unsigned getTotalNumTypes() const
Returns the number of types found in the chain.
Definition: ASTReader.h:1858
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Definition: ASTReader.cpp:9013
Decl * getKeyDeclaration(Decl *D)
Returns the first key declaration for the given declaration.
Definition: ASTReader.h:1332
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
Definition: ASTReader.cpp:8814
bool isProcessingUpdateRecords()
Definition: ASTReader.h:2420
unsigned getTotalNumMacros() const
Returns the number of macros found in the chain.
Definition: ASTReader.h:1853
unsigned getTotalNumDecls() const
Returns the number of declarations found in the chain.
Definition: ASTReader.h:1863
An object for streaming information to a record.
void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo)
Definition: ASTWriter.cpp:6138
void AddCXXBaseSpecifiers(ArrayRef< CXXBaseSpecifier > Bases)
Emit a set of C++ base specifiers.
Definition: ASTWriter.cpp:6278
void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs)
Emit a template argument list.
Definition: ASTWriter.cpp:6225
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.
Definition: ASTWriter.cpp:5873
void writeOMPTraitInfo(const OMPTraitInfo *TI)
Write an OMPTraitInfo object.
Definition: ASTWriter.cpp:7617
void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base)
Emit a C++ base specifier.
Definition: ASTWriter.cpp:6254
void writeOMPClause(OMPClause *C)
Definition: ASTWriter.cpp:6823
void writeBool(bool Value)
void AddAPValue(const APValue &Value)
Emit an APvalue.
void AddUnresolvedSet(const ASTUnresolvedSet &Set)
Emit a UnresolvedSet structure.
Definition: ASTWriter.cpp:6244
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 AddSelectorRef(Selector S)
Emit a Selector (which is a smart pointer reference).
Definition: ASTWriter.cpp:5850
void AddSourceRange(SourceRange Range, LocSeq *Seq=nullptr)
Emit a source range.
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 writeQualType(QualType T)
void writeOpenACCClauseList(ArrayRef< const OpenACCClause * > Clauses)
Writes out a list of OpenACC clauses.
Definition: ASTWriter.cpp:7736
void AddSourceLocation(SourceLocation Loc, LocSeq *Seq=nullptr)
Emit a source location.
void push_back(uint64_t N)
Minimal vector-like interface.
void AddTypeLoc(TypeLoc TL, LocSeq *Seq=nullptr)
Emits source location information for a type. Does not emit the type.
Definition: ASTWriter.cpp:5929
void AddCXXCtorInitializers(ArrayRef< CXXCtorInitializer * > CtorInits)
Emit a CXXCtorInitializer array.
Definition: ASTWriter.cpp:6318
void AddTemplateParameterList(const TemplateParameterList *TemplateParams)
Emit a template parameter list.
Definition: ASTWriter.cpp:6206
void AddTemplateArgument(const TemplateArgument &Arg)
Emit a template argument.
void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, DeclarationName Name)
Definition: ASTWriter.cpp:6111
void AddAPFloat(const llvm::APFloat &Value)
Emit a floating-point value.
Definition: ASTWriter.cpp:5804
void AddTypeSourceInfo(TypeSourceInfo *TInfo)
Emits a reference to a declarator info.
Definition: ASTWriter.cpp:5919
void AddQualifierInfo(const QualifierInfo &Info)
Definition: ASTWriter.cpp:6145
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.
Definition: ASTWriter.cpp:7634
void AddConceptReference(const ConceptReference *CR)
Definition: ASTWriter.cpp:495
void AddAPInt(const llvm::APInt &Value)
Emit an integral value.
void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg)
Emits a template argument location info.
Definition: ASTWriter.cpp:5877
void AddAttributes(ArrayRef< const Attr * > Attrs)
Emit a list of attributes.
Definition: ASTWriter.cpp:4560
void AddASTTemplateArgumentListInfo(const ASTTemplateArgumentListInfo *ASTTemplArgList)
Emits an AST template argument list info.
Definition: ASTWriter.cpp:6233
void AddCXXDefinitionData(const CXXRecordDecl *D)
Definition: ASTWriter.cpp:6323
void AddVarDeclInit(const VarDecl *VD)
Emit information about the initializer of a VarDecl.
Definition: ASTWriter.cpp:6420
void writeStmtRef(const Stmt *S)
void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg)
Emits a template argument location.
Definition: ASTWriter.cpp:5906
void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS)
Emit a nested name specifier with source-location information.
Definition: ASTWriter.cpp:6152
void writeOpenACCClause(const OpenACCClause *C)
Writes out a single OpenACC Clause.
Definition: ASTWriter.cpp:7648
void AddAttr(const Attr *A)
Definition: ASTWriter.cpp:4536
An UnresolvedSet-like class which uses the ASTContext's allocator.
Writes an AST file containing the contents of a translation unit.
Definition: ASTWriter.h:86
serialization::MacroID getMacroID(MacroInfo *MI)
Determine the ID of an already-emitted macro.
Definition: ASTWriter.cpp:5838
ASTFileSignature WriteAST(Sema &SemaRef, StringRef OutputFile, Module *WritingModule, StringRef isysroot, bool ShouldCacheASTInMemory=false)
Write a precompiled header for the given semantic analysis.
Definition: ASTWriter.cpp:4714
serialization::TypeID getTypeID(QualType T) const
Determine the type ID of an already-emitted type.
Definition: ASTWriter.cpp:5963
void AddEmittedDeclRef(const Decl *D, RecordDataImpl &Record)
Definition: ASTWriter.cpp:5976
void AddSourceRange(SourceRange Range, RecordDataImpl &Record, LocSeq *Seq=nullptr)
Emit a source range.
Definition: ASTWriter.cpp:5798
bool isWritingStdCXXNamedModules() const
Definition: ASTWriter.h:826
void EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record, StringRef Path)
Emit the current record with the given path as a blob.
Definition: ASTWriter.cpp:4645
void AddFileID(FileID FID, RecordDataImpl &Record)
Emit a FileID.
Definition: ASTWriter.cpp:5788
bool hasChain() const
Definition: ASTWriter.h:823
void AddPath(StringRef Path, RecordDataImpl &Record)
Add a path to the given record.
Definition: ASTWriter.cpp:4639
unsigned getTypeExtQualAbbrev() const
Definition: ASTWriter.h:776
void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record)
Add a version tuple to the given record.
Definition: ASTWriter.cpp:4652
uint32_t getMacroDirectivesOffset(const IdentifierInfo *Name)
Definition: ASTWriter.cpp:5846
void AddAlignPackInfo(const Sema::AlignPackInfo &Info, RecordDataImpl &Record)
Emit a AlignPackInfo.
Definition: ASTWriter.cpp:5720
bool IsLocalDecl(const Decl *D)
Is this a local declaration (that is, one that will be written to our AST file)? This is the case for...
Definition: ASTWriter.h:706
bool wasDeclEmitted(const Decl *D) const
Whether or not the declaration got emitted.
Definition: ASTWriter.cpp:6037
void AddString(StringRef Str, RecordDataImpl &Record)
Add a string to the given record.
Definition: ASTWriter.cpp:4611
time_t getTimestampForOutput(const FileEntry *E) const
Get a timestamp for output into the AST file.
Definition: ASTWriter.cpp:4710
~ASTWriter() override
LocalDeclID GetDeclRef(const Decl *D)
Force a declaration to be emitted and get its local ID to the module file been writing.
Definition: ASTWriter.cpp:5987
LocalDeclID getDeclID(const Decl *D)
Determine the local declaration ID of an already-emitted declaration.
Definition: ASTWriter.cpp:6024
void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record)
Emit a reference to an identifier.
Definition: ASTWriter.cpp:5808
serialization::TypeID GetOrCreateTypeID(QualType T)
Force a type to be emitted and get its ID.
Definition: ASTWriter.cpp:5940
serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name)
Get the unique number used to refer to the given macro.
Definition: ASTWriter.cpp:5822
void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record, LocSeq *Seq=nullptr)
Emit a source location.
Definition: ASTWriter.cpp:5792
void AddTypeRef(QualType T, RecordDataImpl &Record)
Emit a reference to a type.
Definition: ASTWriter.cpp:5936
ASTReader * getChain() const
Definition: ASTWriter.h:824
bool getDoneWritingDeclsAndTypes() const
Definition: ASTWriter.h:832
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...
Definition: ASTWriter.cpp:2763
void AddToken(const Token &Tok, RecordDataImpl &Record)
Emit a token.
Definition: ASTWriter.cpp:4566
serialization::SelectorID getSelectorRef(Selector Sel)
Get the unique number used to refer to the given selector.
Definition: ASTWriter.cpp:5854
ASTWriter(llvm::BitstreamWriter &Stream, SmallVectorImpl< char > &Buffer, InMemoryModuleCache &ModuleCache, 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.
Definition: ASTWriter.cpp:4687
SmallVector< uint64_t, 64 > RecordData
Definition: ASTWriter.h:91
unsigned getAnonymousDeclarationNumber(const NamedDecl *D)
Definition: ASTWriter.cpp:6090
serialization::IdentID getIdentifierRef(const IdentifierInfo *II)
Get the unique number used to refer to the given identifier.
Definition: ASTWriter.cpp:5812
const LangOptions & getLangOpts() const
Definition: ASTWriter.cpp:4705
void SetSelectorOffset(Selector Sel, uint32_t Offset)
Note that the selector Sel occurs at the given offset within the method pool/selector table.
Definition: ASTWriter.cpp:4677
bool PreparePathForOutput(SmallVectorImpl< char > &Path)
Convert a path from this build process into one that is appropriate for emission in the module file.
Definition: ASTWriter.cpp:4616
void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset)
Note that the identifier II occurs at the given offset within the identifier table.
Definition: ASTWriter.cpp:4667
void AddDeclRef(const Decl *D, RecordDataImpl &Record)
Emit a reference to a declaration.
Definition: ASTWriter.cpp:5983
Wrapper for source info for array parameter types.
Definition: TypeLoc.h:1617
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1563
Expr * getSizeExpr() const
Definition: TypeLoc.h:1583
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1571
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:2634
SourceLocation getKWLoc() const
Definition: TypeLoc.h:2618
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:2626
Attr - This represents one attribute.
Definition: Attr.h:42
attr::Kind getKind() const
Definition: Attr.h:88
SourceLocation getScopeLoc() const
const IdentifierInfo * getScopeName() const
const IdentifierInfo * getAttrName() const
Type source information for an attributed type.
Definition: TypeLoc.h:875
const Attr * getAttr() const
The type attribute.
Definition: TypeLoc.h:898
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:2194
bool isDecltypeAuto() const
Definition: TypeLoc.h:2193
bool isConstrained() const
Definition: TypeLoc.h:2197
ConceptReference * getConceptReference() const
Definition: TypeLoc.h:2203
Type source information for an btf_tag attributed type.
Definition: TypeLoc.h:925
A simple helper class to pack several bits in order into (a) 32 bit integer(s).
Definition: ASTWriter.h:950
void addBit(bool Value)
Definition: ASTWriter.h:970
void addBits(uint32_t Value, uint32_t BitsWidth)
Definition: ASTWriter.h:971
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1314
SourceLocation getCaretLoc() const
Definition: TypeLoc.h:1316
Wrapper for source info for builtin types.
Definition: TypeLoc.h:565
SourceLocation getBuiltinLoc() const
Definition: TypeLoc.h:567
TypeSpecifierType getWrittenTypeSpec() const
Definition: TypeLoc.cpp:332
TypeSpecifierWidth getWrittenWidthSpec() const
Definition: TypeLoc.h:629
bool needsExtraLocalData() const
Definition: TypeLoc.h:594
bool hasModeAttr() const
Definition: TypeLoc.h:656
TypeSpecifierSign getWrittenSignSpec() const
Definition: TypeLoc.h:613
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
unsigned getDeviceLambdaManglingNumber() const
Retrieve the device side mangling number.
Definition: DeclCXX.cpp:1702
unsigned getODRHash() const
Definition: DeclCXX.cpp:495
Represents a C++ temporary.
Definition: ExprCXX.h:1453
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1464
Declaration of a class template.
Represents a class template specialization, which refers to a class template with a given set of temp...
A reference to a concept and its template args, as it appears in the code.
Definition: ASTConcept.h:128
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition: ASTConcept.h:167
NamedDecl * getFoundDecl() const
Definition: ASTConcept.h:199
const DeclarationNameInfo & getConceptNameInfo() const
Definition: ASTConcept.h:171
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:203
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:207
SourceLocation getTemplateKWLoc() const
Definition: ASTConcept.h:177
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1262
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool isFileContext() const
Definition: DeclBase.h:2137
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
bool isLookupContext() const
Test whether the context supports looking up names.
Definition: DeclBase.h:2132
bool isTranslationUnit() const
Definition: DeclBase.h:2142
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1920
StoredDeclsMap * buildLookup()
Ensure the lookup structure is fully-built and return it.
Definition: DeclBase.cpp:1721
lookup_result noload_lookup(DeclarationName Name)
Find the declarations with the given name that are visible within this context; don't attempt to retr...
Definition: DeclBase.cpp:1849
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition: DeclBase.h:2330
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1354
bool decls_empty() const
Definition: DeclBase.cpp:1560
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
StoredDeclsMap * getLookupPtr() const
Retrieve the internal representation of the lookup structure.
Definition: DeclBase.h:2630
bool isValid() const
Definition: DeclID.h:123
DeclID get() const
Definition: DeclID.h:117
A helper iterator adaptor to convert the iterators to SmallVector<SomeDeclID> to the iterators to Sma...
Definition: DeclID.h:189
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1066
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:579
bool hasAttrs() const
Definition: DeclBase.h:524
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition: DeclBase.h:849
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition: DeclBase.h:780
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:974
bool isFromExplicitGlobalModule() const
Whether this declaration comes from explicit global module.
Definition: DeclBase.cpp:1105
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:776
SourceLocation getLocation() const
Definition: DeclBase.h:445
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AttrVec & getAttrs()
Definition: DeclBase.h:530
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:448
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).
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
SourceLocation getDecltypeLoc() const
Definition: TypeLoc.h:2083
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:2086
SourceLocation getTemplateNameLoc() const
Definition: TypeLoc.h:2298
Expr * getAttrExprOperand() const
The attribute's expression operand, if it has one.
Definition: TypeLoc.h:1780
SourceRange getAttrOperandParensRange() const
The location of the parentheses around the operand, if there is an operand.
Definition: TypeLoc.h:1791
SourceLocation getAttrNameLoc() const
The location of the attribute name, i.e.
Definition: TypeLoc.h:1770
NestedNameSpecifierLoc getQualifierLoc() const
Definition: TypeLoc.h:2407
SourceLocation getNameLoc() const
Definition: TypeLoc.h:2419
SourceLocation getElaboratedKeywordLoc() const
Definition: TypeLoc.h:2399
SourceLocation getNameLoc() const
Definition: TypeLoc.h:1890
SourceLocation getTemplateNameLoc() const
Definition: TypeLoc.h:2496
SourceLocation getTemplateKeywordLoc() const
Definition: TypeLoc.h:2488
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:2532
SourceLocation getElaboratedKeywordLoc() const
Definition: TypeLoc.h:2456
NestedNameSpecifierLoc getQualifierLoc() const
Definition: TypeLoc.h:2464
SourceLocation getNameLoc() const
Definition: TypeLoc.h:1862
static DiagnosticMapping getDefaultMapping(unsigned DiagID)
Get the default mapping for this diagnostic.
Options for controlling the compiler diagnostics engine.
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.
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
bool hasUncompilableErrorOccurred() const
Errors that actually prevent compilation, not those that are upgraded from a warning by -Werror.
Definition: Diagnostic.h:847
StringRef getName() const
SourceLocation getElaboratedKeywordLoc() const
Definition: TypeLoc.h:2319
NestedNameSpecifierLoc getQualifierLoc() const
Definition: TypeLoc.h:2331
Wrapper for source info for enum types.
Definition: TypeLoc.h:749
This represents one expression.
Definition: Expr.h:110
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
storage_type getAsOpaqueInt() const
Definition: LangOptions.h:976
storage_type getAsOpaqueInt() const
Definition: LangOptions.h:878
Represents a member of a struct/union/class.
Definition: Decl.h:3058
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
StringRef getName() const
The name of this FileEntry.
Definition: FileEntry.h:61
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:300
time_t getModificationTime() const
Definition: FileEntry.h:328
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
void trackVFSUsage(bool Active)
Enable or disable tracking of VFS usage.
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:251
void GetUniqueIDMapping(SmallVectorImpl< OptionalFileEntryRef > &UIDToFiles) const
Produce an array mapping from the unique IDs assigned to each file to the corresponding FileEntryRef.
bool makeAbsolutePath(SmallVectorImpl< char > &Path) const
Makes Path absolute taking into account FileSystemOptions and the working directory option.
FileSystemOptions & getFileSystemOpts()
Returns the current file system options.
Definition: FileManager.h:248
OptionalDirectoryEntryRef getOptionalDirectoryRef(StringRef DirName, bool CacheFailure=true)
Get a DirectoryEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:175
Keeps track of options that affect how file operations are performed.
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
Represents a function declaration or definition.
Definition: Decl.h:1971
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
Declaration of a template function.
Definition: DeclTemplate.h:958
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
unsigned getNumParams() const
Definition: TypeLoc.h:1500
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1506
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1452
SourceRange getExceptionSpecRange() const
Definition: TypeLoc.h:1480
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1444
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1460
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1468
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
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 ModuleCachePath
The directory used for the module cache.
std::string ModuleUserBuildPath
The directory used for a user build.
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
unsigned 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 ModulesIncludeVFSUsage
Whether to include ivfsoverlay usage information in written AST files.
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,...
Definition: HeaderSearch.h:253
std::vector< bool > collectVFSUsageAndClear() const
Collect which HeaderSearchOptions::VFSOverlayFiles have been meaningfully used so far and mark their ...
FileManager & getFileMgr() const
Definition: HeaderSearch.h:388
const HeaderFileInfo * getExistingLocalFileInfo(FileEntryRef FE) const
Return the headerFileInfo structure for the specified FileEntry, if it has ever been filled in locall...
StringRef getModuleCachePath() const
Retrieve the path to the module cache.
Definition: HeaderSearch.h:450
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...
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:837
HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
Definition: HeaderSearch.h:386
unsigned header_file_size() const
Definition: HeaderSearch.h:842
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 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.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
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'.
Implements an efficient mapping from strings to IdentifierInfo nodes.
In-memory cache for modules.
llvm::MemoryBuffer & addBuiltPCM(llvm::StringRef Filename, std::unique_ptr< llvm::MemoryBuffer > Buffer)
Store a just-built PCM under the Filename.
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:705
SourceLocation getAmpLoc() const
Definition: TypeLoc.h:1394
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:525
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
Definition: LangOptions.h:539
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:535
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:516
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
Definition: LangOptions.h:522
Used to hold and unique data used to represent #line information.
Record the location of a macro definition.
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition: MacroInfo.h:313
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Definition: MacroInfo.h:354
const MacroInfo * getMacroInfo() const
Definition: MacroInfo.h:416
Kind getKind() const
Definition: MacroInfo.h:346
SourceLocation getLocation() const
Definition: MacroInfo.h:348
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
bool isUsed() const
Return false if this macro is defined in the main file and has not yet been used.
Definition: MacroInfo.h:224
bool isC99Varargs() const
Definition: MacroInfo.h:207
SourceLocation getDefinitionEndLoc() const
Return the location of the last token in the macro.
Definition: MacroInfo.h:131
ArrayRef< const IdentifierInfo * > params() const
Definition: MacroInfo.h:185
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition: MacroInfo.h:235
unsigned getNumParams() const
Definition: MacroInfo.h:184
const Token & getReplacementToken(unsigned Tok) const
Definition: MacroInfo.h:237
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
Definition: MacroInfo.h:217
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Definition: MacroInfo.h:125
bool hasCommaPasting() const
Definition: MacroInfo.h:219
bool isObjectLike() const
Definition: MacroInfo.h:202
bool isUsedForHeaderGuard() const
Determine whether this macro was used for a header guard.
Definition: MacroInfo.h:294
bool isGNUVarargs() const
Definition: MacroInfo.h:208
SourceLocation getExpansionLoc() const
Definition: TypeLoc.h:1167
Expr * getAttrColumnOperand() const
The attribute's column operand, if it has one.
Definition: TypeLoc.h:1932
SourceRange getAttrOperandParensRange() const
The location of the parentheses around the operand, if there is an operand.
Definition: TypeLoc.h:1939
SourceLocation getAttrNameLoc() const
The location of the attribute name, i.e.
Definition: TypeLoc.h:1920
Expr * getAttrRowOperand() const
The attribute's row operand, if it has one.
Definition: TypeLoc.h:1926
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1332
TypeSourceInfo * getClassTInfo() const
Definition: TypeLoc.h:1346
SourceLocation getStarLoc() const
Definition: TypeLoc.h:1334
Abstract base class that writes a module file extension block into a module file.
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.
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
Definition: ModuleMap.cpp:1247
ArrayRef< KnownHeader > findResolvedModulesForHeader(FileEntryRef File) const
Like findAllModulesForHeader, but do not attempt to infer module ownership from umbrella headers if w...
Definition: ModuleMap.cpp:719
FileID getModuleMapFileIDForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module.
Definition: ModuleMap.cpp:1321
FileID getContainingModuleMapFileID(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
Definition: ModuleMap.cpp:1309
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:127
static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind)
Convert a header kind to a role. Requires Kind to not be HK_Excluded.
Definition: ModuleMap.cpp:93
Describes a module or submodule.
Definition: Module.h:105
unsigned IsExplicit
Whether this is an explicit submodule.
Definition: Module.h:327
SmallVector< ExportDecl, 2 > Exports
The set of export declarations.
Definition: Module.h:414
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition: Module.h:349
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition: Module.h:471
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:111
SmallVector< UnresolvedHeaderDirective, 1 > MissingHeaders
Headers that are mentioned in the module map file but could not be found on the file system.
Definition: Module.h:285
Module * Parent
The parent of this module.
Definition: Module.h:154
ModuleKind Kind
The kind of this module.
Definition: Module.h:150
@ HK_PrivateTextual
Definition: Module.h:243
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition: Module.h:505
SmallVector< Header, 2 > Headers[5]
The headers that are part of this module.
Definition: Module.h:265
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition: Module.h:401
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition: Module.h:332
std::string Name
The name of this module.
Definition: Module.h:108
llvm::iterator_range< submodule_iterator > submodules()
Definition: Module.h:782
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition: Module.h:338
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition: Module.h:377
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
Definition: Module.h:463
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition: Module.h:699
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition: Module.h:295
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:442
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition: Module.h:159
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition: Module.h:382
llvm::SmallSetVector< Module *, 2 > AffectingClangModules
The set of top-level modules that affected the compilation of this module, but were not imported.
Definition: Module.h:405
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition: Module.h:367
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition: Module.h:163
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition: Module.h:359
ArrayRef< FileEntryRef > getTopHeaders(FileManager &FileMgr)
The top-level headers associated with this module.
Definition: Module.cpp:282
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition: Module.h:691
bool isHeaderUnit() const
Is this module a header unit.
Definition: Module.h:612
@ ModuleMapModule
This is a module that was defined by a module map and built out of header files.
Definition: Module.h:119
unsigned IsFramework
Whether this is a framework module.
Definition: Module.h:323
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition: Module.h:179
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:244
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition: Module.h:354
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:665
std::vector< Conflict > Conflicts
The list of conflicts.
Definition: Module.h:496
This represents a decl that may have a name.
Definition: Decl.h:249
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
SourceRange getLocalSourceRange() const
Retrieve the source range covering just the last part of this nested-name-specifier,...
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
SpecifierKind
The kind of specifier that completes this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
This represents 'acq_rel' clause in the '#pragma omp atomic|flush' directives.
This represents 'acquire' clause in the '#pragma omp atomic|flush' directives.
This represents clause 'affinity' in the '#pragma omp task'-based directives.
This represents the 'align' clause in the '#pragma omp allocate' directive.
Definition: OpenMPClause.h:388
This represents clause 'aligned' in the '#pragma omp ...' directives.
This represents clause 'allocate' in the '#pragma omp ...' directives.
Definition: OpenMPClause.h:432
This represents 'allocator' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:354
This represents 'at' clause in the '#pragma omp error' directive.
This represents 'atomic_default_mem_order' clause in the '#pragma omp requires' directive.
This represents 'bind' clause in the '#pragma omp ...' directives.
This represents 'capture' clause in the '#pragma omp atomic' directive.
Contains data for OpenMP directives: clauses, children expressions/statements (helpers for codegen) a...
Class that handles post-update expression for some clauses, like 'lastprivate', 'reduction' etc.
Definition: OpenMPClause.h:233
Class that handles pre-initialization statement for some clauses, like 'shedule', 'firstprivate' etc.
Definition: OpenMPClause.h:195
This is a basic class for representing single OpenMP clause.
Definition: OpenMPClause.h:55
This represents 'collapse' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:977
This represents 'compare' clause in the '#pragma omp atomic' directive.
This represents clause 'copyin' in the '#pragma omp ...' directives.
This represents clause 'copyprivate' in the '#pragma omp ...' directives.
This represents 'default' clause in the '#pragma omp ...' directive.
This represents 'defaultmap' clause in the '#pragma omp ...' directive.
This represents implicit clause 'depend' for the '#pragma omp task' directive.
This represents implicit clause 'depobj' for the '#pragma omp depobj' directive.
This represents 'destroy' clause in the '#pragma omp depobj' directive or the '#pragma omp interop' d...
This represents 'detach' clause in the '#pragma omp task' directive.
This represents 'device' clause in the '#pragma omp ...' directive.
This represents 'dist_schedule' clause in the '#pragma omp ...' directive.
This represents the 'doacross' clause for the '#pragma omp ordered' directive.
This represents 'dynamic_allocators' clause in the '#pragma omp requires' directive.
This represents clause 'exclusive' in the '#pragma omp scan' directive.
This represents 'fail' clause in the '#pragma omp atomic' directive.
This represents 'filter' clause in the '#pragma omp ...' directive.
This represents 'final' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:630
This represents clause 'firstprivate' in the '#pragma omp ...' directives.
This represents implicit clause 'flush' for the '#pragma omp flush' directive.
This represents clause 'from' in the '#pragma omp ...' directives.
Representation of the 'full' clause of the '#pragma omp unroll' directive.
Definition: OpenMPClause.h:879
This represents 'grainsize' clause in the '#pragma omp ...' directive.
This represents clause 'has_device_ptr' in the '#pragma omp ...' directives.
This represents 'hint' clause in the '#pragma omp ...' directive.
This represents 'if' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:527
This represents clause 'in_reduction' in the '#pragma omp task' directives.
This represents clause 'inclusive' in the '#pragma omp scan' directive.
This represents the 'init' clause in '#pragma omp ...' directives.
This represents clause 'is_device_ptr' in the '#pragma omp ...' directives.
This represents clause 'lastprivate' in the '#pragma omp ...' directives.
This represents clause 'linear' in the '#pragma omp ...' directives.
This represents clause 'map' in the '#pragma omp ...' directives.
This represents 'mergeable' clause in the '#pragma omp ...' directive.
This represents 'message' clause in the '#pragma omp error' directive.
This represents 'nocontext' clause in the '#pragma omp ...' directive.
This represents 'nogroup' clause in the '#pragma omp ...' directive.
This represents clause 'nontemporal' in the '#pragma omp ...' directives.
This represents 'novariants' clause in the '#pragma omp ...' directive.
This represents 'nowait' clause in the '#pragma omp ...' directive.
This represents 'num_tasks' clause in the '#pragma omp ...' directive.
This represents 'num_teams' clause in the '#pragma omp ...' directive.
This represents 'num_threads' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:676
This represents 'order' clause in the '#pragma omp ...' directive.
This represents 'ordered' clause in the '#pragma omp ...' directive.
Representation of the 'partial' clause of the '#pragma omp unroll' directive.
Definition: OpenMPClause.h:907
This represents 'priority' clause in the '#pragma omp ...' directive.
This represents clause 'private' in the '#pragma omp ...' directives.
This represents 'proc_bind' clause in the '#pragma omp ...' directive.
This represents 'read' clause in the '#pragma omp atomic' directive.
This represents clause 'reduction' in the '#pragma omp ...' directives.
This represents 'relaxed' clause in the '#pragma omp atomic' directives.
This represents 'release' clause in the '#pragma omp atomic|flush' directives.
This represents 'reverse_offload' clause in the '#pragma omp requires' directive.
This represents 'simd' clause in the '#pragma omp ...' directive.
This represents 'safelen' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:721
This represents 'schedule' clause in the '#pragma omp ...' directive.
This represents 'seq_cst' clause in the '#pragma omp atomic' directive.
This represents 'severity' clause in the '#pragma omp error' directive.
This represents clause 'shared' in the '#pragma omp ...' directives.
This represents 'simdlen' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:756
This represents the 'sizes' clause in the '#pragma omp tile' directive.
Definition: OpenMPClause.h:788
This represents clause 'task_reduction' in the '#pragma omp taskgroup' directives.
This represents 'thread_limit' clause in the '#pragma omp ...' directive.
This represents 'threads' clause in the '#pragma omp ...' directive.
This represents clause 'to' in the '#pragma omp ...' directives.
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
This represents 'unified_address' clause in the '#pragma omp requires' directive.
This represents 'unified_shared_memory' clause in the '#pragma omp requires' directive.
This represents 'untied' clause in the '#pragma omp ...' directive.
This represents 'update' clause in the '#pragma omp atomic' directive.
This represents the 'use' clause in '#pragma omp ...' directives.
This represents clause 'use_device_addr' in the '#pragma omp ...' directives.
This represents clause 'use_device_ptr' in the '#pragma omp ...' directives.
This represents clause 'uses_allocators' in the '#pragma omp target'-based directives.
This represents 'weak' clause in the '#pragma omp atomic' directives.
This represents 'write' clause in the '#pragma omp atomic' directive.
This represents 'ompx_attribute' clause in a directive that might generate an outlined function.
This represents 'ompx_bare' clause in the '#pragma omp target teams ...' directive.
This represents 'ompx_dyn_cgroup_mem' clause in the '#pragma omp target ...' directive.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2326
Iterator that walks over the list of categories, filtering out those that do not meet specific criter...
Definition: DeclObjC.h:1597
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1541
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:1091
SourceLocation getNameEndLoc() const
Definition: TypeLoc.h:1109
SourceLocation getNameLoc() const
Definition: TypeLoc.h:1097
Wraps an ObjCPointerType with source location information.
Definition: TypeLoc.h:1370
SourceLocation getStarLoc() const
Definition: TypeLoc.h:1372
bool hasBaseTypeAsWritten() const
Definition: TypeLoc.h:1042
SourceLocation getTypeArgsLAngleLoc() const
Definition: TypeLoc.h:972
unsigned getNumTypeArgs() const
Definition: TypeLoc.h:988
unsigned getNumProtocols() const
Definition: TypeLoc.h:1018
TypeSourceInfo * getTypeArgTInfo(unsigned i) const
Definition: TypeLoc.h:992
SourceLocation getProtocolRAngleLoc() const
Definition: TypeLoc.h:1010
SourceLocation getProtocolLoc(unsigned i) const
Definition: TypeLoc.h:1022
SourceLocation getProtocolLAngleLoc() const
Definition: TypeLoc.h:1002
SourceLocation getTypeArgsRAngleLoc() const
Definition: TypeLoc.h:980
Kind getKind() const
Definition: ObjCRuntime.h:77
const VersionTuple & getVersion() const
Definition: ObjCRuntime.h:78
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition: TypeLoc.h:772
unsigned getNumProtocols() const
Definition: TypeLoc.h:809
SourceLocation getProtocolLoc(unsigned i) const
Definition: TypeLoc.h:813
SourceLocation getProtocolLAngleLoc() const
Definition: TypeLoc.h:789
SourceLocation getProtocolRAngleLoc() const
Definition: TypeLoc.h:799
This is the base type for all OpenACC Clauses.
Definition: OpenACCClause.h:22
OpenCL supported extensions and optional core features.
Definition: OpenCLOptions.h:69
SourceLocation getEllipsisLoc() const
Definition: TypeLoc.h:2578
SourceLocation getEllipsisLoc() const
Definition: TypeLoc.h:2111
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1195
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1191
Represents a parameter to a function.
Definition: Decl.h:1761
SourceLocation getKWLoc() const
Definition: TypeLoc.h:2673
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
SourceLocation getStarLoc() const
Definition: TypeLoc.h:1303
Iteration over the preprocessed entities.
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
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.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
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.
Definition: Preprocessor.h:128
ArrayRef< ModuleMacro * > getLeafModuleMacros(const IdentifierInfo *II) const
Get the list of leaf (non-overridden) module macros for a name.
ArrayRef< PPConditionalInfo > getPreambleConditionalStack() const
SourceLocation getModuleImportLoc(Module *M) 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.
unsigned getCounterValue() const
SourceManager & getSourceManager() const
std::optional< PreambleSkipInfo > getPreambleSkipInfo() const
bool hasRecordedPreamble() const
FileManager & getFileManager() const
PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
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
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
PreprocessingRecord * getPreprocessingRecord() const
Retrieve the preprocessing record, or NULL if there is no preprocessing record.
DiagnosticsEngine & getDiagnostics() 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: Type.h:940
Wrapper of type source information for a type with non-trivial direct qualifiers.
Definition: TypeLoc.h:289
The collection of all-type qualifiers we support.
Definition: Type.h:318
SourceLocation getAmpAmpLoc() const
Definition: TypeLoc.h:1408
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:4169
Wrapper for source info for record types.
Definition: TypeLoc.h:741
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
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
static uint32_t getRawEncoding(const AlignPackInfo &Info)
Definition: Sema.h:1233
llvm::DenseMap< Selector, Lists >::iterator iterator
Definition: Sema.h:11820
iterator find(Selector Sel)
Definition: Sema.h:11823
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
llvm::MapVector< Selector, SourceLocation > ReferencedSelectors
Method selectors used in a @selector expression.
Definition: Sema.h:11815
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:2618
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:4811
SemaCUDA & CUDA()
Definition: Sema.h:998
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1419
ExtVectorDeclsType ExtVectorDecls
ExtVectorDecls - This is a list all the extended vector types.
Definition: Sema.h:3593
SourceLocation getOptimizeOffPragmaLocation() const
Get the location for the currently active "\#pragma clang optimize off". If this location is invalid,...
Definition: Sema.h:1490
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1420
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:8825
ASTContext & Context
Definition: Sema.h:858
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:2626
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:6476
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition: Sema.h:4373
Preprocessor & PP
Definition: Sema.h:857
void updateOutOfDateSelector(Selector Sel)
llvm::MapVector< const FunctionDecl *, std::unique_ptr< LateParsedTemplate > > LateParsedTemplateMapT
Definition: Sema.h:8824
CXXRecordDecl * getStdBadAlloc() const
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition: Sema.h:1166
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:4379
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:1401
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:10530
bool MSStructPragmaOn
Definition: Sema.h:1163
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition: Sema.h:11840
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition: Sema.cpp:824
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:4814
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:10513
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:2633
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:2708
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:521
NamespaceDecl * getStdNamespace() const
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition: Sema.h:1161
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:2608
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:6480
IdentifierResolver IdResolver
Definition: Sema.h:2537
static uint64_t encode(SourceLocation Loc, SourceLocationSequence *=nullptr)
This object establishes a SourceLocationSequence.
Serialized encoding of a sequence of SourceLocations.
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.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation::UIntTy getNextLocalOffset() const
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.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
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.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const
Return the file characteristic of the specified source location, indicating whether this is a normal ...
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
One instance of this struct is kept for every file loaded or used.
OptionalFileEntryRef ContentsEntry
References the file which the contents were actually loaded from.
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.
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded,...
SourceLocation getExpansionLocStart() const
SourceLocation getSpellingLoc() const
SourceLocation getExpansionLocEnd() const
Information about a FileID, basically just the logical file that it represents and include stack info...
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.
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:864
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:857
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3585
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3688
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3739
Exposes information about the current target.
Definition: TargetInfo.h:213
Options for controlling the target.
Definition: TargetOptions.h:26
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
Definition: TargetOptions.h:58
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:45
std::string TuneCPU
If given, the name of the target CPU to tune code for.
Definition: TargetOptions.h:39
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line.
Definition: TargetOptions.h:54
A template argument list.
Definition: DeclTemplate.h:244
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:265
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
TemplateArgumentLocInfo getLocInfo() const
Definition: TemplateBase.h:576
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
ArgKind
The kind of template argument we're storing.
Definition: TemplateBase.h:64
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:1667
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1695
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:1675
SourceLocation getTemplateNameLoc() const
Definition: TypeLoc.h:1700
SourceLocation getTemplateKeywordLoc() const
Definition: TypeLoc.h:1659
Wrapper for template type parameters.
Definition: TypeLoc.h:758
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:187
unsigned getFlags() const
Return the internal represtation of the flags.
Definition: Token.h:262
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
unsigned getLength() const
Definition: Token.h:135
SourceLocation getAnnotationEndLoc() const
Definition: Token.h:146
void * getAnnotationValue() const
Definition: Token.h:234
tok::TokenKind getKind() const
Definition: Token.h:94
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:121
The top declaration context.
Definition: Decl.h:84
NamespaceDecl * getAnonymousNamespace() const
Definition: Decl.h:122
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:170
bool isNull() const
Definition: TypeLoc.h:121
TypeSourceInfo * getUnmodifiedTInfo() const
Definition: TypeLoc.h:2057
The type-property cache.
Definition: Type.cpp:4353
A container of type source information.
Definition: Type.h:7326
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7337
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
The base class of the type hierarchy.
Definition: Type.h:1813
TypeClass getTypeClass() const
Definition: Type.h:2300
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3433
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:2000
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:2008
SourceLocation getTypeofLoc() const
Definition: TypeLoc.h:1992
SourceLocation getKWLoc() const
Definition: TypeLoc.h:2139
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:2145
TypeSourceInfo * getUnderlyingTInfo() const
Definition: TypeLoc.h:2148
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:2142
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Wrapper for source info for unresolved typename using decls.
Definition: TypeLoc.h:716
Wrapper for source info for types used via transparent aliases.
Definition: TypeLoc.h:682
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
Represents a variable declaration or definition.
Definition: Decl.h:918
EvaluatedStmt * getEvaluatedStmt() const
Definition: Decl.cpp:2547
const Expr * getInit() const
Definition: Decl.h:1355
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition: Decl.cpp:2604
Declaration of a variable template.
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getNameLoc() const
Definition: TypeLoc.h:1839
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
SourceLocation getEllipsisLoc() const
Retrieve the source location of the ellipsis, whose presence indicates that the capture is a pack exp...
Definition: ScopeInfo.h:690
A key used when looking up entities by DeclarationName.
Definition: ASTBitCodes.h:2017
Information about a module that has been loaded by the ASTReader.
Definition: ModuleFile.h:124
serialization::IdentID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition: ModuleFile.h:315
serialization::DeclID BaseDeclID
Base declaration ID for declarations local to this module.
Definition: ModuleFile.h:462
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition: ModuleFile.h:374
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition: ModuleFile.h:502
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition: ModuleFile.h:305
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition: ModuleFile.h:427
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition: ModuleFile.h:407
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition: ModuleFile.h:523
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition: ModuleFile.h:282
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition: ModuleFile.h:410
unsigned LocalNumTypes
The number of types in this AST file.
Definition: ModuleFile.h:494
std::string FileName
The file name of the module file.
Definition: ModuleFile.h:139
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition: ModuleFile.h:288
unsigned LocalNumMacros
The number of macros in this AST file.
Definition: ModuleFile.h:341
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition: ModuleFile.h:455
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition: ModuleFile.h:420
ModuleKind Kind
The type of this module.
Definition: ModuleFile.h:136
std::string ModuleName
The name of the module.
Definition: ModuleFile.h:142
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
Definition: ModuleFile.h:355
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:47
A type index; the type ID with the qualifier bits removed.
Definition: ASTBitCodes.h:80
uint32_t getIndex() const
Definition: ASTBitCodes.h:87
Class that performs name lookup into a DeclContext stored in an AST file.
const unsigned int LOCAL_REDECLARATIONS
Record code for a list of local redeclarations of a declaration.
Definition: ASTBitCodes.h:1166
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:1103
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:1117
const unsigned int DECL_UPDATES
Record of updates for a declaration that was modified after being deserialized.
Definition: ASTBitCodes.h:1162
@ DECL_EMPTY
An EmptyDecl record.
Definition: ASTBitCodes.h:1422
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1393
@ DECL_CXX_RECORD
A CXXRecordDecl record.
Definition: ASTBitCodes.h:1324
@ DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION
A VarTemplatePartialSpecializationDecl record.
Definition: ASTBitCodes.h:1366
@ DECL_OMP_ALLOCATE
An OMPAllocateDcl record.
Definition: ASTBitCodes.h:1419
@ DECL_MS_PROPERTY
A MSPropertyDecl record.
Definition: ASTBitCodes.h:1230
@ DECL_REQUIRES_EXPR_BODY
A RequiresExprBodyDecl record.
Definition: ASTBitCodes.h:1428
@ DECL_STATIC_ASSERT
A StaticAssertDecl record.
Definition: ASTBitCodes.h:1390
@ DECL_INDIRECTFIELD
A IndirectFieldDecl record.
Definition: ASTBitCodes.h:1399
@ DECL_TEMPLATE_TEMPLATE_PARM
A TemplateTemplateParmDecl record.
Definition: ASTBitCodes.h:1378
@ DECL_IMPORT
An ImportDecl recording a module import.
Definition: ASTBitCodes.h:1410
@ DECL_ACCESS_SPEC
An AccessSpecDecl record.
Definition: ASTBitCodes.h:1342
@ DECL_OBJC_TYPE_PARAM
An ObjCTypeParamDecl record.
Definition: ASTBitCodes.h:1431
@ DECL_OBJC_CATEGORY_IMPL
A ObjCCategoryImplDecl record.
Definition: ASTBitCodes.h:1212
@ DECL_ENUM_CONSTANT
An EnumConstantDecl record.
Definition: ASTBitCodes.h:1188
@ DECL_PARM_VAR
A ParmVarDecl record.
Definition: ASTBitCodes.h:1245
@ DECL_TYPEDEF
A TypedefDecl record.
Definition: ASTBitCodes.h:1176
@ DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK
A TemplateTemplateParmDecl record that stores an expanded template template parameter pack.
Definition: ASTBitCodes.h:1407
@ DECL_HLSL_BUFFER
A HLSLBufferDecl record.
Definition: ASTBitCodes.h:1452
@ DECL_NAMESPACE_ALIAS
A NamespaceAliasDecl record.
Definition: ASTBitCodes.h:1291
@ DECL_TYPEALIAS
A TypeAliasDecl record.
Definition: ASTBitCodes.h:1179
@ DECL_FUNCTION_TEMPLATE
A FunctionTemplateDecl record.
Definition: ASTBitCodes.h:1369
@ DECL_UNRESOLVED_USING_TYPENAME
An UnresolvedUsingTypenameDecl record.
Definition: ASTBitCodes.h:1315
@ DECL_CLASS_TEMPLATE_SPECIALIZATION
A ClassTemplateSpecializationDecl record.
Definition: ASTBitCodes.h:1354
@ DECL_FILE_SCOPE_ASM
A FileScopeAsmDecl record.
Definition: ASTBitCodes.h:1254
@ DECL_CXX_CONSTRUCTOR
A CXXConstructorDecl record.
Definition: ASTBitCodes.h:1333
@ DECL_CXX_CONVERSION
A CXXConversionDecl record.
Definition: ASTBitCodes.h:1339
@ DECL_FIELD
A FieldDecl record.
Definition: ASTBitCodes.h:1227
@ DECL_LINKAGE_SPEC
A LinkageSpecDecl record.
Definition: ASTBitCodes.h:1318
@ DECL_NAMESPACE
A NamespaceDecl record.
Definition: ASTBitCodes.h:1288
@ DECL_NON_TYPE_TEMPLATE_PARM
A NonTypeTemplateParmDecl record.
Definition: ASTBitCodes.h:1375
@ DECL_FUNCTION
A FunctionDecl record.
Definition: ASTBitCodes.h:1191
@ DECL_USING_DIRECTIVE
A UsingDirecitveDecl record.
Definition: ASTBitCodes.h:1309
@ DECL_RECORD
A RecordDecl record.
Definition: ASTBitCodes.h:1185
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
Definition: ASTBitCodes.h:1273
@ DECL_BLOCK
A BlockDecl record.
Definition: ASTBitCodes.h:1260
@ DECL_UNRESOLVED_USING_VALUE
An UnresolvedUsingValueDecl record.
Definition: ASTBitCodes.h:1312
@ DECL_TYPE_ALIAS_TEMPLATE
A TypeAliasTemplateDecl record.
Definition: ASTBitCodes.h:1381
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1396
@ DECL_OBJC_CATEGORY
A ObjCCategoryDecl record.
Definition: ASTBitCodes.h:1209
@ DECL_VAR
A VarDecl record.
Definition: ASTBitCodes.h:1239
@ DECL_USING
A UsingDecl record.
Definition: ASTBitCodes.h:1294
@ DECL_OBJC_PROTOCOL
A ObjCProtocolDecl record.
Definition: ASTBitCodes.h:1200
@ DECL_TEMPLATE_TYPE_PARM
A TemplateTypeParmDecl record.
Definition: ASTBitCodes.h:1372
@ DECL_VAR_TEMPLATE_SPECIALIZATION
A VarTemplateSpecializationDecl record.
Definition: ASTBitCodes.h:1363
@ DECL_OBJC_IMPLEMENTATION
A ObjCImplementationDecl record.
Definition: ASTBitCodes.h:1215
@ DECL_OBJC_COMPATIBLE_ALIAS
A ObjCCompatibleAliasDecl record.
Definition: ASTBitCodes.h:1218
@ DECL_FRIEND_TEMPLATE
A FriendTemplateDecl record.
Definition: ASTBitCodes.h:1348
@ DECL_PRAGMA_DETECT_MISMATCH
A PragmaDetectMismatchDecl record.
Definition: ASTBitCodes.h:1440
@ DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK
A NonTypeTemplateParmDecl record that stores an expanded non-type template parameter pack.
Definition: ASTBitCodes.h:1403
@ DECL_OBJC_AT_DEFS_FIELD
A ObjCAtDefsFieldDecl record.
Definition: ASTBitCodes.h:1206
@ DECL_IMPLICIT_PARAM
An ImplicitParamDecl record.
Definition: ASTBitCodes.h:1242
@ DECL_FRIEND
A FriendDecl record.
Definition: ASTBitCodes.h:1345
@ DECL_CXX_METHOD
A CXXMethodDecl record.
Definition: ASTBitCodes.h:1330
@ DECL_PRAGMA_COMMENT
A PragmaCommentDecl record.
Definition: ASTBitCodes.h:1437
@ DECL_ENUM
An EnumDecl record.
Definition: ASTBitCodes.h:1182
@ DECL_OMP_DECLARE_REDUCTION
An OMPDeclareReductionDecl record.
Definition: ASTBitCodes.h:1446
@ DECL_OMP_THREADPRIVATE
An OMPThreadPrivateDecl record.
Definition: ASTBitCodes.h:1413
@ DECL_OBJC_METHOD
A ObjCMethodDecl record.
Definition: ASTBitCodes.h:1194
@ DECL_CXX_DESTRUCTOR
A CXXDestructorDecl record.
Definition: ASTBitCodes.h:1336
@ DECL_OMP_CAPTUREDEXPR
An OMPCapturedExprDecl record.
Definition: ASTBitCodes.h:1434
@ DECL_CLASS_TEMPLATE
A ClassTemplateDecl record.
Definition: ASTBitCodes.h:1351
@ DECL_USING_SHADOW
A UsingShadowDecl record.
Definition: ASTBitCodes.h:1303
@ DECL_CONCEPT
A ConceptDecl record.
Definition: ASTBitCodes.h:1384
@ DECL_OBJC_IVAR
A ObjCIvarDecl record.
Definition: ASTBitCodes.h:1203
@ DECL_OBJC_PROPERTY
A ObjCPropertyDecl record.
Definition: ASTBitCodes.h:1221
@ DECL_OBJC_INTERFACE
A ObjCInterfaceDecl record.
Definition: ASTBitCodes.h:1197
@ DECL_VAR_TEMPLATE
A VarTemplateDecl record.
Definition: ASTBitCodes.h:1360
@ DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION
A ClassTemplatePartialSpecializationDecl record.
Definition: ASTBitCodes.h:1357
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1282
@ DECL_OBJC_PROPERTY_IMPL
A ObjCPropertyImplDecl record.
Definition: ASTBitCodes.h:1224
@ TYPE_EXT_QUAL
An ExtQualType record.
Definition: ASTBitCodes.h:1123
@ EXPR_DESIGNATED_INIT
A DesignatedInitExpr record.
Definition: ASTBitCodes.h:1614
@ EXPR_COMPOUND_LITERAL
A CompoundLiteralExpr record.
Definition: ASTBitCodes.h:1605
@ EXPR_OBJC_IVAR_REF_EXPR
An ObjCIvarRefExpr record.
Definition: ASTBitCodes.h:1689
@ EXPR_MEMBER
A MemberExpr record.
Definition: ASTBitCodes.h:1587
@ EXPR_CXX_TEMPORARY_OBJECT
A CXXTemporaryObjectExpr record.
Definition: ASTBitCodes.h:1763
@ EXPR_COMPOUND_ASSIGN_OPERATOR
A CompoundAssignOperator record.
Definition: ASTBitCodes.h:1593
@ EXPR_CXX_STATIC_CAST
A CXXStaticCastExpr record.
Definition: ASTBitCodes.h:1766
@ EXPR_OBJC_STRING_LITERAL
An ObjCStringLiteral record.
Definition: ASTBitCodes.h:1673
@ EXPR_VA_ARG
A VAArgExpr record.
Definition: ASTBitCodes.h:1632
@ EXPR_CXX_OPERATOR_CALL
A CXXOperatorCallExpr record.
Definition: ASTBitCodes.h:1748
@ STMT_OBJC_AT_TRY
An ObjCAtTryStmt record.
Definition: ASTBitCodes.h:1719
@ STMT_DO
A DoStmt record.
Definition: ASTBitCodes.h:1506
@ STMT_OBJC_CATCH
An ObjCAtCatchStmt record.
Definition: ASTBitCodes.h:1713
@ STMT_IF
An IfStmt record.
Definition: ASTBitCodes.h:1497
@ EXPR_STRING_LITERAL
A StringLiteral record.
Definition: ASTBitCodes.h:1557
@ EXPR_IMPLICIT_CAST
An ImplicitCastExpr record.
Definition: ASTBitCodes.h:1599
@ STMT_GCCASM
A GCC-style AsmStmt record.
Definition: ASTBitCodes.h:1533
@ EXPR_IMAGINARY_LITERAL
An ImaginaryLiteral record.
Definition: ASTBitCodes.h:1554
@ STMT_WHILE
A WhileStmt record.
Definition: ASTBitCodes.h:1503
@ EXPR_STMT
A StmtExpr record.
Definition: ASTBitCodes.h:1638
@ EXPR_CXX_REINTERPRET_CAST
A CXXReinterpretCastExpr record.
Definition: ASTBitCodes.h:1772
@ EXPR_DESIGNATED_INIT_UPDATE
A DesignatedInitUpdateExpr record.
Definition: ASTBitCodes.h:1617
@ STMT_OBJC_AT_SYNCHRONIZED
An ObjCAtSynchronizedStmt record.
Definition: ASTBitCodes.h:1722
@ EXPR_CHARACTER_LITERAL
A CharacterLiteral record.
Definition: ASTBitCodes.h:1560
@ EXPR_OBJC_ENCODE
An ObjCEncodeExpr record.
Definition: ASTBitCodes.h:1680
@ EXPR_CSTYLE_CAST
A CStyleCastExpr record.
Definition: ASTBitCodes.h:1602
@ EXPR_OBJC_BOOL_LITERAL
An ObjCBoolLiteralExpr record.
Definition: ASTBitCodes.h:1731
@ EXPR_EXT_VECTOR_ELEMENT
An ExtVectorElementExpr record.
Definition: ASTBitCodes.h:1608
@ STMT_RETURN
A ReturnStmt record.
Definition: ASTBitCodes.h:1524
@ STMT_OBJC_FOR_COLLECTION
An ObjCForCollectionStmt record.
Definition: ASTBitCodes.h:1710
@ STMT_CONTINUE
A ContinueStmt record.
Definition: ASTBitCodes.h:1518
@ EXPR_PREDEFINED
A PredefinedExpr record.
Definition: ASTBitCodes.h:1542
@ EXPR_CXX_BOOL_LITERAL
A CXXBoolLiteralExpr record.
Definition: ASTBitCodes.h:1793
@ EXPR_PAREN_LIST
A ParenListExpr record.
Definition: ASTBitCodes.h:1566
@ EXPR_CXX_PAREN_LIST_INIT
A CXXParenListInitExpr record.
Definition: ASTBitCodes.h:1796
@ STMT_COMPOUND
A CompoundStmt record.
Definition: ASTBitCodes.h:1482
@ STMT_FOR
A ForStmt record.
Definition: ASTBitCodes.h:1509
@ STMT_ATTRIBUTED
An AttributedStmt record.
Definition: ASTBitCodes.h:1494
@ EXPR_CXX_REWRITTEN_BINARY_OPERATOR
A CXXRewrittenBinaryOperator record.
Definition: ASTBitCodes.h:1754
@ STMT_GOTO
A GotoStmt record.
Definition: ASTBitCodes.h:1512
@ EXPR_NO_INIT
An NoInitExpr record.
Definition: ASTBitCodes.h:1620
@ EXPR_OBJC_PROTOCOL_EXPR
An ObjCProtocolExpr record.
Definition: ASTBitCodes.h:1686
@ EXPR_CXX_CONSTRUCT
A CXXConstructExpr record.
Definition: ASTBitCodes.h:1757
@ EXPR_CXX_DYNAMIC_CAST
A CXXDynamicCastExpr record.
Definition: ASTBitCodes.h:1769
@ STMT_CXX_TRY
A CXXTryStmt record.
Definition: ASTBitCodes.h:1742
@ EXPR_GENERIC_SELECTION
A GenericSelectionExpr record.
Definition: ASTBitCodes.h:1659
@ EXPR_CALL
A CallExpr record.
Definition: ASTBitCodes.h:1584
@ EXPR_GNU_NULL
A GNUNullExpr record.
Definition: ASTBitCodes.h:1644
@ EXPR_OBJC_PROPERTY_REF_EXPR
An ObjCPropertyRefExpr record.
Definition: ASTBitCodes.h:1692
@ EXPR_CXX_CONST_CAST
A CXXConstCastExpr record.
Definition: ASTBitCodes.h:1775
@ STMT_REF_PTR
A reference to a previously [de]serialized Stmt record.
Definition: ASTBitCodes.h:1476
@ EXPR_OBJC_MESSAGE_EXPR
An ObjCMessageExpr record.
Definition: ASTBitCodes.h:1701
@ STMT_CASE
A CaseStmt record.
Definition: ASTBitCodes.h:1485
@ STMT_STOP
A marker record that indicates that we are at the end of an expression.
Definition: ASTBitCodes.h:1470
@ STMT_MSASM
A MS-style AsmStmt record.
Definition: ASTBitCodes.h:1536
@ EXPR_CONDITIONAL_OPERATOR
A ConditionOperator record.
Definition: ASTBitCodes.h:1596
@ EXPR_BINARY_OPERATOR
A BinaryOperator record.
Definition: ASTBitCodes.h:1590
@ EXPR_CXX_STD_INITIALIZER_LIST
A CXXStdInitializerListExpr record.
Definition: ASTBitCodes.h:1790
@ EXPR_SHUFFLE_VECTOR
A ShuffleVectorExpr record.
Definition: ASTBitCodes.h:1650
@ STMT_OBJC_FINALLY
An ObjCAtFinallyStmt record.
Definition: ASTBitCodes.h:1716
@ EXPR_OBJC_SELECTOR_EXPR
An ObjCSelectorExpr record.
Definition: ASTBitCodes.h:1683
@ EXPR_FLOATING_LITERAL
A FloatingLiteral record.
Definition: ASTBitCodes.h:1551
@ STMT_NULL_PTR
A NULL expression.
Definition: ASTBitCodes.h:1473
@ STMT_DEFAULT
A DefaultStmt record.
Definition: ASTBitCodes.h:1488
@ EXPR_CHOOSE
A ChooseExpr record.
Definition: ASTBitCodes.h:1641
@ STMT_NULL
A NullStmt record.
Definition: ASTBitCodes.h:1479
@ EXPR_BLOCK
BlockExpr.
Definition: ASTBitCodes.h:1656
@ EXPR_DECL_REF
A DeclRefExpr record.
Definition: ASTBitCodes.h:1545
@ EXPR_INIT_LIST
An InitListExpr record.
Definition: ASTBitCodes.h:1611
@ EXPR_IMPLICIT_VALUE_INIT
An ImplicitValueInitExpr record.
Definition: ASTBitCodes.h:1629
@ EXPR_PAREN
A ParenExpr record.
Definition: ASTBitCodes.h:1563
@ STMT_LABEL
A LabelStmt record.
Definition: ASTBitCodes.h:1491
@ EXPR_CXX_FUNCTIONAL_CAST
A CXXFunctionalCastExpr record.
Definition: ASTBitCodes.h:1781
@ EXPR_USER_DEFINED_LITERAL
A UserDefinedLiteral record.
Definition: ASTBitCodes.h:1787
@ EXPR_INTEGER_LITERAL
An IntegerLiteral record.
Definition: ASTBitCodes.h:1548
@ EXPR_CXX_MEMBER_CALL
A CXXMemberCallExpr record.
Definition: ASTBitCodes.h:1751
@ STMT_SWITCH
A SwitchStmt record.
Definition: ASTBitCodes.h:1500
@ STMT_DECL
A DeclStmt record.
Definition: ASTBitCodes.h:1527
@ EXPR_OBJC_KVC_REF_EXPR
UNUSED.
Definition: ASTBitCodes.h:1698
@ EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK
Definition: ASTBitCodes.h:1832
@ EXPR_SIZEOF_ALIGN_OF
A SizefAlignOfExpr record.
Definition: ASTBitCodes.h:1575
@ STMT_BREAK
A BreakStmt record.
Definition: ASTBitCodes.h:1521
@ STMT_OBJC_AT_THROW
An ObjCAtThrowStmt record.
Definition: ASTBitCodes.h:1725
@ EXPR_ADDR_LABEL
An AddrLabelExpr record.
Definition: ASTBitCodes.h:1635
@ STMT_CXX_FOR_RANGE
A CXXForRangeStmt record.
Definition: ASTBitCodes.h:1745
@ EXPR_CXX_ADDRSPACE_CAST
A CXXAddrspaceCastExpr record.
Definition: ASTBitCodes.h:1778
@ EXPR_ARRAY_SUBSCRIPT
An ArraySubscriptExpr record.
Definition: ASTBitCodes.h:1578
@ EXPR_UNARY_OPERATOR
A UnaryOperator record.
Definition: ASTBitCodes.h:1569
@ STMT_CXX_CATCH
A CXXCatchStmt record.
Definition: ASTBitCodes.h:1739
@ STMT_INDIRECT_GOTO
An IndirectGotoStmt record.
Definition: ASTBitCodes.h:1515
Defines the clang::TargetInfo interface.
bool isSystem(CharacteristicKind CK)
Determine whether a file / directory characteristic is for system code.
Definition: SourceManager.h:90
bool isModuleMap(CharacteristicKind CK)
Determine whether a file characteristic is for a module map.
Definition: SourceManager.h:95
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:882
@ EXTENSION_METADATA
Metadata describing this particular extension.
Definition: ASTBitCodes.h:408
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:77
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
Definition: ASTBitCodes.h:798
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:780
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:818
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:777
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
Definition: ASTBitCodes.h:826
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
Definition: ASTBitCodes.h:783
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:774
@ SUBMODULE_METADATA
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:766
@ SUBMODULE_REQUIRES
Specifies a required feature.
Definition: ASTBitCodes.h:794
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:810
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:787
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
Definition: ASTBitCodes.h:807
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
Definition: ASTBitCodes.h:822
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:770
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:801
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:804
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:791
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:814
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
Definition: ASTBitCodes.h:829
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition: ASTBitCodes.h:129
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:163
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
Definition: ASTBitCodes.h:372
@ TARGET_OPTIONS
Record code for the target options table.
Definition: ASTBitCodes.h:369
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
Definition: ASTBitCodes.h:378
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
Definition: ASTBitCodes.h:375
@ LANGUAGE_OPTIONS
Record code for the language options table.
Definition: ASTBitCodes.h:366
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:145
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
Definition: ASTBitCodes.h:265
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:160
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
Definition: ASTBitCodes.h:166
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
Definition: ASTBitCodes.h:290
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
Definition: ASTBitCodes.h:287
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
Definition: ASTBitCodes.h:272
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
Definition: ASTBitCodes.h:276
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
Definition: ASTBitCodes.h:298
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
Definition: ASTBitCodes.h:284
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
Definition: ASTBitCodes.h:280
@ COMMENTS_BLOCK_ID
The block containing comments.
Definition: ASTBitCodes.h:293
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
Definition: ASTBitCodes.h:320
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
Definition: ASTBitCodes.h:314
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
Definition: ASTBitCodes.h:311
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
Definition: ASTBitCodes.h:304
uint32_t IdentID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:126
const unsigned VERSION_MINOR
AST file minor version number supported by this version of Clang.
Definition: ASTBitCodes.h:55
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:703
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:717
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:707
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:713
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:721
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
Definition: ASTBitCodes.h:148
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
Definition: ASTCommon.cpp:456
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:45
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:65
TypeID MakeTypeID(ASTContext &Context, QualType T, IdxForTypeTy IdxForType)
Definition: ASTCommon.h:50
@ PP_TOKEN
Describes one token.
Definition: ASTBitCodes.h:740
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
Definition: ASTBitCodes.h:736
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
Definition: ASTBitCodes.h:731
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:743
@ PP_MODULE_MACRO
A macro directive exported by a module.
Definition: ASTBitCodes.h:747
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:96
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
Definition: ASTBitCodes.h:351
@ MODULE_DIRECTORY
Record code for the module build directory.
Definition: ASTBitCodes.h:354
@ IMPORTS
Record code for the list of other AST files imported by this AST file.
Definition: ASTBitCodes.h:331
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
Definition: ASTBitCodes.h:340
@ MODULE_NAME
Record code for the module name.
Definition: ASTBitCodes.h:347
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
Definition: ASTBitCodes.h:336
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
Definition: ASTBitCodes.h:344
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
Definition: ASTBitCodes.h:327
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:390
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
Definition: ASTBitCodes.h:399
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
Definition: ASTBitCodes.h:387
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:396
@ SIGNATURE
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:384
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
Definition: ASTBitCodes.h:393
@ VFS_USAGE
Record code for the indices of used VFSs.
Definition: ASTBitCodes.h:402
@ INPUT_FILE_HASH
The input file content hash.
Definition: ASTBitCodes.h:421
@ INPUT_FILE
An input file.
Definition: ASTBitCodes.h:418
const DeclContext * getDefinitiveDeclContext(const DeclContext *DC)
Retrieve the "definitive" declaration that provides all of the visible entries for the given declarat...
Definition: ASTCommon.cpp:293
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:760
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:753
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:756
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
Definition: ASTBitCodes.h:142
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:566
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:500
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
Definition: ASTBitCodes.h:686
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:592
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:496
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:555
@ TYPE_OFFSET
Record code for the offsets of each type.
Definition: ASTBitCodes.h:438
@ DELEGATING_CTORS
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:588
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
Definition: ASTBitCodes.h:692
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:525
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:585
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:582
@ VTABLE_USES
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:535
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
Definition: ASTBitCodes.h:642
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
Definition: ASTBitCodes.h:683
@ DECL_OFFSET
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:450
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:602
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
Definition: ASTBitCodes.h:516
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:653
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:562
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched #pragma clang cuda_force_host_device begin directives we've seen.
Definition: ASTBitCodes.h:663
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:630
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:532
@ OPENCL_EXTENSION_DECLS
Record code for declarations associated with OpenCL extensions.
Definition: ASTBitCodes.h:669
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:458
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:623
@ METHOD_POOL
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:512
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
Definition: ASTBitCodes.h:696
@ PP_CONDITIONAL_STACK
The stack of open #ifs/#ifdefs recorded in a preamble.
Definition: ASTBitCodes.h:677
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
Definition: ASTBitCodes.h:540
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:520
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:552
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
Definition: ASTBitCodes.h:639
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:609
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:656
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:503
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:528
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
Definition: ASTBitCodes.h:674
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
Definition: ASTBitCodes.h:613
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:509
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:648
@ OPENCL_EXTENSION_TYPES
Record code for types associated with OpenCL extensions.
Definition: ASTBitCodes.h:666
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:487
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
Definition: ASTBitCodes.h:635
@ HEADER_SEARCH_TABLE
Record code for header search information.
Definition: ASTBitCodes.h:579
@ OBJC_CATEGORIES_MAP
Record code for map of Objective-C class definition IDs to the ObjC categories in a module that are a...
Definition: ASTBitCodes.h:606
@ METADATA_OLD_FORMAT
This is so that older clang versions, before the introduction of the control block,...
Definition: ASTBitCodes.h:463
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:576
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:544
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
Definition: ASTBitCodes.h:680
@ IDENTIFIER_TABLE
Record code for the identifier table.
Definition: ASTBitCodes.h:477
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:549
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:645
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:598
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:659
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:132
unsigned ComputeHash(Selector Sel)
Definition: ASTCommon.cpp:281
@ UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER
Definition: ASTCommon.h:33
@ UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION
Definition: ASTCommon.h:26
@ UPD_DECL_MARKED_OPENMP_DECLARETARGET
Definition: ASTCommon.h:42
@ UPD_CXX_POINT_OF_INSTANTIATION
Definition: ASTCommon.h:30
@ UPD_CXX_RESOLVED_EXCEPTION_SPEC
Definition: ASTCommon.h:35
@ UPD_CXX_ADDED_FUNCTION_DEFINITION
Definition: ASTCommon.h:28
@ UPD_DECL_MARKED_OPENMP_THREADPRIVATE
Definition: ASTCommon.h:40
@ UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT
Definition: ASTCommon.h:32
@ UPD_DECL_MARKED_OPENMP_ALLOCATE
Definition: ASTCommon.h:41
@ UPD_CXX_ADDED_ANONYMOUS_NAMESPACE
Definition: ASTCommon.h:27
@ UPD_CXX_INSTANTIATED_CLASS_DEFINITION
Definition: ASTCommon.h:31
RangeSelector range(RangeSelector Begin, RangeSelector End)
DEPRECATED. Use enclose.
Definition: RangeSelector.h:41
std::shared_ptr< MatchComputation< T > > Generator
Definition: RewriteRule.h:65
The JSON file list parser is used to communicate input to InstallAPI.
@ Auto
'auto' clause, allowed on 'loop' directives.
@ Bind
'bind' clause, allowed on routine constructs.
@ Gang
'gang' clause, allowed on 'loop' and Combined constructs.
@ Wait
'wait' clause, allowed on Compute, Data, 'update', and Combined constructs.
@ DevicePtr
'deviceptr' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ VectorLength
'vector_length' clause, allowed on 'parallel', 'kernels', 'parallel loop', and 'kernels loop' constru...
@ Async
'async' clause, allowed on Compute, Data, 'update', 'wait', and Combined constructs.
@ Collapse
'collapse' clause, allowed on 'loop' and Combined constructs.
@ NoHost
'nohost' clause, allowed on 'routine' directives.
@ DeviceNum
'device_num' clause, allowed on 'init', 'shutdown', and 'set' constructs.
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
@ Invalid
Represents an invalid clause, for the purposes of parsing.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Copy
'copy' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ Worker
'worker' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Create
'copyin' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ DeviceType
'device_type' clause, allowed on Compute, 'data', 'init', 'shutdown', 'set', update',...
@ DefaultAsync
'default_async' clause, allowed on 'set' construct.
@ Attach
'attach' clause, allowed on Compute and Combined constructs, plus 'data' and 'enter data'.
@ NumGangs
'num_gangs' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Default
'default' clause, allowed on parallel, serial, kernel (and compound) constructs.
@ UseDevice
'use_device' clause, allowed on 'host_data' construct.
@ NoCreate
'no_create' clause, allowed on allowed on Compute and Combined constructs, plus 'data'.
@ Link
'link' clause, allowed on 'declare' construct.
@ Reduction
'reduction' clause, allowed on Parallel, Serial, Loop, and the combined constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ CopyOut
'copyout' clause, allowed on Compute and Combined constructs, plus 'data', 'exit data',...
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ FirstPrivate
'firstprivate' clause, allowed on 'parallel', 'serial', 'parallel loop', and 'serial loop' constructs...
@ Host
'host' clause, allowed on 'update' construct.
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
@ DeviceResident
'device_resident' clause, allowed on the 'declare' construct.
@ Present
'present' clause, allowed on Compute and Combined constructs, plus 'data' and 'declare'.
@ DType
'dtype' clause, an alias for 'device_type', stored separately for diagnostic purposes.
@ CopyIn
'copyin' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ Device
'device' clause, allowed on the 'update' construct.
@ Independent
'independent' clause, allowed on 'loop' directives.
@ NumWorkers
'num_workers' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs...
@ IfPresent
'if_present' clause, allowed on 'host_data' and 'update' directives.
@ Detach
'detach' clause, allowed on the 'exit data' construct.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ Finalize
'finalize' clause, allowed on 'exit data' directive.
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ CPlusPlus
Definition: LangStandard.h:55
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
static constexpr unsigned NumberOfOMPMapClauseModifiers
Number of allowed map-type-modifiers.
Definition: OpenMPKinds.h:87
const unsigned int NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition: DeclID.h:90
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
PredefinedDeclIDs
Predefined declaration IDs.
Definition: DeclID.h:30
@ PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID
The internal '__NSConstantString' tag type.
Definition: DeclID.h:80
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition: DeclID.h:35
@ PREDEF_DECL_TYPE_PACK_ELEMENT_ID
The internal '__type_pack_element' template.
Definition: DeclID.h:83
@ PREDEF_DECL_OBJC_CLASS_ID
The Objective-C 'Class' type.
Definition: DeclID.h:44
@ PREDEF_DECL_BUILTIN_MS_GUID_ID
The predeclared '_GUID' struct.
Definition: DeclID.h:68
@ PREDEF_DECL_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition: DeclID.h:56
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition: DeclID.h:47
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition: DeclID.h:53
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition: DeclID.h:41
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition: DeclID.h:50
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition: DeclID.h:62
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition: DeclID.h:65
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition: DeclID.h:77
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition: DeclID.h:59
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition: DeclID.h:71
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition: DeclID.h:38
@ PREDEF_DECL_MAKE_INTEGER_SEQ_ID
The internal '__make_integer_seq' template.
Definition: DeclID.h:74
@ Property
The type of a property.
@ Result
The result type of a method or function.
bool CanElideDeclDef(const Decl *D)
If we can elide the definition of.
static constexpr unsigned NumberOfOMPMotionModifiers
Number of allowed motion-modifiers.
Definition: OpenMPKinds.h:99
@ PMSST_ON
Definition: PragmaKinds.h:25
@ PMSST_OFF
Definition: PragmaKinds.h:24
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
for(const auto &A :T->param_types())
const FunctionProtoType * T
bool shouldSkipCheckingODR(const Decl *D)
Definition: ASTReader.h:2467
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:68
@ None
The alignment was not explicit in code.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
unsigned long uint64_t
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...
The signature of a module, which is a hash of the AST content.
Definition: Module.h:57
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition: Module.h:75
static ASTFileSignature createDummy()
Definition: Module.h:85
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:691
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments.
Definition: TemplateBase.h:700
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:688
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:694
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:883
The preprocessor keeps track of this information for each file that is #included.
Definition: HeaderSearch.h:58
unsigned isModuleHeader
Whether this header is part of and built with a module.
Definition: HeaderSearch.h:91
unsigned isCompilingModuleHeader
Whether this header is part of the module that we are building, even if it doesn't build with the mod...
Definition: HeaderSearch.h:101
unsigned IsLocallyIncluded
True if this file has been included (or imported) locally.
Definition: HeaderSearch.h:63
frontend::IncludeDirGroup Group
unsigned IgnoreSysRoot
IgnoreSysRoot - This is false if an absolute path should be treated relative to the sysroot,...
Contains a late templated function.
Definition: Sema.h:12837
CachedTokens Toks
Definition: Sema.h:12838
FPOptions FPO
Floating-point options in the point of definition.
Definition: Sema.h:12842
Decl * D
The template function declaration to be late parsed.
Definition: Sema.h:12840
Data for list of allocators.
a linked list of methods with the same selector name but different signatures.
ObjCMethodList * getNext() const
A struct with extended info about a syntactic name qualifier, to be used for the case of out-of-line ...
Definition: Decl.h:743
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition: Decl.h:757
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:744
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition: Decl.h:750
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:517
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:507
TypeSourceInfo * getAsTypeSourceInfo() const
Definition: TemplateBase.h:501
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:513
Describes the categories of an Objective-C class.
Definition: ASTBitCodes.h:1984
Source range/offset of a preprocessed entity.
Definition: ASTBitCodes.h:169