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 "clang/Serialization/ASTWriter.h"
14 #include "ASTCommon.h"
15 #include "ASTReaderInternals.h"
16 #include "MultiOnDiskHashTable.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTUnresolvedSet.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"
23 #include "clang/AST/DeclContextInternals.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/DeclarationName.h"
28 #include "clang/AST/Expr.h"
29 #include "clang/AST/ExprCXX.h"
30 #include "clang/AST/LambdaCapture.h"
31 #include "clang/AST/NestedNameSpecifier.h"
32 #include "clang/AST/RawCommentList.h"
33 #include "clang/AST/TemplateName.h"
34 #include "clang/AST/Type.h"
35 #include "clang/AST/TypeLocVisitor.h"
36 #include "clang/Basic/Diagnostic.h"
37 #include "clang/Basic/DiagnosticOptions.h"
38 #include "clang/Basic/FileManager.h"
39 #include "clang/Basic/FileSystemOptions.h"
40 #include "clang/Basic/IdentifierTable.h"
41 #include "clang/Basic/LLVM.h"
42 #include "clang/Basic/Lambda.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/Module.h"
45 #include "clang/Basic/ObjCRuntime.h"
46 #include "clang/Basic/OpenCLOptions.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/SourceManagerInternals.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/TargetInfo.h"
52 #include "clang/Basic/TargetOptions.h"
53 #include "clang/Basic/Version.h"
54 #include "clang/Lex/HeaderSearch.h"
55 #include "clang/Lex/HeaderSearchOptions.h"
56 #include "clang/Lex/MacroInfo.h"
57 #include "clang/Lex/ModuleMap.h"
58 #include "clang/Lex/PreprocessingRecord.h"
59 #include "clang/Lex/Preprocessor.h"
60 #include "clang/Lex/PreprocessorOptions.h"
61 #include "clang/Lex/Token.h"
62 #include "clang/Sema/IdentifierResolver.h"
63 #include "clang/Sema/ObjCMethodList.h"
64 #include "clang/Sema/Sema.h"
65 #include "clang/Sema/Weak.h"
66 #include "clang/Serialization/ASTReader.h"
67 #include "clang/Serialization/InMemoryModuleCache.h"
68 #include "clang/Serialization/Module.h"
69 #include "clang/Serialization/ModuleFileExtension.h"
70 #include "clang/Serialization/SerializationDiagnostic.h"
71 #include "llvm/ADT/APFloat.h"
72 #include "llvm/ADT/APInt.h"
73 #include "llvm/ADT/APSInt.h"
74 #include "llvm/ADT/ArrayRef.h"
75 #include "llvm/ADT/DenseMap.h"
76 #include "llvm/ADT/Hashing.h"
77 #include "llvm/ADT/Optional.h"
78 #include "llvm/ADT/PointerIntPair.h"
79 #include "llvm/ADT/STLExtras.h"
80 #include "llvm/ADT/ScopeExit.h"
81 #include "llvm/ADT/SmallSet.h"
82 #include "llvm/ADT/SmallString.h"
83 #include "llvm/ADT/SmallVector.h"
84 #include "llvm/ADT/StringMap.h"
85 #include "llvm/ADT/StringRef.h"
86 #include "llvm/Bitstream/BitCodes.h"
87 #include "llvm/Bitstream/BitstreamWriter.h"
88 #include "llvm/Support/Casting.h"
89 #include "llvm/Support/Compression.h"
90 #include "llvm/Support/DJB.h"
91 #include "llvm/Support/Endian.h"
92 #include "llvm/Support/EndianStream.h"
93 #include "llvm/Support/Error.h"
94 #include "llvm/Support/ErrorHandling.h"
95 #include "llvm/Support/MemoryBuffer.h"
96 #include "llvm/Support/OnDiskHashTable.h"
97 #include "llvm/Support/Path.h"
98 #include "llvm/Support/SHA1.h"
99 #include "llvm/Support/VersionTuple.h"
100 #include "llvm/Support/raw_ostream.h"
101 #include <algorithm>
102 #include <cassert>
103 #include <cstdint>
104 #include <cstdlib>
105 #include <cstring>
106 #include <ctime>
107 #include <deque>
108 #include <limits>
109 #include <memory>
110 #include <queue>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
114 
115 using namespace clang;
116 using namespace clang::serialization;
117 
118 template <typename T, typename Allocator>
119 static StringRef bytes(const std::vector<T, Allocator> &v) {
120   if (v.empty()) return StringRef();
121   return StringRef(reinterpret_cast<const char*>(&v[0]),
122                          sizeof(T) * v.size());
123 }
124 
125 template <typename T>
126 static StringRef bytes(const SmallVectorImpl<T> &v) {
127   return StringRef(reinterpret_cast<const char*>(v.data()),
128                          sizeof(T) * v.size());
129 }
130 
131 //===----------------------------------------------------------------------===//
132 // Type serialization
133 //===----------------------------------------------------------------------===//
134 
135 namespace clang {
136 
137   class ASTTypeWriter {
138     ASTWriter &Writer;
139     ASTRecordWriter Record;
140 
141     /// Type code that corresponds to the record generated.
142     TypeCode Code = static_cast<TypeCode>(0);
143 
144     /// Abbreviation to use for the record, if any.
145     unsigned AbbrevToUse = 0;
146 
147   public:
148     ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
149       : Writer(Writer), Record(Writer, Record) {}
150 
151     uint64_t Emit() {
152       return Record.Emit(Code, AbbrevToUse);
153     }
154 
155     void Visit(QualType T) {
156       if (T.hasLocalNonFastQualifiers()) {
157         Qualifiers Qs = T.getLocalQualifiers();
158         Record.AddTypeRef(T.getLocalUnqualifiedType());
159         Record.push_back(Qs.getAsOpaqueValue());
160         Code = TYPE_EXT_QUAL;
161         AbbrevToUse = Writer.TypeExtQualAbbrev;
162       } else {
163         switch (T->getTypeClass()) {
164           // For all of the concrete, non-dependent types, call the
165           // appropriate visitor function.
166 #define TYPE(Class, Base) \
167         case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
168 #define ABSTRACT_TYPE(Class, Base)
169 #include "clang/AST/TypeNodes.def"
170         }
171       }
172     }
173 
174     void VisitArrayType(const ArrayType *T);
175     void VisitFunctionType(const FunctionType *T);
176     void VisitTagType(const TagType *T);
177 
178 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
179 #define ABSTRACT_TYPE(Class, Base)
180 #include "clang/AST/TypeNodes.def"
181   };
182 
183 } // namespace clang
184 
185 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
186   llvm_unreachable("Built-in types are never serialized");
187 }
188 
189 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
190   Record.AddTypeRef(T->getElementType());
191   Code = TYPE_COMPLEX;
192 }
193 
194 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
195   Record.AddTypeRef(T->getPointeeType());
196   Code = TYPE_POINTER;
197 }
198 
199 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
200   Record.AddTypeRef(T->getOriginalType());
201   Code = TYPE_DECAYED;
202 }
203 
204 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
205   Record.AddTypeRef(T->getOriginalType());
206   Record.AddTypeRef(T->getAdjustedType());
207   Code = TYPE_ADJUSTED;
208 }
209 
210 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
211   Record.AddTypeRef(T->getPointeeType());
212   Code = TYPE_BLOCK_POINTER;
213 }
214 
215 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
216   Record.AddTypeRef(T->getPointeeTypeAsWritten());
217   Record.push_back(T->isSpelledAsLValue());
218   Code = TYPE_LVALUE_REFERENCE;
219 }
220 
221 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
222   Record.AddTypeRef(T->getPointeeTypeAsWritten());
223   Code = TYPE_RVALUE_REFERENCE;
224 }
225 
226 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
227   Record.AddTypeRef(T->getPointeeType());
228   Record.AddTypeRef(QualType(T->getClass(), 0));
229   Code = TYPE_MEMBER_POINTER;
230 }
231 
232 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
233   Record.AddTypeRef(T->getElementType());
234   Record.push_back(T->getSizeModifier()); // FIXME: stable values
235   Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
236 }
237 
238 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
239   VisitArrayType(T);
240   Record.AddAPInt(T->getSize());
241   Code = TYPE_CONSTANT_ARRAY;
242 }
243 
244 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
245   VisitArrayType(T);
246   Code = TYPE_INCOMPLETE_ARRAY;
247 }
248 
249 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
250   VisitArrayType(T);
251   Record.AddSourceLocation(T->getLBracketLoc());
252   Record.AddSourceLocation(T->getRBracketLoc());
253   Record.AddStmt(T->getSizeExpr());
254   Code = TYPE_VARIABLE_ARRAY;
255 }
256 
257 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
258   Record.AddTypeRef(T->getElementType());
259   Record.push_back(T->getNumElements());
260   Record.push_back(T->getVectorKind());
261   Code = TYPE_VECTOR;
262 }
263 
264 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
265   VisitVectorType(T);
266   Code = TYPE_EXT_VECTOR;
267 }
268 
269 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
270   Record.AddTypeRef(T->getReturnType());
271   FunctionType::ExtInfo C = T->getExtInfo();
272   Record.push_back(C.getNoReturn());
273   Record.push_back(C.getHasRegParm());
274   Record.push_back(C.getRegParm());
275   // FIXME: need to stabilize encoding of calling convention...
276   Record.push_back(C.getCC());
277   Record.push_back(C.getProducesResult());
278   Record.push_back(C.getNoCallerSavedRegs());
279   Record.push_back(C.getNoCfCheck());
280 
281   if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
282     AbbrevToUse = 0;
283 }
284 
285 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
286   VisitFunctionType(T);
287   Code = TYPE_FUNCTION_NO_PROTO;
288 }
289 
290 static void addExceptionSpec(const FunctionProtoType *T,
291                              ASTRecordWriter &Record) {
292   Record.push_back(T->getExceptionSpecType());
293   if (T->getExceptionSpecType() == EST_Dynamic) {
294     Record.push_back(T->getNumExceptions());
295     for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
296       Record.AddTypeRef(T->getExceptionType(I));
297   } else if (isComputedNoexcept(T->getExceptionSpecType())) {
298     Record.AddStmt(T->getNoexceptExpr());
299   } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
300     Record.AddDeclRef(T->getExceptionSpecDecl());
301     Record.AddDeclRef(T->getExceptionSpecTemplate());
302   } else if (T->getExceptionSpecType() == EST_Unevaluated) {
303     Record.AddDeclRef(T->getExceptionSpecDecl());
304   }
305 }
306 
307 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
308   VisitFunctionType(T);
309 
310   Record.push_back(T->isVariadic());
311   Record.push_back(T->hasTrailingReturn());
312   Record.push_back(T->getMethodQuals().getAsOpaqueValue());
313   Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
314   addExceptionSpec(T, Record);
315 
316   Record.push_back(T->getNumParams());
317   for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
318     Record.AddTypeRef(T->getParamType(I));
319 
320   if (T->hasExtParameterInfos()) {
321     for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
322       Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
323   }
324 
325   if (T->isVariadic() || T->hasTrailingReturn() || T->getMethodQuals() ||
326       T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
327       T->hasExtParameterInfos())
328     AbbrevToUse = 0;
329 
330   Code = TYPE_FUNCTION_PROTO;
331 }
332 
333 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
334   Record.AddDeclRef(T->getDecl());
335   Code = TYPE_UNRESOLVED_USING;
336 }
337 
338 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
339   Record.AddDeclRef(T->getDecl());
340   assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
341   Record.AddTypeRef(T->getCanonicalTypeInternal());
342   Code = TYPE_TYPEDEF;
343 }
344 
345 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
346   Record.AddStmt(T->getUnderlyingExpr());
347   Code = TYPE_TYPEOF_EXPR;
348 }
349 
350 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
351   Record.AddTypeRef(T->getUnderlyingType());
352   Code = TYPE_TYPEOF;
353 }
354 
355 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
356   Record.AddTypeRef(T->getUnderlyingType());
357   Record.AddStmt(T->getUnderlyingExpr());
358   Code = TYPE_DECLTYPE;
359 }
360 
361 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
362   Record.AddTypeRef(T->getBaseType());
363   Record.AddTypeRef(T->getUnderlyingType());
364   Record.push_back(T->getUTTKind());
365   Code = TYPE_UNARY_TRANSFORM;
366 }
367 
368 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
369   Record.AddTypeRef(T->getDeducedType());
370   Record.push_back((unsigned)T->getKeyword());
371   if (T->getDeducedType().isNull())
372     Record.push_back(T->containsUnexpandedParameterPack() ? 2 :
373                      T->isDependentType() ? 1 : 0);
374   Code = TYPE_AUTO;
375 }
376 
377 void ASTTypeWriter::VisitDeducedTemplateSpecializationType(
378     const DeducedTemplateSpecializationType *T) {
379   Record.AddTemplateName(T->getTemplateName());
380   Record.AddTypeRef(T->getDeducedType());
381   if (T->getDeducedType().isNull())
382     Record.push_back(T->isDependentType());
383   Code = TYPE_DEDUCED_TEMPLATE_SPECIALIZATION;
384 }
385 
386 void ASTTypeWriter::VisitTagType(const TagType *T) {
387   Record.push_back(T->isDependentType());
388   Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
389   assert(!T->isBeingDefined() &&
390          "Cannot serialize in the middle of a type definition");
391 }
392 
393 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
394   VisitTagType(T);
395   Code = TYPE_RECORD;
396 }
397 
398 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
399   VisitTagType(T);
400   Code = TYPE_ENUM;
401 }
402 
403 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
404   Record.AddTypeRef(T->getModifiedType());
405   Record.AddTypeRef(T->getEquivalentType());
406   Record.push_back(T->getAttrKind());
407   Code = TYPE_ATTRIBUTED;
408 }
409 
410 void
411 ASTTypeWriter::VisitSubstTemplateTypeParmType(
412                                         const SubstTemplateTypeParmType *T) {
413   Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
414   Record.AddTypeRef(T->getReplacementType());
415   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
416 }
417 
418 void
419 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
420                                       const SubstTemplateTypeParmPackType *T) {
421   Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
422   Record.AddTemplateArgument(T->getArgumentPack());
423   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
424 }
425 
426 void
427 ASTTypeWriter::VisitTemplateSpecializationType(
428                                        const TemplateSpecializationType *T) {
429   Record.push_back(T->isDependentType());
430   Record.AddTemplateName(T->getTemplateName());
431   Record.push_back(T->getNumArgs());
432   for (const auto &ArgI : *T)
433     Record.AddTemplateArgument(ArgI);
434   Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
435                                      : T->isCanonicalUnqualified()
436                                            ? QualType()
437                                            : T->getCanonicalTypeInternal());
438   Code = TYPE_TEMPLATE_SPECIALIZATION;
439 }
440 
441 void
442 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
443   VisitArrayType(T);
444   Record.AddStmt(T->getSizeExpr());
445   Record.AddSourceRange(T->getBracketsRange());
446   Code = TYPE_DEPENDENT_SIZED_ARRAY;
447 }
448 
449 void
450 ASTTypeWriter::VisitDependentSizedExtVectorType(
451                                         const DependentSizedExtVectorType *T) {
452   Record.AddTypeRef(T->getElementType());
453   Record.AddStmt(T->getSizeExpr());
454   Record.AddSourceLocation(T->getAttributeLoc());
455   Code = TYPE_DEPENDENT_SIZED_EXT_VECTOR;
456 }
457 
458 void ASTTypeWriter::VisitDependentVectorType(const DependentVectorType *T) {
459   Record.AddTypeRef(T->getElementType());
460   Record.AddStmt(const_cast<Expr*>(T->getSizeExpr()));
461   Record.AddSourceLocation(T->getAttributeLoc());
462   Record.push_back(T->getVectorKind());
463   Code = TYPE_DEPENDENT_SIZED_VECTOR;
464 }
465 
466 void
467 ASTTypeWriter::VisitDependentAddressSpaceType(
468     const DependentAddressSpaceType *T) {
469   Record.AddTypeRef(T->getPointeeType());
470   Record.AddStmt(T->getAddrSpaceExpr());
471   Record.AddSourceLocation(T->getAttributeLoc());
472   Code = TYPE_DEPENDENT_ADDRESS_SPACE;
473 }
474 
475 void
476 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
477   Record.push_back(T->getDepth());
478   Record.push_back(T->getIndex());
479   Record.push_back(T->isParameterPack());
480   Record.AddDeclRef(T->getDecl());
481   Code = TYPE_TEMPLATE_TYPE_PARM;
482 }
483 
484 void
485 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
486   Record.push_back(T->getKeyword());
487   Record.AddNestedNameSpecifier(T->getQualifier());
488   Record.AddIdentifierRef(T->getIdentifier());
489   Record.AddTypeRef(
490       T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
491   Code = TYPE_DEPENDENT_NAME;
492 }
493 
494 void
495 ASTTypeWriter::VisitDependentTemplateSpecializationType(
496                                 const DependentTemplateSpecializationType *T) {
497   Record.push_back(T->getKeyword());
498   Record.AddNestedNameSpecifier(T->getQualifier());
499   Record.AddIdentifierRef(T->getIdentifier());
500   Record.push_back(T->getNumArgs());
501   for (const auto &I : *T)
502     Record.AddTemplateArgument(I);
503   Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
504 }
505 
506 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
507   Record.AddTypeRef(T->getPattern());
508   if (Optional<unsigned> NumExpansions = T->getNumExpansions())
509     Record.push_back(*NumExpansions + 1);
510   else
511     Record.push_back(0);
512   Code = TYPE_PACK_EXPANSION;
513 }
514 
515 void ASTTypeWriter::VisitParenType(const ParenType *T) {
516   Record.AddTypeRef(T->getInnerType());
517   Code = TYPE_PAREN;
518 }
519 
520 void ASTTypeWriter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
521   Record.AddTypeRef(T->getUnderlyingType());
522   Record.AddIdentifierRef(T->getMacroIdentifier());
523   Code = TYPE_MACRO_QUALIFIED;
524 }
525 
526 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
527   Record.push_back(T->getKeyword());
528   Record.AddNestedNameSpecifier(T->getQualifier());
529   Record.AddTypeRef(T->getNamedType());
530   Record.AddDeclRef(T->getOwnedTagDecl());
531   Code = TYPE_ELABORATED;
532 }
533 
534 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
535   Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
536   Record.AddTypeRef(T->getInjectedSpecializationType());
537   Code = TYPE_INJECTED_CLASS_NAME;
538 }
539 
540 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
541   Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
542   Code = TYPE_OBJC_INTERFACE;
543 }
544 
545 void ASTTypeWriter::VisitObjCTypeParamType(const ObjCTypeParamType *T) {
546   Record.AddDeclRef(T->getDecl());
547   Record.push_back(T->getNumProtocols());
548   for (const auto *I : T->quals())
549     Record.AddDeclRef(I);
550   Code = TYPE_OBJC_TYPE_PARAM;
551 }
552 
553 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
554   Record.AddTypeRef(T->getBaseType());
555   Record.push_back(T->getTypeArgsAsWritten().size());
556   for (auto TypeArg : T->getTypeArgsAsWritten())
557     Record.AddTypeRef(TypeArg);
558   Record.push_back(T->getNumProtocols());
559   for (const auto *I : T->quals())
560     Record.AddDeclRef(I);
561   Record.push_back(T->isKindOfTypeAsWritten());
562   Code = TYPE_OBJC_OBJECT;
563 }
564 
565 void
566 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
567   Record.AddTypeRef(T->getPointeeType());
568   Code = TYPE_OBJC_OBJECT_POINTER;
569 }
570 
571 void
572 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
573   Record.AddTypeRef(T->getValueType());
574   Code = TYPE_ATOMIC;
575 }
576 
577 void
578 ASTTypeWriter::VisitPipeType(const PipeType *T) {
579   Record.AddTypeRef(T->getElementType());
580   Record.push_back(T->isReadOnly());
581   Code = TYPE_PIPE;
582 }
583 
584 namespace {
585 
586 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
587   ASTRecordWriter &Record;
588 
589 public:
590   TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
591 
592 #define ABSTRACT_TYPELOC(CLASS, PARENT)
593 #define TYPELOC(CLASS, PARENT) \
594     void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
595 #include "clang/AST/TypeLocNodes.def"
596 
597   void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
598   void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
599 };
600 
601 } // namespace
602 
603 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
604   // nothing to do
605 }
606 
607 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
608   Record.AddSourceLocation(TL.getBuiltinLoc());
609   if (TL.needsExtraLocalData()) {
610     Record.push_back(TL.getWrittenTypeSpec());
611     Record.push_back(TL.getWrittenSignSpec());
612     Record.push_back(TL.getWrittenWidthSpec());
613     Record.push_back(TL.hasModeAttr());
614   }
615 }
616 
617 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
618   Record.AddSourceLocation(TL.getNameLoc());
619 }
620 
621 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
622   Record.AddSourceLocation(TL.getStarLoc());
623 }
624 
625 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
626   // nothing to do
627 }
628 
629 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
630   // nothing to do
631 }
632 
633 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
634   Record.AddSourceLocation(TL.getCaretLoc());
635 }
636 
637 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
638   Record.AddSourceLocation(TL.getAmpLoc());
639 }
640 
641 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
642   Record.AddSourceLocation(TL.getAmpAmpLoc());
643 }
644 
645 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
646   Record.AddSourceLocation(TL.getStarLoc());
647   Record.AddTypeSourceInfo(TL.getClassTInfo());
648 }
649 
650 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
651   Record.AddSourceLocation(TL.getLBracketLoc());
652   Record.AddSourceLocation(TL.getRBracketLoc());
653   Record.push_back(TL.getSizeExpr() ? 1 : 0);
654   if (TL.getSizeExpr())
655     Record.AddStmt(TL.getSizeExpr());
656 }
657 
658 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
659   VisitArrayTypeLoc(TL);
660 }
661 
662 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
663   VisitArrayTypeLoc(TL);
664 }
665 
666 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
667   VisitArrayTypeLoc(TL);
668 }
669 
670 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
671                                             DependentSizedArrayTypeLoc TL) {
672   VisitArrayTypeLoc(TL);
673 }
674 
675 void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
676     DependentAddressSpaceTypeLoc TL) {
677   Record.AddSourceLocation(TL.getAttrNameLoc());
678   SourceRange range = TL.getAttrOperandParensRange();
679   Record.AddSourceLocation(range.getBegin());
680   Record.AddSourceLocation(range.getEnd());
681   Record.AddStmt(TL.getAttrExprOperand());
682 }
683 
684 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
685                                         DependentSizedExtVectorTypeLoc TL) {
686   Record.AddSourceLocation(TL.getNameLoc());
687 }
688 
689 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
690   Record.AddSourceLocation(TL.getNameLoc());
691 }
692 
693 void TypeLocWriter::VisitDependentVectorTypeLoc(
694     DependentVectorTypeLoc TL) {
695   Record.AddSourceLocation(TL.getNameLoc());
696 }
697 
698 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
699   Record.AddSourceLocation(TL.getNameLoc());
700 }
701 
702 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
703   Record.AddSourceLocation(TL.getLocalRangeBegin());
704   Record.AddSourceLocation(TL.getLParenLoc());
705   Record.AddSourceLocation(TL.getRParenLoc());
706   Record.AddSourceRange(TL.getExceptionSpecRange());
707   Record.AddSourceLocation(TL.getLocalRangeEnd());
708   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
709     Record.AddDeclRef(TL.getParam(i));
710 }
711 
712 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
713   VisitFunctionTypeLoc(TL);
714 }
715 
716 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
717   VisitFunctionTypeLoc(TL);
718 }
719 
720 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
721   Record.AddSourceLocation(TL.getNameLoc());
722 }
723 
724 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
725   Record.AddSourceLocation(TL.getNameLoc());
726 }
727 
728 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
729   if (TL.getNumProtocols()) {
730     Record.AddSourceLocation(TL.getProtocolLAngleLoc());
731     Record.AddSourceLocation(TL.getProtocolRAngleLoc());
732   }
733   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
734     Record.AddSourceLocation(TL.getProtocolLoc(i));
735 }
736 
737 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
738   Record.AddSourceLocation(TL.getTypeofLoc());
739   Record.AddSourceLocation(TL.getLParenLoc());
740   Record.AddSourceLocation(TL.getRParenLoc());
741 }
742 
743 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
744   Record.AddSourceLocation(TL.getTypeofLoc());
745   Record.AddSourceLocation(TL.getLParenLoc());
746   Record.AddSourceLocation(TL.getRParenLoc());
747   Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
748 }
749 
750 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
751   Record.AddSourceLocation(TL.getNameLoc());
752 }
753 
754 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
755   Record.AddSourceLocation(TL.getKWLoc());
756   Record.AddSourceLocation(TL.getLParenLoc());
757   Record.AddSourceLocation(TL.getRParenLoc());
758   Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
759 }
760 
761 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
762   Record.AddSourceLocation(TL.getNameLoc());
763 }
764 
765 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
766     DeducedTemplateSpecializationTypeLoc TL) {
767   Record.AddSourceLocation(TL.getTemplateNameLoc());
768 }
769 
770 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
771   Record.AddSourceLocation(TL.getNameLoc());
772 }
773 
774 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
775   Record.AddSourceLocation(TL.getNameLoc());
776 }
777 
778 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
779   Record.AddAttr(TL.getAttr());
780 }
781 
782 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
783   Record.AddSourceLocation(TL.getNameLoc());
784 }
785 
786 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
787                                             SubstTemplateTypeParmTypeLoc TL) {
788   Record.AddSourceLocation(TL.getNameLoc());
789 }
790 
791 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
792                                           SubstTemplateTypeParmPackTypeLoc TL) {
793   Record.AddSourceLocation(TL.getNameLoc());
794 }
795 
796 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
797                                            TemplateSpecializationTypeLoc TL) {
798   Record.AddSourceLocation(TL.getTemplateKeywordLoc());
799   Record.AddSourceLocation(TL.getTemplateNameLoc());
800   Record.AddSourceLocation(TL.getLAngleLoc());
801   Record.AddSourceLocation(TL.getRAngleLoc());
802   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
803     Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
804                                       TL.getArgLoc(i).getLocInfo());
805 }
806 
807 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
808   Record.AddSourceLocation(TL.getLParenLoc());
809   Record.AddSourceLocation(TL.getRParenLoc());
810 }
811 
812 void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
813   Record.AddSourceLocation(TL.getExpansionLoc());
814 }
815 
816 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
817   Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
818   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
819 }
820 
821 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
822   Record.AddSourceLocation(TL.getNameLoc());
823 }
824 
825 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
826   Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
827   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
828   Record.AddSourceLocation(TL.getNameLoc());
829 }
830 
831 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
832        DependentTemplateSpecializationTypeLoc TL) {
833   Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
834   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
835   Record.AddSourceLocation(TL.getTemplateKeywordLoc());
836   Record.AddSourceLocation(TL.getTemplateNameLoc());
837   Record.AddSourceLocation(TL.getLAngleLoc());
838   Record.AddSourceLocation(TL.getRAngleLoc());
839   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
840     Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
841                                       TL.getArgLoc(I).getLocInfo());
842 }
843 
844 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
845   Record.AddSourceLocation(TL.getEllipsisLoc());
846 }
847 
848 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
849   Record.AddSourceLocation(TL.getNameLoc());
850 }
851 
852 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
853   Record.push_back(TL.hasBaseTypeAsWritten());
854   Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
855   Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
856   for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
857     Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
858   Record.AddSourceLocation(TL.getProtocolLAngleLoc());
859   Record.AddSourceLocation(TL.getProtocolRAngleLoc());
860   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
861     Record.AddSourceLocation(TL.getProtocolLoc(i));
862 }
863 
864 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
865   Record.AddSourceLocation(TL.getStarLoc());
866 }
867 
868 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
869   Record.AddSourceLocation(TL.getKWLoc());
870   Record.AddSourceLocation(TL.getLParenLoc());
871   Record.AddSourceLocation(TL.getRParenLoc());
872 }
873 
874 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
875   Record.AddSourceLocation(TL.getKWLoc());
876 }
877 
878 void ASTWriter::WriteTypeAbbrevs() {
879   using namespace llvm;
880 
881   std::shared_ptr<BitCodeAbbrev> Abv;
882 
883   // Abbreviation for TYPE_EXT_QUAL
884   Abv = std::make_shared<BitCodeAbbrev>();
885   Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
886   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Type
887   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3));   // Quals
888   TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
889 
890   // Abbreviation for TYPE_FUNCTION_PROTO
891   Abv = std::make_shared<BitCodeAbbrev>();
892   Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
893   // FunctionType
894   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // ReturnType
895   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
896   Abv->Add(BitCodeAbbrevOp(0));                         // HasRegParm
897   Abv->Add(BitCodeAbbrevOp(0));                         // RegParm
898   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
899   Abv->Add(BitCodeAbbrevOp(0));                         // ProducesResult
900   Abv->Add(BitCodeAbbrevOp(0));                         // NoCallerSavedRegs
901   Abv->Add(BitCodeAbbrevOp(0));                         // NoCfCheck
902   // FunctionProtoType
903   Abv->Add(BitCodeAbbrevOp(0));                         // IsVariadic
904   Abv->Add(BitCodeAbbrevOp(0));                         // HasTrailingReturn
905   Abv->Add(BitCodeAbbrevOp(0));                         // TypeQuals
906   Abv->Add(BitCodeAbbrevOp(0));                         // RefQualifier
907   Abv->Add(BitCodeAbbrevOp(EST_None));                  // ExceptionSpec
908   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // NumParams
909   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
910   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Params
911   TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
912 }
913 
914 //===----------------------------------------------------------------------===//
915 // ASTWriter Implementation
916 //===----------------------------------------------------------------------===//
917 
918 static void EmitBlockID(unsigned ID, const char *Name,
919                         llvm::BitstreamWriter &Stream,
920                         ASTWriter::RecordDataImpl &Record) {
921   Record.clear();
922   Record.push_back(ID);
923   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
924 
925   // Emit the block name if present.
926   if (!Name || Name[0] == 0)
927     return;
928   Record.clear();
929   while (*Name)
930     Record.push_back(*Name++);
931   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
932 }
933 
934 static void EmitRecordID(unsigned ID, const char *Name,
935                          llvm::BitstreamWriter &Stream,
936                          ASTWriter::RecordDataImpl &Record) {
937   Record.clear();
938   Record.push_back(ID);
939   while (*Name)
940     Record.push_back(*Name++);
941   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
942 }
943 
944 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
945                           ASTWriter::RecordDataImpl &Record) {
946 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
947   RECORD(STMT_STOP);
948   RECORD(STMT_NULL_PTR);
949   RECORD(STMT_REF_PTR);
950   RECORD(STMT_NULL);
951   RECORD(STMT_COMPOUND);
952   RECORD(STMT_CASE);
953   RECORD(STMT_DEFAULT);
954   RECORD(STMT_LABEL);
955   RECORD(STMT_ATTRIBUTED);
956   RECORD(STMT_IF);
957   RECORD(STMT_SWITCH);
958   RECORD(STMT_WHILE);
959   RECORD(STMT_DO);
960   RECORD(STMT_FOR);
961   RECORD(STMT_GOTO);
962   RECORD(STMT_INDIRECT_GOTO);
963   RECORD(STMT_CONTINUE);
964   RECORD(STMT_BREAK);
965   RECORD(STMT_RETURN);
966   RECORD(STMT_DECL);
967   RECORD(STMT_GCCASM);
968   RECORD(STMT_MSASM);
969   RECORD(EXPR_PREDEFINED);
970   RECORD(EXPR_DECL_REF);
971   RECORD(EXPR_INTEGER_LITERAL);
972   RECORD(EXPR_FLOATING_LITERAL);
973   RECORD(EXPR_IMAGINARY_LITERAL);
974   RECORD(EXPR_STRING_LITERAL);
975   RECORD(EXPR_CHARACTER_LITERAL);
976   RECORD(EXPR_PAREN);
977   RECORD(EXPR_PAREN_LIST);
978   RECORD(EXPR_UNARY_OPERATOR);
979   RECORD(EXPR_SIZEOF_ALIGN_OF);
980   RECORD(EXPR_ARRAY_SUBSCRIPT);
981   RECORD(EXPR_CALL);
982   RECORD(EXPR_MEMBER);
983   RECORD(EXPR_BINARY_OPERATOR);
984   RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
985   RECORD(EXPR_CONDITIONAL_OPERATOR);
986   RECORD(EXPR_IMPLICIT_CAST);
987   RECORD(EXPR_CSTYLE_CAST);
988   RECORD(EXPR_COMPOUND_LITERAL);
989   RECORD(EXPR_EXT_VECTOR_ELEMENT);
990   RECORD(EXPR_INIT_LIST);
991   RECORD(EXPR_DESIGNATED_INIT);
992   RECORD(EXPR_DESIGNATED_INIT_UPDATE);
993   RECORD(EXPR_IMPLICIT_VALUE_INIT);
994   RECORD(EXPR_NO_INIT);
995   RECORD(EXPR_VA_ARG);
996   RECORD(EXPR_ADDR_LABEL);
997   RECORD(EXPR_STMT);
998   RECORD(EXPR_CHOOSE);
999   RECORD(EXPR_GNU_NULL);
1000   RECORD(EXPR_SHUFFLE_VECTOR);
1001   RECORD(EXPR_BLOCK);
1002   RECORD(EXPR_GENERIC_SELECTION);
1003   RECORD(EXPR_OBJC_STRING_LITERAL);
1004   RECORD(EXPR_OBJC_BOXED_EXPRESSION);
1005   RECORD(EXPR_OBJC_ARRAY_LITERAL);
1006   RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
1007   RECORD(EXPR_OBJC_ENCODE);
1008   RECORD(EXPR_OBJC_SELECTOR_EXPR);
1009   RECORD(EXPR_OBJC_PROTOCOL_EXPR);
1010   RECORD(EXPR_OBJC_IVAR_REF_EXPR);
1011   RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
1012   RECORD(EXPR_OBJC_KVC_REF_EXPR);
1013   RECORD(EXPR_OBJC_MESSAGE_EXPR);
1014   RECORD(STMT_OBJC_FOR_COLLECTION);
1015   RECORD(STMT_OBJC_CATCH);
1016   RECORD(STMT_OBJC_FINALLY);
1017   RECORD(STMT_OBJC_AT_TRY);
1018   RECORD(STMT_OBJC_AT_SYNCHRONIZED);
1019   RECORD(STMT_OBJC_AT_THROW);
1020   RECORD(EXPR_OBJC_BOOL_LITERAL);
1021   RECORD(STMT_CXX_CATCH);
1022   RECORD(STMT_CXX_TRY);
1023   RECORD(STMT_CXX_FOR_RANGE);
1024   RECORD(EXPR_CXX_OPERATOR_CALL);
1025   RECORD(EXPR_CXX_MEMBER_CALL);
1026   RECORD(EXPR_CXX_CONSTRUCT);
1027   RECORD(EXPR_CXX_TEMPORARY_OBJECT);
1028   RECORD(EXPR_CXX_STATIC_CAST);
1029   RECORD(EXPR_CXX_DYNAMIC_CAST);
1030   RECORD(EXPR_CXX_REINTERPRET_CAST);
1031   RECORD(EXPR_CXX_CONST_CAST);
1032   RECORD(EXPR_CXX_FUNCTIONAL_CAST);
1033   RECORD(EXPR_USER_DEFINED_LITERAL);
1034   RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
1035   RECORD(EXPR_CXX_BOOL_LITERAL);
1036   RECORD(EXPR_CXX_NULL_PTR_LITERAL);
1037   RECORD(EXPR_CXX_TYPEID_EXPR);
1038   RECORD(EXPR_CXX_TYPEID_TYPE);
1039   RECORD(EXPR_CXX_THIS);
1040   RECORD(EXPR_CXX_THROW);
1041   RECORD(EXPR_CXX_DEFAULT_ARG);
1042   RECORD(EXPR_CXX_DEFAULT_INIT);
1043   RECORD(EXPR_CXX_BIND_TEMPORARY);
1044   RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
1045   RECORD(EXPR_CXX_NEW);
1046   RECORD(EXPR_CXX_DELETE);
1047   RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
1048   RECORD(EXPR_EXPR_WITH_CLEANUPS);
1049   RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
1050   RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
1051   RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
1052   RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
1053   RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
1054   RECORD(EXPR_CXX_EXPRESSION_TRAIT);
1055   RECORD(EXPR_CXX_NOEXCEPT);
1056   RECORD(EXPR_OPAQUE_VALUE);
1057   RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
1058   RECORD(EXPR_TYPE_TRAIT);
1059   RECORD(EXPR_ARRAY_TYPE_TRAIT);
1060   RECORD(EXPR_PACK_EXPANSION);
1061   RECORD(EXPR_SIZEOF_PACK);
1062   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
1063   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
1064   RECORD(EXPR_FUNCTION_PARM_PACK);
1065   RECORD(EXPR_MATERIALIZE_TEMPORARY);
1066   RECORD(EXPR_CUDA_KERNEL_CALL);
1067   RECORD(EXPR_CXX_UUIDOF_EXPR);
1068   RECORD(EXPR_CXX_UUIDOF_TYPE);
1069   RECORD(EXPR_LAMBDA);
1070 #undef RECORD
1071 }
1072 
1073 void ASTWriter::WriteBlockInfoBlock() {
1074   RecordData Record;
1075   Stream.EnterBlockInfoBlock();
1076 
1077 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
1078 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
1079 
1080   // Control Block.
1081   BLOCK(CONTROL_BLOCK);
1082   RECORD(METADATA);
1083   RECORD(MODULE_NAME);
1084   RECORD(MODULE_DIRECTORY);
1085   RECORD(MODULE_MAP_FILE);
1086   RECORD(IMPORTS);
1087   RECORD(ORIGINAL_FILE);
1088   RECORD(ORIGINAL_PCH_DIR);
1089   RECORD(ORIGINAL_FILE_ID);
1090   RECORD(INPUT_FILE_OFFSETS);
1091 
1092   BLOCK(OPTIONS_BLOCK);
1093   RECORD(LANGUAGE_OPTIONS);
1094   RECORD(TARGET_OPTIONS);
1095   RECORD(FILE_SYSTEM_OPTIONS);
1096   RECORD(HEADER_SEARCH_OPTIONS);
1097   RECORD(PREPROCESSOR_OPTIONS);
1098 
1099   BLOCK(INPUT_FILES_BLOCK);
1100   RECORD(INPUT_FILE);
1101 
1102   // AST Top-Level Block.
1103   BLOCK(AST_BLOCK);
1104   RECORD(TYPE_OFFSET);
1105   RECORD(DECL_OFFSET);
1106   RECORD(IDENTIFIER_OFFSET);
1107   RECORD(IDENTIFIER_TABLE);
1108   RECORD(EAGERLY_DESERIALIZED_DECLS);
1109   RECORD(MODULAR_CODEGEN_DECLS);
1110   RECORD(SPECIAL_TYPES);
1111   RECORD(STATISTICS);
1112   RECORD(TENTATIVE_DEFINITIONS);
1113   RECORD(SELECTOR_OFFSETS);
1114   RECORD(METHOD_POOL);
1115   RECORD(PP_COUNTER_VALUE);
1116   RECORD(SOURCE_LOCATION_OFFSETS);
1117   RECORD(SOURCE_LOCATION_PRELOADS);
1118   RECORD(EXT_VECTOR_DECLS);
1119   RECORD(UNUSED_FILESCOPED_DECLS);
1120   RECORD(PPD_ENTITIES_OFFSETS);
1121   RECORD(VTABLE_USES);
1122   RECORD(PPD_SKIPPED_RANGES);
1123   RECORD(REFERENCED_SELECTOR_POOL);
1124   RECORD(TU_UPDATE_LEXICAL);
1125   RECORD(SEMA_DECL_REFS);
1126   RECORD(WEAK_UNDECLARED_IDENTIFIERS);
1127   RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
1128   RECORD(UPDATE_VISIBLE);
1129   RECORD(DECL_UPDATE_OFFSETS);
1130   RECORD(DECL_UPDATES);
1131   RECORD(CUDA_SPECIAL_DECL_REFS);
1132   RECORD(HEADER_SEARCH_TABLE);
1133   RECORD(FP_PRAGMA_OPTIONS);
1134   RECORD(OPENCL_EXTENSIONS);
1135   RECORD(OPENCL_EXTENSION_TYPES);
1136   RECORD(OPENCL_EXTENSION_DECLS);
1137   RECORD(DELEGATING_CTORS);
1138   RECORD(KNOWN_NAMESPACES);
1139   RECORD(MODULE_OFFSET_MAP);
1140   RECORD(SOURCE_MANAGER_LINE_TABLE);
1141   RECORD(OBJC_CATEGORIES_MAP);
1142   RECORD(FILE_SORTED_DECLS);
1143   RECORD(IMPORTED_MODULES);
1144   RECORD(OBJC_CATEGORIES);
1145   RECORD(MACRO_OFFSET);
1146   RECORD(INTERESTING_IDENTIFIERS);
1147   RECORD(UNDEFINED_BUT_USED);
1148   RECORD(LATE_PARSED_TEMPLATE);
1149   RECORD(OPTIMIZE_PRAGMA_OPTIONS);
1150   RECORD(MSSTRUCT_PRAGMA_OPTIONS);
1151   RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
1152   RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
1153   RECORD(DELETE_EXPRS_TO_ANALYZE);
1154   RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
1155   RECORD(PP_CONDITIONAL_STACK);
1156 
1157   // SourceManager Block.
1158   BLOCK(SOURCE_MANAGER_BLOCK);
1159   RECORD(SM_SLOC_FILE_ENTRY);
1160   RECORD(SM_SLOC_BUFFER_ENTRY);
1161   RECORD(SM_SLOC_BUFFER_BLOB);
1162   RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
1163   RECORD(SM_SLOC_EXPANSION_ENTRY);
1164 
1165   // Preprocessor Block.
1166   BLOCK(PREPROCESSOR_BLOCK);
1167   RECORD(PP_MACRO_DIRECTIVE_HISTORY);
1168   RECORD(PP_MACRO_FUNCTION_LIKE);
1169   RECORD(PP_MACRO_OBJECT_LIKE);
1170   RECORD(PP_MODULE_MACRO);
1171   RECORD(PP_TOKEN);
1172 
1173   // Submodule Block.
1174   BLOCK(SUBMODULE_BLOCK);
1175   RECORD(SUBMODULE_METADATA);
1176   RECORD(SUBMODULE_DEFINITION);
1177   RECORD(SUBMODULE_UMBRELLA_HEADER);
1178   RECORD(SUBMODULE_HEADER);
1179   RECORD(SUBMODULE_TOPHEADER);
1180   RECORD(SUBMODULE_UMBRELLA_DIR);
1181   RECORD(SUBMODULE_IMPORTS);
1182   RECORD(SUBMODULE_EXPORTS);
1183   RECORD(SUBMODULE_REQUIRES);
1184   RECORD(SUBMODULE_EXCLUDED_HEADER);
1185   RECORD(SUBMODULE_LINK_LIBRARY);
1186   RECORD(SUBMODULE_CONFIG_MACRO);
1187   RECORD(SUBMODULE_CONFLICT);
1188   RECORD(SUBMODULE_PRIVATE_HEADER);
1189   RECORD(SUBMODULE_TEXTUAL_HEADER);
1190   RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1191   RECORD(SUBMODULE_INITIALIZERS);
1192   RECORD(SUBMODULE_EXPORT_AS);
1193 
1194   // Comments Block.
1195   BLOCK(COMMENTS_BLOCK);
1196   RECORD(COMMENTS_RAW_COMMENT);
1197 
1198   // Decls and Types block.
1199   BLOCK(DECLTYPES_BLOCK);
1200   RECORD(TYPE_EXT_QUAL);
1201   RECORD(TYPE_COMPLEX);
1202   RECORD(TYPE_POINTER);
1203   RECORD(TYPE_BLOCK_POINTER);
1204   RECORD(TYPE_LVALUE_REFERENCE);
1205   RECORD(TYPE_RVALUE_REFERENCE);
1206   RECORD(TYPE_MEMBER_POINTER);
1207   RECORD(TYPE_CONSTANT_ARRAY);
1208   RECORD(TYPE_INCOMPLETE_ARRAY);
1209   RECORD(TYPE_VARIABLE_ARRAY);
1210   RECORD(TYPE_VECTOR);
1211   RECORD(TYPE_EXT_VECTOR);
1212   RECORD(TYPE_FUNCTION_NO_PROTO);
1213   RECORD(TYPE_FUNCTION_PROTO);
1214   RECORD(TYPE_TYPEDEF);
1215   RECORD(TYPE_TYPEOF_EXPR);
1216   RECORD(TYPE_TYPEOF);
1217   RECORD(TYPE_RECORD);
1218   RECORD(TYPE_ENUM);
1219   RECORD(TYPE_OBJC_INTERFACE);
1220   RECORD(TYPE_OBJC_OBJECT_POINTER);
1221   RECORD(TYPE_DECLTYPE);
1222   RECORD(TYPE_ELABORATED);
1223   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1224   RECORD(TYPE_UNRESOLVED_USING);
1225   RECORD(TYPE_INJECTED_CLASS_NAME);
1226   RECORD(TYPE_OBJC_OBJECT);
1227   RECORD(TYPE_TEMPLATE_TYPE_PARM);
1228   RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1229   RECORD(TYPE_DEPENDENT_NAME);
1230   RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1231   RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1232   RECORD(TYPE_PAREN);
1233   RECORD(TYPE_MACRO_QUALIFIED);
1234   RECORD(TYPE_PACK_EXPANSION);
1235   RECORD(TYPE_ATTRIBUTED);
1236   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
1237   RECORD(TYPE_AUTO);
1238   RECORD(TYPE_UNARY_TRANSFORM);
1239   RECORD(TYPE_ATOMIC);
1240   RECORD(TYPE_DECAYED);
1241   RECORD(TYPE_ADJUSTED);
1242   RECORD(TYPE_OBJC_TYPE_PARAM);
1243   RECORD(LOCAL_REDECLARATIONS);
1244   RECORD(DECL_TYPEDEF);
1245   RECORD(DECL_TYPEALIAS);
1246   RECORD(DECL_ENUM);
1247   RECORD(DECL_RECORD);
1248   RECORD(DECL_ENUM_CONSTANT);
1249   RECORD(DECL_FUNCTION);
1250   RECORD(DECL_OBJC_METHOD);
1251   RECORD(DECL_OBJC_INTERFACE);
1252   RECORD(DECL_OBJC_PROTOCOL);
1253   RECORD(DECL_OBJC_IVAR);
1254   RECORD(DECL_OBJC_AT_DEFS_FIELD);
1255   RECORD(DECL_OBJC_CATEGORY);
1256   RECORD(DECL_OBJC_CATEGORY_IMPL);
1257   RECORD(DECL_OBJC_IMPLEMENTATION);
1258   RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1259   RECORD(DECL_OBJC_PROPERTY);
1260   RECORD(DECL_OBJC_PROPERTY_IMPL);
1261   RECORD(DECL_FIELD);
1262   RECORD(DECL_MS_PROPERTY);
1263   RECORD(DECL_VAR);
1264   RECORD(DECL_IMPLICIT_PARAM);
1265   RECORD(DECL_PARM_VAR);
1266   RECORD(DECL_FILE_SCOPE_ASM);
1267   RECORD(DECL_BLOCK);
1268   RECORD(DECL_CONTEXT_LEXICAL);
1269   RECORD(DECL_CONTEXT_VISIBLE);
1270   RECORD(DECL_NAMESPACE);
1271   RECORD(DECL_NAMESPACE_ALIAS);
1272   RECORD(DECL_USING);
1273   RECORD(DECL_USING_SHADOW);
1274   RECORD(DECL_USING_DIRECTIVE);
1275   RECORD(DECL_UNRESOLVED_USING_VALUE);
1276   RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1277   RECORD(DECL_LINKAGE_SPEC);
1278   RECORD(DECL_CXX_RECORD);
1279   RECORD(DECL_CXX_METHOD);
1280   RECORD(DECL_CXX_CONSTRUCTOR);
1281   RECORD(DECL_CXX_DESTRUCTOR);
1282   RECORD(DECL_CXX_CONVERSION);
1283   RECORD(DECL_ACCESS_SPEC);
1284   RECORD(DECL_FRIEND);
1285   RECORD(DECL_FRIEND_TEMPLATE);
1286   RECORD(DECL_CLASS_TEMPLATE);
1287   RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1288   RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1289   RECORD(DECL_VAR_TEMPLATE);
1290   RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1291   RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1292   RECORD(DECL_FUNCTION_TEMPLATE);
1293   RECORD(DECL_TEMPLATE_TYPE_PARM);
1294   RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1295   RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1296   RECORD(DECL_CONCEPT);
1297   RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1298   RECORD(DECL_STATIC_ASSERT);
1299   RECORD(DECL_CXX_BASE_SPECIFIERS);
1300   RECORD(DECL_CXX_CTOR_INITIALIZERS);
1301   RECORD(DECL_INDIRECTFIELD);
1302   RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1303   RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1304   RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1305   RECORD(DECL_IMPORT);
1306   RECORD(DECL_OMP_THREADPRIVATE);
1307   RECORD(DECL_EMPTY);
1308   RECORD(DECL_OBJC_TYPE_PARAM);
1309   RECORD(DECL_OMP_CAPTUREDEXPR);
1310   RECORD(DECL_PRAGMA_COMMENT);
1311   RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1312   RECORD(DECL_OMP_DECLARE_REDUCTION);
1313   RECORD(DECL_OMP_ALLOCATE);
1314 
1315   // Statements and Exprs can occur in the Decls and Types block.
1316   AddStmtsExprs(Stream, Record);
1317 
1318   BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1319   RECORD(PPD_MACRO_EXPANSION);
1320   RECORD(PPD_MACRO_DEFINITION);
1321   RECORD(PPD_INCLUSION_DIRECTIVE);
1322 
1323   // Decls and Types block.
1324   BLOCK(EXTENSION_BLOCK);
1325   RECORD(EXTENSION_METADATA);
1326 
1327   BLOCK(UNHASHED_CONTROL_BLOCK);
1328   RECORD(SIGNATURE);
1329   RECORD(DIAGNOSTIC_OPTIONS);
1330   RECORD(DIAG_PRAGMA_MAPPINGS);
1331 
1332 #undef RECORD
1333 #undef BLOCK
1334   Stream.ExitBlock();
1335 }
1336 
1337 /// Prepares a path for being written to an AST file by converting it
1338 /// to an absolute path and removing nested './'s.
1339 ///
1340 /// \return \c true if the path was changed.
1341 static bool cleanPathForOutput(FileManager &FileMgr,
1342                                SmallVectorImpl<char> &Path) {
1343   bool Changed = FileMgr.makeAbsolutePath(Path);
1344   return Changed | llvm::sys::path::remove_dots(Path);
1345 }
1346 
1347 /// Adjusts the given filename to only write out the portion of the
1348 /// filename that is not part of the system root directory.
1349 ///
1350 /// \param Filename the file name to adjust.
1351 ///
1352 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1353 /// the returned filename will be adjusted by this root directory.
1354 ///
1355 /// \returns either the original filename (if it needs no adjustment) or the
1356 /// adjusted filename (which points into the @p Filename parameter).
1357 static const char *
1358 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1359   assert(Filename && "No file name to adjust?");
1360 
1361   if (BaseDir.empty())
1362     return Filename;
1363 
1364   // Verify that the filename and the system root have the same prefix.
1365   unsigned Pos = 0;
1366   for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1367     if (Filename[Pos] != BaseDir[Pos])
1368       return Filename; // Prefixes don't match.
1369 
1370   // We hit the end of the filename before we hit the end of the system root.
1371   if (!Filename[Pos])
1372     return Filename;
1373 
1374   // If there's not a path separator at the end of the base directory nor
1375   // immediately after it, then this isn't within the base directory.
1376   if (!llvm::sys::path::is_separator(Filename[Pos])) {
1377     if (!llvm::sys::path::is_separator(BaseDir.back()))
1378       return Filename;
1379   } else {
1380     // If the file name has a '/' at the current position, skip over the '/'.
1381     // We distinguish relative paths from absolute paths by the
1382     // absence of '/' at the beginning of relative paths.
1383     //
1384     // FIXME: This is wrong. We distinguish them by asking if the path is
1385     // absolute, which isn't the same thing. And there might be multiple '/'s
1386     // in a row. Use a better mechanism to indicate whether we have emitted an
1387     // absolute or relative path.
1388     ++Pos;
1389   }
1390 
1391   return Filename + Pos;
1392 }
1393 
1394 ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
1395   // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
1396   llvm::SHA1 Hasher;
1397   Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
1398   auto Hash = Hasher.result();
1399 
1400   // Convert to an array [5*i32].
1401   ASTFileSignature Signature;
1402   auto LShift = [&](unsigned char Val, unsigned Shift) {
1403     return (uint32_t)Val << Shift;
1404   };
1405   for (int I = 0; I != 5; ++I)
1406     Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
1407                    LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
1408 
1409   return Signature;
1410 }
1411 
1412 ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1413                                                       ASTContext &Context) {
1414   // Flush first to prepare the PCM hash (signature).
1415   Stream.FlushToWord();
1416   auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1417 
1418   // Enter the block and prepare to write records.
1419   RecordData Record;
1420   Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1421 
1422   // For implicit modules, write the hash of the PCM as its signature.
1423   ASTFileSignature Signature;
1424   if (WritingModule &&
1425       PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1426     Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1427     Record.append(Signature.begin(), Signature.end());
1428     Stream.EmitRecord(SIGNATURE, Record);
1429     Record.clear();
1430   }
1431 
1432   // Diagnostic options.
1433   const auto &Diags = Context.getDiagnostics();
1434   const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1435 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1436 #define ENUM_DIAGOPT(Name, Type, Bits, Default)                                \
1437   Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1438 #include "clang/Basic/DiagnosticOptions.def"
1439   Record.push_back(DiagOpts.Warnings.size());
1440   for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1441     AddString(DiagOpts.Warnings[I], Record);
1442   Record.push_back(DiagOpts.Remarks.size());
1443   for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1444     AddString(DiagOpts.Remarks[I], Record);
1445   // Note: we don't serialize the log or serialization file names, because they
1446   // are generally transient files and will almost always be overridden.
1447   Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1448 
1449   // Write out the diagnostic/pragma mappings.
1450   WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
1451 
1452   // Leave the options block.
1453   Stream.ExitBlock();
1454   return Signature;
1455 }
1456 
1457 /// Write the control block.
1458 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1459                                   StringRef isysroot,
1460                                   const std::string &OutputFile) {
1461   using namespace llvm;
1462 
1463   Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1464   RecordData Record;
1465 
1466   // Metadata
1467   auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1468   MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1469   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1470   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1471   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1472   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1473   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1474   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1475   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile
1476   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1477   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1478   unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1479   assert((!WritingModule || isysroot.empty()) &&
1480          "writing module as a relocatable PCH?");
1481   {
1482     RecordData::value_type Record[] = {
1483         METADATA,
1484         VERSION_MAJOR,
1485         VERSION_MINOR,
1486         CLANG_VERSION_MAJOR,
1487         CLANG_VERSION_MINOR,
1488         !isysroot.empty(),
1489         IncludeTimestamps,
1490         Context.getLangOpts().BuildingPCHWithObjectFile,
1491         ASTHasCompilerErrors};
1492     Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1493                               getClangFullRepositoryVersion());
1494   }
1495 
1496   if (WritingModule) {
1497     // Module name
1498     auto Abbrev = std::make_shared<BitCodeAbbrev>();
1499     Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1500     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1501     unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1502     RecordData::value_type Record[] = {MODULE_NAME};
1503     Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1504   }
1505 
1506   if (WritingModule && WritingModule->Directory) {
1507     SmallString<128> BaseDir(WritingModule->Directory->getName());
1508     cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1509 
1510     // If the home of the module is the current working directory, then we
1511     // want to pick up the cwd of the build process loading the module, not
1512     // our cwd, when we load this module.
1513     if (!PP.getHeaderSearchInfo()
1514              .getHeaderSearchOpts()
1515              .ModuleMapFileHomeIsCwd ||
1516         WritingModule->Directory->getName() != StringRef(".")) {
1517       // Module directory.
1518       auto Abbrev = std::make_shared<BitCodeAbbrev>();
1519       Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1520       Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1521       unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1522 
1523       RecordData::value_type Record[] = {MODULE_DIRECTORY};
1524       Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1525     }
1526 
1527     // Write out all other paths relative to the base directory if possible.
1528     BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1529   } else if (!isysroot.empty()) {
1530     // Write out paths relative to the sysroot if possible.
1531     BaseDirectory = isysroot;
1532   }
1533 
1534   // Module map file
1535   if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1536     Record.clear();
1537 
1538     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1539     AddPath(WritingModule->PresumedModuleMapFile.empty()
1540                 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1541                 : StringRef(WritingModule->PresumedModuleMapFile),
1542             Record);
1543 
1544     // Additional module map files.
1545     if (auto *AdditionalModMaps =
1546             Map.getAdditionalModuleMapFiles(WritingModule)) {
1547       Record.push_back(AdditionalModMaps->size());
1548       for (const FileEntry *F : *AdditionalModMaps)
1549         AddPath(F->getName(), Record);
1550     } else {
1551       Record.push_back(0);
1552     }
1553 
1554     Stream.EmitRecord(MODULE_MAP_FILE, Record);
1555   }
1556 
1557   // Imports
1558   if (Chain) {
1559     serialization::ModuleManager &Mgr = Chain->getModuleManager();
1560     Record.clear();
1561 
1562     for (ModuleFile &M : Mgr) {
1563       // Skip modules that weren't directly imported.
1564       if (!M.isDirectlyImported())
1565         continue;
1566 
1567       Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1568       AddSourceLocation(M.ImportLoc, Record);
1569 
1570       // If we have calculated signature, there is no need to store
1571       // the size or timestamp.
1572       Record.push_back(M.Signature ? 0 : M.File->getSize());
1573       Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1574 
1575       for (auto I : M.Signature)
1576         Record.push_back(I);
1577 
1578       AddString(M.ModuleName, Record);
1579       AddPath(M.FileName, Record);
1580     }
1581     Stream.EmitRecord(IMPORTS, Record);
1582   }
1583 
1584   // Write the options block.
1585   Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1586 
1587   // Language options.
1588   Record.clear();
1589   const LangOptions &LangOpts = Context.getLangOpts();
1590 #define LANGOPT(Name, Bits, Default, Description) \
1591   Record.push_back(LangOpts.Name);
1592 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1593   Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1594 #include "clang/Basic/LangOptions.def"
1595 #define SANITIZER(NAME, ID)                                                    \
1596   Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1597 #include "clang/Basic/Sanitizers.def"
1598 
1599   Record.push_back(LangOpts.ModuleFeatures.size());
1600   for (StringRef Feature : LangOpts.ModuleFeatures)
1601     AddString(Feature, Record);
1602 
1603   Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1604   AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1605 
1606   AddString(LangOpts.CurrentModule, Record);
1607 
1608   // Comment options.
1609   Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1610   for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1611     AddString(I, Record);
1612   }
1613   Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1614 
1615   // OpenMP offloading options.
1616   Record.push_back(LangOpts.OMPTargetTriples.size());
1617   for (auto &T : LangOpts.OMPTargetTriples)
1618     AddString(T.getTriple(), Record);
1619 
1620   AddString(LangOpts.OMPHostIRFile, Record);
1621 
1622   Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1623 
1624   // Target options.
1625   Record.clear();
1626   const TargetInfo &Target = Context.getTargetInfo();
1627   const TargetOptions &TargetOpts = Target.getTargetOpts();
1628   AddString(TargetOpts.Triple, Record);
1629   AddString(TargetOpts.CPU, Record);
1630   AddString(TargetOpts.ABI, Record);
1631   Record.push_back(TargetOpts.FeaturesAsWritten.size());
1632   for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1633     AddString(TargetOpts.FeaturesAsWritten[I], Record);
1634   }
1635   Record.push_back(TargetOpts.Features.size());
1636   for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1637     AddString(TargetOpts.Features[I], Record);
1638   }
1639   Stream.EmitRecord(TARGET_OPTIONS, Record);
1640 
1641   // File system options.
1642   Record.clear();
1643   const FileSystemOptions &FSOpts =
1644       Context.getSourceManager().getFileManager().getFileSystemOpts();
1645   AddString(FSOpts.WorkingDir, Record);
1646   Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1647 
1648   // Header search options.
1649   Record.clear();
1650   const HeaderSearchOptions &HSOpts
1651     = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1652   AddString(HSOpts.Sysroot, Record);
1653 
1654   // Include entries.
1655   Record.push_back(HSOpts.UserEntries.size());
1656   for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1657     const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1658     AddString(Entry.Path, Record);
1659     Record.push_back(static_cast<unsigned>(Entry.Group));
1660     Record.push_back(Entry.IsFramework);
1661     Record.push_back(Entry.IgnoreSysRoot);
1662   }
1663 
1664   // System header prefixes.
1665   Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1666   for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1667     AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1668     Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1669   }
1670 
1671   AddString(HSOpts.ResourceDir, Record);
1672   AddString(HSOpts.ModuleCachePath, Record);
1673   AddString(HSOpts.ModuleUserBuildPath, Record);
1674   Record.push_back(HSOpts.DisableModuleHash);
1675   Record.push_back(HSOpts.ImplicitModuleMaps);
1676   Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1677   Record.push_back(HSOpts.UseBuiltinIncludes);
1678   Record.push_back(HSOpts.UseStandardSystemIncludes);
1679   Record.push_back(HSOpts.UseStandardCXXIncludes);
1680   Record.push_back(HSOpts.UseLibcxx);
1681   // Write out the specific module cache path that contains the module files.
1682   AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1683   Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1684 
1685   // Preprocessor options.
1686   Record.clear();
1687   const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1688 
1689   // Macro definitions.
1690   Record.push_back(PPOpts.Macros.size());
1691   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1692     AddString(PPOpts.Macros[I].first, Record);
1693     Record.push_back(PPOpts.Macros[I].second);
1694   }
1695 
1696   // Includes
1697   Record.push_back(PPOpts.Includes.size());
1698   for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1699     AddString(PPOpts.Includes[I], Record);
1700 
1701   // Macro includes
1702   Record.push_back(PPOpts.MacroIncludes.size());
1703   for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1704     AddString(PPOpts.MacroIncludes[I], Record);
1705 
1706   Record.push_back(PPOpts.UsePredefines);
1707   // Detailed record is important since it is used for the module cache hash.
1708   Record.push_back(PPOpts.DetailedRecord);
1709   AddString(PPOpts.ImplicitPCHInclude, Record);
1710   Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1711   Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1712 
1713   // Leave the options block.
1714   Stream.ExitBlock();
1715 
1716   // Original file name and file ID
1717   SourceManager &SM = Context.getSourceManager();
1718   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1719     auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1720     FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1721     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1722     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1723     unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1724 
1725     Record.clear();
1726     Record.push_back(ORIGINAL_FILE);
1727     Record.push_back(SM.getMainFileID().getOpaqueValue());
1728     EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1729   }
1730 
1731   Record.clear();
1732   Record.push_back(SM.getMainFileID().getOpaqueValue());
1733   Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1734 
1735   // Original PCH directory
1736   if (!OutputFile.empty() && OutputFile != "-") {
1737     auto Abbrev = std::make_shared<BitCodeAbbrev>();
1738     Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1739     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1740     unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1741 
1742     SmallString<128> OutputPath(OutputFile);
1743 
1744     SM.getFileManager().makeAbsolutePath(OutputPath);
1745     StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1746 
1747     RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1748     Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1749   }
1750 
1751   WriteInputFiles(Context.SourceMgr,
1752                   PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1753                   PP.getLangOpts().Modules);
1754   Stream.ExitBlock();
1755 }
1756 
1757 namespace  {
1758 
1759 /// An input file.
1760 struct InputFileEntry {
1761   const FileEntry *File;
1762   bool IsSystemFile;
1763   bool IsTransient;
1764   bool BufferOverridden;
1765   bool IsTopLevelModuleMap;
1766 };
1767 
1768 } // namespace
1769 
1770 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1771                                 HeaderSearchOptions &HSOpts,
1772                                 bool Modules) {
1773   using namespace llvm;
1774 
1775   Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1776 
1777   // Create input-file abbreviation.
1778   auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1779   IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1780   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1781   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1782   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1783   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1784   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1785   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1786   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1787   unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1788 
1789   // Get all ContentCache objects for files, sorted by whether the file is a
1790   // system one or not. System files go at the back, users files at the front.
1791   std::deque<InputFileEntry> SortedFiles;
1792   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1793     // Get this source location entry.
1794     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1795     assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1796 
1797     // We only care about file entries that were not overridden.
1798     if (!SLoc->isFile())
1799       continue;
1800     const SrcMgr::FileInfo &File = SLoc->getFile();
1801     const SrcMgr::ContentCache *Cache = File.getContentCache();
1802     if (!Cache->OrigEntry)
1803       continue;
1804 
1805     InputFileEntry Entry;
1806     Entry.File = Cache->OrigEntry;
1807     Entry.IsSystemFile = Cache->IsSystemFile;
1808     Entry.IsTransient = Cache->IsTransient;
1809     Entry.BufferOverridden = Cache->BufferOverridden;
1810     Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1811                                 File.getIncludeLoc().isInvalid();
1812     if (Cache->IsSystemFile)
1813       SortedFiles.push_back(Entry);
1814     else
1815       SortedFiles.push_front(Entry);
1816   }
1817 
1818   unsigned UserFilesNum = 0;
1819   // Write out all of the input files.
1820   std::vector<uint64_t> InputFileOffsets;
1821   for (const auto &Entry : SortedFiles) {
1822     uint32_t &InputFileID = InputFileIDs[Entry.File];
1823     if (InputFileID != 0)
1824       continue; // already recorded this file.
1825 
1826     // Record this entry's offset.
1827     InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1828 
1829     InputFileID = InputFileOffsets.size();
1830 
1831     if (!Entry.IsSystemFile)
1832       ++UserFilesNum;
1833 
1834     // Emit size/modification time for this file.
1835     // And whether this file was overridden.
1836     RecordData::value_type Record[] = {
1837         INPUT_FILE,
1838         InputFileOffsets.size(),
1839         (uint64_t)Entry.File->getSize(),
1840         (uint64_t)getTimestampForOutput(Entry.File),
1841         Entry.BufferOverridden,
1842         Entry.IsTransient,
1843         Entry.IsTopLevelModuleMap};
1844 
1845     EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1846   }
1847 
1848   Stream.ExitBlock();
1849 
1850   // Create input file offsets abbreviation.
1851   auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1852   OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1853   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1854   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1855                                                                 //   input files
1856   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));   // Array
1857   unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1858 
1859   // Write input file offsets.
1860   RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1861                                      InputFileOffsets.size(), UserFilesNum};
1862   Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1863 }
1864 
1865 //===----------------------------------------------------------------------===//
1866 // Source Manager Serialization
1867 //===----------------------------------------------------------------------===//
1868 
1869 /// Create an abbreviation for the SLocEntry that refers to a
1870 /// file.
1871 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1872   using namespace llvm;
1873 
1874   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1875   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1876   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1877   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1878   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1879   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1880   // FileEntry fields.
1881   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1882   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1883   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1884   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1885   return Stream.EmitAbbrev(std::move(Abbrev));
1886 }
1887 
1888 /// Create an abbreviation for the SLocEntry that refers to a
1889 /// buffer.
1890 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1891   using namespace llvm;
1892 
1893   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1894   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1895   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1896   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1897   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1898   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1899   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1900   return Stream.EmitAbbrev(std::move(Abbrev));
1901 }
1902 
1903 /// Create an abbreviation for the SLocEntry that refers to a
1904 /// buffer's blob.
1905 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1906                                            bool Compressed) {
1907   using namespace llvm;
1908 
1909   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1910   Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1911                                          : SM_SLOC_BUFFER_BLOB));
1912   if (Compressed)
1913     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1914   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1915   return Stream.EmitAbbrev(std::move(Abbrev));
1916 }
1917 
1918 /// Create an abbreviation for the SLocEntry that refers to a macro
1919 /// expansion.
1920 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1921   using namespace llvm;
1922 
1923   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1924   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1925   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1926   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1927   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1928   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1929   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
1930   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1931   return Stream.EmitAbbrev(std::move(Abbrev));
1932 }
1933 
1934 namespace {
1935 
1936   // Trait used for the on-disk hash table of header search information.
1937   class HeaderFileInfoTrait {
1938     ASTWriter &Writer;
1939 
1940     // Keep track of the framework names we've used during serialization.
1941     SmallVector<char, 128> FrameworkStringData;
1942     llvm::StringMap<unsigned> FrameworkNameOffset;
1943 
1944   public:
1945     HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1946 
1947     struct key_type {
1948       StringRef Filename;
1949       off_t Size;
1950       time_t ModTime;
1951     };
1952     using key_type_ref = const key_type &;
1953 
1954     using UnresolvedModule =
1955         llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1956 
1957     struct data_type {
1958       const HeaderFileInfo &HFI;
1959       ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1960       UnresolvedModule Unresolved;
1961     };
1962     using data_type_ref = const data_type &;
1963 
1964     using hash_value_type = unsigned;
1965     using offset_type = unsigned;
1966 
1967     hash_value_type ComputeHash(key_type_ref key) {
1968       // The hash is based only on size/time of the file, so that the reader can
1969       // match even when symlinking or excess path elements ("foo/../", "../")
1970       // change the form of the name. However, complete path is still the key.
1971       return llvm::hash_combine(key.Size, key.ModTime);
1972     }
1973 
1974     std::pair<unsigned, unsigned>
1975     EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1976       using namespace llvm::support;
1977 
1978       endian::Writer LE(Out, little);
1979       unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1980       LE.write<uint16_t>(KeyLen);
1981       unsigned DataLen = 1 + 2 + 4 + 4;
1982       for (auto ModInfo : Data.KnownHeaders)
1983         if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1984           DataLen += 4;
1985       if (Data.Unresolved.getPointer())
1986         DataLen += 4;
1987       LE.write<uint8_t>(DataLen);
1988       return std::make_pair(KeyLen, DataLen);
1989     }
1990 
1991     void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1992       using namespace llvm::support;
1993 
1994       endian::Writer LE(Out, little);
1995       LE.write<uint64_t>(key.Size);
1996       KeyLen -= 8;
1997       LE.write<uint64_t>(key.ModTime);
1998       KeyLen -= 8;
1999       Out.write(key.Filename.data(), KeyLen);
2000     }
2001 
2002     void EmitData(raw_ostream &Out, key_type_ref key,
2003                   data_type_ref Data, unsigned DataLen) {
2004       using namespace llvm::support;
2005 
2006       endian::Writer LE(Out, little);
2007       uint64_t Start = Out.tell(); (void)Start;
2008 
2009       unsigned char Flags = (Data.HFI.isImport << 5)
2010                           | (Data.HFI.isPragmaOnce << 4)
2011                           | (Data.HFI.DirInfo << 1)
2012                           | Data.HFI.IndexHeaderMapHeader;
2013       LE.write<uint8_t>(Flags);
2014       LE.write<uint16_t>(Data.HFI.NumIncludes);
2015 
2016       if (!Data.HFI.ControllingMacro)
2017         LE.write<uint32_t>(Data.HFI.ControllingMacroID);
2018       else
2019         LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
2020 
2021       unsigned Offset = 0;
2022       if (!Data.HFI.Framework.empty()) {
2023         // If this header refers into a framework, save the framework name.
2024         llvm::StringMap<unsigned>::iterator Pos
2025           = FrameworkNameOffset.find(Data.HFI.Framework);
2026         if (Pos == FrameworkNameOffset.end()) {
2027           Offset = FrameworkStringData.size() + 1;
2028           FrameworkStringData.append(Data.HFI.Framework.begin(),
2029                                      Data.HFI.Framework.end());
2030           FrameworkStringData.push_back(0);
2031 
2032           FrameworkNameOffset[Data.HFI.Framework] = Offset;
2033         } else
2034           Offset = Pos->second;
2035       }
2036       LE.write<uint32_t>(Offset);
2037 
2038       auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
2039         if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
2040           uint32_t Value = (ModID << 2) | (unsigned)Role;
2041           assert((Value >> 2) == ModID && "overflow in header module info");
2042           LE.write<uint32_t>(Value);
2043         }
2044       };
2045 
2046       // FIXME: If the header is excluded, we should write out some
2047       // record of that fact.
2048       for (auto ModInfo : Data.KnownHeaders)
2049         EmitModule(ModInfo.getModule(), ModInfo.getRole());
2050       if (Data.Unresolved.getPointer())
2051         EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
2052 
2053       assert(Out.tell() - Start == DataLen && "Wrong data length");
2054     }
2055 
2056     const char *strings_begin() const { return FrameworkStringData.begin(); }
2057     const char *strings_end() const { return FrameworkStringData.end(); }
2058   };
2059 
2060 } // namespace
2061 
2062 /// Write the header search block for the list of files that
2063 ///
2064 /// \param HS The header search structure to save.
2065 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
2066   HeaderFileInfoTrait GeneratorTrait(*this);
2067   llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
2068   SmallVector<const char *, 4> SavedStrings;
2069   unsigned NumHeaderSearchEntries = 0;
2070 
2071   // Find all unresolved headers for the current module. We generally will
2072   // have resolved them before we get here, but not necessarily: we might be
2073   // compiling a preprocessed module, where there is no requirement for the
2074   // original files to exist any more.
2075   const HeaderFileInfo Empty; // So we can take a reference.
2076   if (WritingModule) {
2077     llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2078     while (!Worklist.empty()) {
2079       Module *M = Worklist.pop_back_val();
2080       if (!M->isAvailable())
2081         continue;
2082 
2083       // Map to disk files where possible, to pick up any missing stat
2084       // information. This also means we don't need to check the unresolved
2085       // headers list when emitting resolved headers in the first loop below.
2086       // FIXME: It'd be preferable to avoid doing this if we were given
2087       // sufficient stat information in the module map.
2088       HS.getModuleMap().resolveHeaderDirectives(M);
2089 
2090       // If the file didn't exist, we can still create a module if we were given
2091       // enough information in the module map.
2092       for (auto U : M->MissingHeaders) {
2093         // Check that we were given enough information to build a module
2094         // without this file existing on disk.
2095         if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
2096           PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2097             << WritingModule->getFullModuleName() << U.Size.hasValue()
2098             << U.FileName;
2099           continue;
2100         }
2101 
2102         // Form the effective relative pathname for the file.
2103         SmallString<128> Filename(M->Directory->getName());
2104         llvm::sys::path::append(Filename, U.FileName);
2105         PreparePathForOutput(Filename);
2106 
2107         StringRef FilenameDup = strdup(Filename.c_str());
2108         SavedStrings.push_back(FilenameDup.data());
2109 
2110         HeaderFileInfoTrait::key_type Key = {
2111           FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
2112         };
2113         HeaderFileInfoTrait::data_type Data = {
2114           Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
2115         };
2116         // FIXME: Deal with cases where there are multiple unresolved header
2117         // directives in different submodules for the same header.
2118         Generator.insert(Key, Data, GeneratorTrait);
2119         ++NumHeaderSearchEntries;
2120       }
2121 
2122       Worklist.append(M->submodule_begin(), M->submodule_end());
2123     }
2124   }
2125 
2126   SmallVector<const FileEntry *, 16> FilesByUID;
2127   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
2128 
2129   if (FilesByUID.size() > HS.header_file_size())
2130     FilesByUID.resize(HS.header_file_size());
2131 
2132   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
2133     const FileEntry *File = FilesByUID[UID];
2134     if (!File)
2135       continue;
2136 
2137     // Get the file info. This will load info from the external source if
2138     // necessary. Skip emitting this file if we have no information on it
2139     // as a header file (in which case HFI will be null) or if it hasn't
2140     // changed since it was loaded. Also skip it if it's for a modular header
2141     // from a different module; in that case, we rely on the module(s)
2142     // containing the header to provide this information.
2143     const HeaderFileInfo *HFI =
2144         HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
2145     if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
2146       continue;
2147 
2148     // Massage the file path into an appropriate form.
2149     StringRef Filename = File->getName();
2150     SmallString<128> FilenameTmp(Filename);
2151     if (PreparePathForOutput(FilenameTmp)) {
2152       // If we performed any translation on the file name at all, we need to
2153       // save this string, since the generator will refer to it later.
2154       Filename = StringRef(strdup(FilenameTmp.c_str()));
2155       SavedStrings.push_back(Filename.data());
2156     }
2157 
2158     HeaderFileInfoTrait::key_type Key = {
2159       Filename, File->getSize(), getTimestampForOutput(File)
2160     };
2161     HeaderFileInfoTrait::data_type Data = {
2162       *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
2163     };
2164     Generator.insert(Key, Data, GeneratorTrait);
2165     ++NumHeaderSearchEntries;
2166   }
2167 
2168   // Create the on-disk hash table in a buffer.
2169   SmallString<4096> TableData;
2170   uint32_t BucketOffset;
2171   {
2172     using namespace llvm::support;
2173 
2174     llvm::raw_svector_ostream Out(TableData);
2175     // Make sure that no bucket is at offset 0
2176     endian::write<uint32_t>(Out, 0, little);
2177     BucketOffset = Generator.Emit(Out, GeneratorTrait);
2178   }
2179 
2180   // Create a blob abbreviation
2181   using namespace llvm;
2182 
2183   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2184   Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2185   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2186   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2187   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2188   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2189   unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2190 
2191   // Write the header search table
2192   RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2193                                      NumHeaderSearchEntries, TableData.size()};
2194   TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
2195   Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
2196 
2197   // Free all of the strings we had to duplicate.
2198   for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
2199     free(const_cast<char *>(SavedStrings[I]));
2200 }
2201 
2202 static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2203                      unsigned SLocBufferBlobCompressedAbbrv,
2204                      unsigned SLocBufferBlobAbbrv) {
2205   using RecordDataType = ASTWriter::RecordData::value_type;
2206 
2207   // Compress the buffer if possible. We expect that almost all PCM
2208   // consumers will not want its contents.
2209   SmallString<0> CompressedBuffer;
2210   if (llvm::zlib::isAvailable()) {
2211     llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
2212     if (!E) {
2213       RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2214                                  Blob.size() - 1};
2215       Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2216                                 CompressedBuffer);
2217       return;
2218     }
2219     llvm::consumeError(std::move(E));
2220   }
2221 
2222   RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2223   Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2224 }
2225 
2226 /// Writes the block containing the serialized form of the
2227 /// source manager.
2228 ///
2229 /// TODO: We should probably use an on-disk hash table (stored in a
2230 /// blob), indexed based on the file name, so that we only create
2231 /// entries for files that we actually need. In the common case (no
2232 /// errors), we probably won't have to create file entries for any of
2233 /// the files in the AST.
2234 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2235                                         const Preprocessor &PP) {
2236   RecordData Record;
2237 
2238   // Enter the source manager block.
2239   Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2240 
2241   // Abbreviations for the various kinds of source-location entries.
2242   unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2243   unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2244   unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2245   unsigned SLocBufferBlobCompressedAbbrv =
2246       CreateSLocBufferBlobAbbrev(Stream, true);
2247   unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2248 
2249   // Write out the source location entry table. We skip the first
2250   // entry, which is always the same dummy entry.
2251   std::vector<uint32_t> SLocEntryOffsets;
2252   RecordData PreloadSLocs;
2253   SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2254   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2255        I != N; ++I) {
2256     // Get this source location entry.
2257     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2258     FileID FID = FileID::get(I);
2259     assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2260 
2261     // Record the offset of this source-location entry.
2262     SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
2263 
2264     // Figure out which record code to use.
2265     unsigned Code;
2266     if (SLoc->isFile()) {
2267       const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
2268       if (Cache->OrigEntry) {
2269         Code = SM_SLOC_FILE_ENTRY;
2270       } else
2271         Code = SM_SLOC_BUFFER_ENTRY;
2272     } else
2273       Code = SM_SLOC_EXPANSION_ENTRY;
2274     Record.clear();
2275     Record.push_back(Code);
2276 
2277     // Starting offset of this entry within this module, so skip the dummy.
2278     Record.push_back(SLoc->getOffset() - 2);
2279     if (SLoc->isFile()) {
2280       const SrcMgr::FileInfo &File = SLoc->getFile();
2281       AddSourceLocation(File.getIncludeLoc(), Record);
2282       Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2283       Record.push_back(File.hasLineDirectives());
2284 
2285       const SrcMgr::ContentCache *Content = File.getContentCache();
2286       bool EmitBlob = false;
2287       if (Content->OrigEntry) {
2288         assert(Content->OrigEntry == Content->ContentsEntry &&
2289                "Writing to AST an overridden file is not supported");
2290 
2291         // The source location entry is a file. Emit input file ID.
2292         assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2293         Record.push_back(InputFileIDs[Content->OrigEntry]);
2294 
2295         Record.push_back(File.NumCreatedFIDs);
2296 
2297         FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2298         if (FDI != FileDeclIDs.end()) {
2299           Record.push_back(FDI->second->FirstDeclIndex);
2300           Record.push_back(FDI->second->DeclIDs.size());
2301         } else {
2302           Record.push_back(0);
2303           Record.push_back(0);
2304         }
2305 
2306         Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2307 
2308         if (Content->BufferOverridden || Content->IsTransient)
2309           EmitBlob = true;
2310       } else {
2311         // The source location entry is a buffer. The blob associated
2312         // with this entry contains the contents of the buffer.
2313 
2314         // We add one to the size so that we capture the trailing NULL
2315         // that is required by llvm::MemoryBuffer::getMemBuffer (on
2316         // the reader side).
2317         const llvm::MemoryBuffer *Buffer
2318           = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2319         StringRef Name = Buffer->getBufferIdentifier();
2320         Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2321                                   StringRef(Name.data(), Name.size() + 1));
2322         EmitBlob = true;
2323 
2324         if (Name == "<built-in>")
2325           PreloadSLocs.push_back(SLocEntryOffsets.size());
2326       }
2327 
2328       if (EmitBlob) {
2329         // Include the implicit terminating null character in the on-disk buffer
2330         // if we're writing it uncompressed.
2331         const llvm::MemoryBuffer *Buffer =
2332             Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2333         StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2334         emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2335                  SLocBufferBlobAbbrv);
2336       }
2337     } else {
2338       // The source location entry is a macro expansion.
2339       const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2340       AddSourceLocation(Expansion.getSpellingLoc(), Record);
2341       AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2342       AddSourceLocation(Expansion.isMacroArgExpansion()
2343                             ? SourceLocation()
2344                             : Expansion.getExpansionLocEnd(),
2345                         Record);
2346       Record.push_back(Expansion.isExpansionTokenRange());
2347 
2348       // Compute the token length for this macro expansion.
2349       unsigned NextOffset = SourceMgr.getNextLocalOffset();
2350       if (I + 1 != N)
2351         NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2352       Record.push_back(NextOffset - SLoc->getOffset() - 1);
2353       Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2354     }
2355   }
2356 
2357   Stream.ExitBlock();
2358 
2359   if (SLocEntryOffsets.empty())
2360     return;
2361 
2362   // Write the source-location offsets table into the AST block. This
2363   // table is used for lazily loading source-location information.
2364   using namespace llvm;
2365 
2366   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2367   Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2368   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2369   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2370   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2371   unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2372   {
2373     RecordData::value_type Record[] = {
2374         SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2375         SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2376     Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2377                               bytes(SLocEntryOffsets));
2378   }
2379   // Write the source location entry preloads array, telling the AST
2380   // reader which source locations entries it should load eagerly.
2381   Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2382 
2383   // Write the line table. It depends on remapping working, so it must come
2384   // after the source location offsets.
2385   if (SourceMgr.hasLineTable()) {
2386     LineTableInfo &LineTable = SourceMgr.getLineTable();
2387 
2388     Record.clear();
2389 
2390     // Emit the needed file names.
2391     llvm::DenseMap<int, int> FilenameMap;
2392     FilenameMap[-1] = -1; // For unspecified filenames.
2393     for (const auto &L : LineTable) {
2394       if (L.first.ID < 0)
2395         continue;
2396       for (auto &LE : L.second) {
2397         if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2398                                               FilenameMap.size() - 1)).second)
2399           AddPath(LineTable.getFilename(LE.FilenameID), Record);
2400       }
2401     }
2402     Record.push_back(0);
2403 
2404     // Emit the line entries
2405     for (const auto &L : LineTable) {
2406       // Only emit entries for local files.
2407       if (L.first.ID < 0)
2408         continue;
2409 
2410       // Emit the file ID
2411       Record.push_back(L.first.ID);
2412 
2413       // Emit the line entries
2414       Record.push_back(L.second.size());
2415       for (const auto &LE : L.second) {
2416         Record.push_back(LE.FileOffset);
2417         Record.push_back(LE.LineNo);
2418         Record.push_back(FilenameMap[LE.FilenameID]);
2419         Record.push_back((unsigned)LE.FileKind);
2420         Record.push_back(LE.IncludeOffset);
2421       }
2422     }
2423 
2424     Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2425   }
2426 }
2427 
2428 //===----------------------------------------------------------------------===//
2429 // Preprocessor Serialization
2430 //===----------------------------------------------------------------------===//
2431 
2432 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2433                               const Preprocessor &PP) {
2434   if (MacroInfo *MI = MD->getMacroInfo())
2435     if (MI->isBuiltinMacro())
2436       return true;
2437 
2438   if (IsModule) {
2439     SourceLocation Loc = MD->getLocation();
2440     if (Loc.isInvalid())
2441       return true;
2442     if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2443       return true;
2444   }
2445 
2446   return false;
2447 }
2448 
2449 /// Writes the block containing the serialized form of the
2450 /// preprocessor.
2451 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2452   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2453   if (PPRec)
2454     WritePreprocessorDetail(*PPRec);
2455 
2456   RecordData Record;
2457   RecordData ModuleMacroRecord;
2458 
2459   // If the preprocessor __COUNTER__ value has been bumped, remember it.
2460   if (PP.getCounterValue() != 0) {
2461     RecordData::value_type Record[] = {PP.getCounterValue()};
2462     Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2463   }
2464 
2465   if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2466     assert(!IsModule);
2467     auto SkipInfo = PP.getPreambleSkipInfo();
2468     if (SkipInfo.hasValue()) {
2469       Record.push_back(true);
2470       AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2471       AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2472       Record.push_back(SkipInfo->FoundNonSkipPortion);
2473       Record.push_back(SkipInfo->FoundElse);
2474       AddSourceLocation(SkipInfo->ElseLoc, Record);
2475     } else {
2476       Record.push_back(false);
2477     }
2478     for (const auto &Cond : PP.getPreambleConditionalStack()) {
2479       AddSourceLocation(Cond.IfLoc, Record);
2480       Record.push_back(Cond.WasSkipping);
2481       Record.push_back(Cond.FoundNonSkip);
2482       Record.push_back(Cond.FoundElse);
2483     }
2484     Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2485     Record.clear();
2486   }
2487 
2488   // Enter the preprocessor block.
2489   Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2490 
2491   // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2492   // FIXME: Include a location for the use, and say which one was used.
2493   if (PP.SawDateOrTime())
2494     PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2495 
2496   // Loop over all the macro directives that are live at the end of the file,
2497   // emitting each to the PP section.
2498 
2499   // Construct the list of identifiers with macro directives that need to be
2500   // serialized.
2501   SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2502   for (auto &Id : PP.getIdentifierTable())
2503     if (Id.second->hadMacroDefinition() &&
2504         (!Id.second->isFromAST() ||
2505          Id.second->hasChangedSinceDeserialization()))
2506       MacroIdentifiers.push_back(Id.second);
2507   // Sort the set of macro definitions that need to be serialized by the
2508   // name of the macro, to provide a stable ordering.
2509   llvm::sort(MacroIdentifiers, llvm::less_ptr<IdentifierInfo>());
2510 
2511   // Emit the macro directives as a list and associate the offset with the
2512   // identifier they belong to.
2513   for (const IdentifierInfo *Name : MacroIdentifiers) {
2514     MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2515     auto StartOffset = Stream.GetCurrentBitNo();
2516 
2517     // Emit the macro directives in reverse source order.
2518     for (; MD; MD = MD->getPrevious()) {
2519       // Once we hit an ignored macro, we're done: the rest of the chain
2520       // will all be ignored macros.
2521       if (shouldIgnoreMacro(MD, IsModule, PP))
2522         break;
2523 
2524       AddSourceLocation(MD->getLocation(), Record);
2525       Record.push_back(MD->getKind());
2526       if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2527         Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2528       } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2529         Record.push_back(VisMD->isPublic());
2530       }
2531     }
2532 
2533     // Write out any exported module macros.
2534     bool EmittedModuleMacros = false;
2535     // We write out exported module macros for PCH as well.
2536     auto Leafs = PP.getLeafModuleMacros(Name);
2537     SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2538     llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2539     while (!Worklist.empty()) {
2540       auto *Macro = Worklist.pop_back_val();
2541 
2542       // Emit a record indicating this submodule exports this macro.
2543       ModuleMacroRecord.push_back(
2544           getSubmoduleID(Macro->getOwningModule()));
2545       ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2546       for (auto *M : Macro->overrides())
2547         ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2548 
2549       Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2550       ModuleMacroRecord.clear();
2551 
2552       // Enqueue overridden macros once we've visited all their ancestors.
2553       for (auto *M : Macro->overrides())
2554         if (++Visits[M] == M->getNumOverridingMacros())
2555           Worklist.push_back(M);
2556 
2557       EmittedModuleMacros = true;
2558     }
2559 
2560     if (Record.empty() && !EmittedModuleMacros)
2561       continue;
2562 
2563     IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2564     Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2565     Record.clear();
2566   }
2567 
2568   /// Offsets of each of the macros into the bitstream, indexed by
2569   /// the local macro ID
2570   ///
2571   /// For each identifier that is associated with a macro, this map
2572   /// provides the offset into the bitstream where that macro is
2573   /// defined.
2574   std::vector<uint32_t> MacroOffsets;
2575 
2576   for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2577     const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2578     MacroInfo *MI = MacroInfosToEmit[I].MI;
2579     MacroID ID = MacroInfosToEmit[I].ID;
2580 
2581     if (ID < FirstMacroID) {
2582       assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2583       continue;
2584     }
2585 
2586     // Record the local offset of this macro.
2587     unsigned Index = ID - FirstMacroID;
2588     if (Index == MacroOffsets.size())
2589       MacroOffsets.push_back(Stream.GetCurrentBitNo());
2590     else {
2591       if (Index > MacroOffsets.size())
2592         MacroOffsets.resize(Index + 1);
2593 
2594       MacroOffsets[Index] = Stream.GetCurrentBitNo();
2595     }
2596 
2597     AddIdentifierRef(Name, Record);
2598     AddSourceLocation(MI->getDefinitionLoc(), Record);
2599     AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2600     Record.push_back(MI->isUsed());
2601     Record.push_back(MI->isUsedForHeaderGuard());
2602     unsigned Code;
2603     if (MI->isObjectLike()) {
2604       Code = PP_MACRO_OBJECT_LIKE;
2605     } else {
2606       Code = PP_MACRO_FUNCTION_LIKE;
2607 
2608       Record.push_back(MI->isC99Varargs());
2609       Record.push_back(MI->isGNUVarargs());
2610       Record.push_back(MI->hasCommaPasting());
2611       Record.push_back(MI->getNumParams());
2612       for (const IdentifierInfo *Param : MI->params())
2613         AddIdentifierRef(Param, Record);
2614     }
2615 
2616     // If we have a detailed preprocessing record, record the macro definition
2617     // ID that corresponds to this macro.
2618     if (PPRec)
2619       Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2620 
2621     Stream.EmitRecord(Code, Record);
2622     Record.clear();
2623 
2624     // Emit the tokens array.
2625     for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2626       // Note that we know that the preprocessor does not have any annotation
2627       // tokens in it because they are created by the parser, and thus can't
2628       // be in a macro definition.
2629       const Token &Tok = MI->getReplacementToken(TokNo);
2630       AddToken(Tok, Record);
2631       Stream.EmitRecord(PP_TOKEN, Record);
2632       Record.clear();
2633     }
2634     ++NumMacros;
2635   }
2636 
2637   Stream.ExitBlock();
2638 
2639   // Write the offsets table for macro IDs.
2640   using namespace llvm;
2641 
2642   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2643   Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2644   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2645   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2646   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2647 
2648   unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2649   {
2650     RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2651                                        FirstMacroID - NUM_PREDEF_MACRO_IDS};
2652     Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2653   }
2654 }
2655 
2656 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2657   if (PPRec.local_begin() == PPRec.local_end())
2658     return;
2659 
2660   SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2661 
2662   // Enter the preprocessor block.
2663   Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2664 
2665   // If the preprocessor has a preprocessing record, emit it.
2666   unsigned NumPreprocessingRecords = 0;
2667   using namespace llvm;
2668 
2669   // Set up the abbreviation for
2670   unsigned InclusionAbbrev = 0;
2671   {
2672     auto Abbrev = std::make_shared<BitCodeAbbrev>();
2673     Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2674     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2675     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2676     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2677     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2678     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2679     InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2680   }
2681 
2682   unsigned FirstPreprocessorEntityID
2683     = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2684     + NUM_PREDEF_PP_ENTITY_IDS;
2685   unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2686   RecordData Record;
2687   for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2688                                   EEnd = PPRec.local_end();
2689        E != EEnd;
2690        (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2691     Record.clear();
2692 
2693     PreprocessedEntityOffsets.push_back(
2694         PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
2695 
2696     if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2697       // Record this macro definition's ID.
2698       MacroDefinitions[MD] = NextPreprocessorEntityID;
2699 
2700       AddIdentifierRef(MD->getName(), Record);
2701       Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2702       continue;
2703     }
2704 
2705     if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2706       Record.push_back(ME->isBuiltinMacro());
2707       if (ME->isBuiltinMacro())
2708         AddIdentifierRef(ME->getName(), Record);
2709       else
2710         Record.push_back(MacroDefinitions[ME->getDefinition()]);
2711       Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2712       continue;
2713     }
2714 
2715     if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2716       Record.push_back(PPD_INCLUSION_DIRECTIVE);
2717       Record.push_back(ID->getFileName().size());
2718       Record.push_back(ID->wasInQuotes());
2719       Record.push_back(static_cast<unsigned>(ID->getKind()));
2720       Record.push_back(ID->importedModule());
2721       SmallString<64> Buffer;
2722       Buffer += ID->getFileName();
2723       // Check that the FileEntry is not null because it was not resolved and
2724       // we create a PCH even with compiler errors.
2725       if (ID->getFile())
2726         Buffer += ID->getFile()->getName();
2727       Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2728       continue;
2729     }
2730 
2731     llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2732   }
2733   Stream.ExitBlock();
2734 
2735   // Write the offsets table for the preprocessing record.
2736   if (NumPreprocessingRecords > 0) {
2737     assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2738 
2739     // Write the offsets table for identifier IDs.
2740     using namespace llvm;
2741 
2742     auto Abbrev = std::make_shared<BitCodeAbbrev>();
2743     Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2744     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2745     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2746     unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2747 
2748     RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2749                                        FirstPreprocessorEntityID -
2750                                            NUM_PREDEF_PP_ENTITY_IDS};
2751     Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2752                               bytes(PreprocessedEntityOffsets));
2753   }
2754 
2755   // Write the skipped region table for the preprocessing record.
2756   ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2757   if (SkippedRanges.size() > 0) {
2758     std::vector<PPSkippedRange> SerializedSkippedRanges;
2759     SerializedSkippedRanges.reserve(SkippedRanges.size());
2760     for (auto const& Range : SkippedRanges)
2761       SerializedSkippedRanges.emplace_back(Range);
2762 
2763     using namespace llvm;
2764     auto Abbrev = std::make_shared<BitCodeAbbrev>();
2765     Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2766     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2767     unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2768 
2769     Record.clear();
2770     Record.push_back(PPD_SKIPPED_RANGES);
2771     Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2772                               bytes(SerializedSkippedRanges));
2773   }
2774 }
2775 
2776 unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
2777   if (!Mod)
2778     return 0;
2779 
2780   llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2781   if (Known != SubmoduleIDs.end())
2782     return Known->second;
2783 
2784   auto *Top = Mod->getTopLevelModule();
2785   if (Top != WritingModule &&
2786       (getLangOpts().CompilingPCH ||
2787        !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2788     return 0;
2789 
2790   return SubmoduleIDs[Mod] = NextSubmoduleID++;
2791 }
2792 
2793 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2794   // FIXME: This can easily happen, if we have a reference to a submodule that
2795   // did not result in us loading a module file for that submodule. For
2796   // instance, a cross-top-level-module 'conflict' declaration will hit this.
2797   unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2798   assert((ID || !Mod) &&
2799          "asked for module ID for non-local, non-imported module");
2800   return ID;
2801 }
2802 
2803 /// Compute the number of modules within the given tree (including the
2804 /// given module).
2805 static unsigned getNumberOfModules(Module *Mod) {
2806   unsigned ChildModules = 0;
2807   for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2808        Sub != SubEnd; ++Sub)
2809     ChildModules += getNumberOfModules(*Sub);
2810 
2811   return ChildModules + 1;
2812 }
2813 
2814 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2815   // Enter the submodule description block.
2816   Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2817 
2818   // Write the abbreviations needed for the submodules block.
2819   using namespace llvm;
2820 
2821   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2822   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2823   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2824   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2825   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
2826   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2827   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2828   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2829   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2830   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2831   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2832   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2833   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2834   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2835   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2836   unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2837 
2838   Abbrev = std::make_shared<BitCodeAbbrev>();
2839   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2840   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2841   unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2842 
2843   Abbrev = std::make_shared<BitCodeAbbrev>();
2844   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2845   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2846   unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2847 
2848   Abbrev = std::make_shared<BitCodeAbbrev>();
2849   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2850   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2851   unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2852 
2853   Abbrev = std::make_shared<BitCodeAbbrev>();
2854   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2855   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2856   unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2857 
2858   Abbrev = std::make_shared<BitCodeAbbrev>();
2859   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2860   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2861   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Feature
2862   unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2863 
2864   Abbrev = std::make_shared<BitCodeAbbrev>();
2865   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2866   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2867   unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2868 
2869   Abbrev = std::make_shared<BitCodeAbbrev>();
2870   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2871   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2872   unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2873 
2874   Abbrev = std::make_shared<BitCodeAbbrev>();
2875   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2876   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2877   unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2878 
2879   Abbrev = std::make_shared<BitCodeAbbrev>();
2880   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2881   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2882   unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2883 
2884   Abbrev = std::make_shared<BitCodeAbbrev>();
2885   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2886   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2887   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Name
2888   unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2889 
2890   Abbrev = std::make_shared<BitCodeAbbrev>();
2891   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2892   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2893   unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2894 
2895   Abbrev = std::make_shared<BitCodeAbbrev>();
2896   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2897   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));  // Other module
2898   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Message
2899   unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2900 
2901   Abbrev = std::make_shared<BitCodeAbbrev>();
2902   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2903   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2904   unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2905 
2906   // Write the submodule metadata block.
2907   RecordData::value_type Record[] = {
2908       getNumberOfModules(WritingModule),
2909       FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2910   Stream.EmitRecord(SUBMODULE_METADATA, Record);
2911 
2912   // Write all of the submodules.
2913   std::queue<Module *> Q;
2914   Q.push(WritingModule);
2915   while (!Q.empty()) {
2916     Module *Mod = Q.front();
2917     Q.pop();
2918     unsigned ID = getSubmoduleID(Mod);
2919 
2920     uint64_t ParentID = 0;
2921     if (Mod->Parent) {
2922       assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2923       ParentID = SubmoduleIDs[Mod->Parent];
2924     }
2925 
2926     // Emit the definition of the block.
2927     {
2928       RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2929                                          ID,
2930                                          ParentID,
2931                                          (RecordData::value_type)Mod->Kind,
2932                                          Mod->IsFramework,
2933                                          Mod->IsExplicit,
2934                                          Mod->IsSystem,
2935                                          Mod->IsExternC,
2936                                          Mod->InferSubmodules,
2937                                          Mod->InferExplicitSubmodules,
2938                                          Mod->InferExportWildcard,
2939                                          Mod->ConfigMacrosExhaustive,
2940                                          Mod->ModuleMapIsPrivate};
2941       Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2942     }
2943 
2944     // Emit the requirements.
2945     for (const auto &R : Mod->Requirements) {
2946       RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2947       Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2948     }
2949 
2950     // Emit the umbrella header, if there is one.
2951     if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2952       RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2953       Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2954                                 UmbrellaHeader.NameAsWritten);
2955     } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2956       RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2957       Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2958                                 UmbrellaDir.NameAsWritten);
2959     }
2960 
2961     // Emit the headers.
2962     struct {
2963       unsigned RecordKind;
2964       unsigned Abbrev;
2965       Module::HeaderKind HeaderKind;
2966     } HeaderLists[] = {
2967       {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2968       {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2969       {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2970       {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2971         Module::HK_PrivateTextual},
2972       {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2973     };
2974     for (auto &HL : HeaderLists) {
2975       RecordData::value_type Record[] = {HL.RecordKind};
2976       for (auto &H : Mod->Headers[HL.HeaderKind])
2977         Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2978     }
2979 
2980     // Emit the top headers.
2981     {
2982       auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2983       RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2984       for (auto *H : TopHeaders)
2985         Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2986     }
2987 
2988     // Emit the imports.
2989     if (!Mod->Imports.empty()) {
2990       RecordData Record;
2991       for (auto *I : Mod->Imports)
2992         Record.push_back(getSubmoduleID(I));
2993       Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2994     }
2995 
2996     // Emit the exports.
2997     if (!Mod->Exports.empty()) {
2998       RecordData Record;
2999       for (const auto &E : Mod->Exports) {
3000         // FIXME: This may fail; we don't require that all exported modules
3001         // are local or imported.
3002         Record.push_back(getSubmoduleID(E.getPointer()));
3003         Record.push_back(E.getInt());
3004       }
3005       Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
3006     }
3007 
3008     //FIXME: How do we emit the 'use'd modules?  They may not be submodules.
3009     // Might be unnecessary as use declarations are only used to build the
3010     // module itself.
3011 
3012     // Emit the link libraries.
3013     for (const auto &LL : Mod->LinkLibraries) {
3014       RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
3015                                          LL.IsFramework};
3016       Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
3017     }
3018 
3019     // Emit the conflicts.
3020     for (const auto &C : Mod->Conflicts) {
3021       // FIXME: This may fail; we don't require that all conflicting modules
3022       // are local or imported.
3023       RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
3024                                          getSubmoduleID(C.Other)};
3025       Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
3026     }
3027 
3028     // Emit the configuration macros.
3029     for (const auto &CM : Mod->ConfigMacros) {
3030       RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
3031       Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
3032     }
3033 
3034     // Emit the initializers, if any.
3035     RecordData Inits;
3036     for (Decl *D : Context->getModuleInitializers(Mod))
3037       Inits.push_back(GetDeclRef(D));
3038     if (!Inits.empty())
3039       Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
3040 
3041     // Emit the name of the re-exported module, if any.
3042     if (!Mod->ExportAsModule.empty()) {
3043       RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
3044       Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
3045     }
3046 
3047     // Queue up the submodules of this module.
3048     for (auto *M : Mod->submodules())
3049       Q.push(M);
3050   }
3051 
3052   Stream.ExitBlock();
3053 
3054   assert((NextSubmoduleID - FirstSubmoduleID ==
3055           getNumberOfModules(WritingModule)) &&
3056          "Wrong # of submodules; found a reference to a non-local, "
3057          "non-imported submodule?");
3058 }
3059 
3060 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3061                                               bool isModule) {
3062   llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3063       DiagStateIDMap;
3064   unsigned CurrID = 0;
3065   RecordData Record;
3066 
3067   auto EncodeDiagStateFlags =
3068       [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3069     unsigned Result = (unsigned)DS->ExtBehavior;
3070     for (unsigned Val :
3071          {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3072           (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3073           (unsigned)DS->SuppressSystemWarnings})
3074       Result = (Result << 1) | Val;
3075     return Result;
3076   };
3077 
3078   unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3079   Record.push_back(Flags);
3080 
3081   auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3082                           bool IncludeNonPragmaStates) {
3083     // Ensure that the diagnostic state wasn't modified since it was created.
3084     // We will not correctly round-trip this information otherwise.
3085     assert(Flags == EncodeDiagStateFlags(State) &&
3086            "diag state flags vary in single AST file");
3087 
3088     unsigned &DiagStateID = DiagStateIDMap[State];
3089     Record.push_back(DiagStateID);
3090 
3091     if (DiagStateID == 0) {
3092       DiagStateID = ++CurrID;
3093 
3094       // Add a placeholder for the number of mappings.
3095       auto SizeIdx = Record.size();
3096       Record.emplace_back();
3097       for (const auto &I : *State) {
3098         if (I.second.isPragma() || IncludeNonPragmaStates) {
3099           Record.push_back(I.first);
3100           Record.push_back(I.second.serialize());
3101         }
3102       }
3103       // Update the placeholder.
3104       Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
3105     }
3106   };
3107 
3108   AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3109 
3110   // Reserve a spot for the number of locations with state transitions.
3111   auto NumLocationsIdx = Record.size();
3112   Record.emplace_back();
3113 
3114   // Emit the state transitions.
3115   unsigned NumLocations = 0;
3116   for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3117     if (!FileIDAndFile.first.isValid() ||
3118         !FileIDAndFile.second.HasLocalTransitions)
3119       continue;
3120     ++NumLocations;
3121 
3122     SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
3123     assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
3124     AddSourceLocation(Loc, Record);
3125 
3126     Record.push_back(FileIDAndFile.second.StateTransitions.size());
3127     for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3128       Record.push_back(StatePoint.Offset);
3129       AddDiagState(StatePoint.State, false);
3130     }
3131   }
3132 
3133   // Backpatch the number of locations.
3134   Record[NumLocationsIdx] = NumLocations;
3135 
3136   // Emit CurDiagStateLoc.  Do it last in order to match source order.
3137   //
3138   // This also protects against a hypothetical corner case with simulating
3139   // -Werror settings for implicit modules in the ASTReader, where reading
3140   // CurDiagState out of context could change whether warning pragmas are
3141   // treated as errors.
3142   AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3143   AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3144 
3145   Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3146 }
3147 
3148 //===----------------------------------------------------------------------===//
3149 // Type Serialization
3150 //===----------------------------------------------------------------------===//
3151 
3152 /// Write the representation of a type to the AST stream.
3153 void ASTWriter::WriteType(QualType T) {
3154   TypeIdx &IdxRef = TypeIdxs[T];
3155   if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3156     IdxRef = TypeIdx(NextTypeID++);
3157   TypeIdx Idx = IdxRef;
3158 
3159   assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
3160 
3161   RecordData Record;
3162 
3163   // Emit the type's representation.
3164   ASTTypeWriter W(*this, Record);
3165   W.Visit(T);
3166   uint64_t Offset = W.Emit();
3167 
3168   // Record the offset for this type.
3169   unsigned Index = Idx.getIndex() - FirstTypeID;
3170   if (TypeOffsets.size() == Index)
3171     TypeOffsets.push_back(Offset);
3172   else if (TypeOffsets.size() < Index) {
3173     TypeOffsets.resize(Index + 1);
3174     TypeOffsets[Index] = Offset;
3175   } else {
3176     llvm_unreachable("Types emitted in wrong order");
3177   }
3178 }
3179 
3180 //===----------------------------------------------------------------------===//
3181 // Declaration Serialization
3182 //===----------------------------------------------------------------------===//
3183 
3184 /// Write the block containing all of the declaration IDs
3185 /// lexically declared within the given DeclContext.
3186 ///
3187 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3188 /// bitstream, or 0 if no block was written.
3189 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3190                                                  DeclContext *DC) {
3191   if (DC->decls_empty())
3192     return 0;
3193 
3194   uint64_t Offset = Stream.GetCurrentBitNo();
3195   SmallVector<uint32_t, 128> KindDeclPairs;
3196   for (const auto *D : DC->decls()) {
3197     KindDeclPairs.push_back(D->getKind());
3198     KindDeclPairs.push_back(GetDeclRef(D));
3199   }
3200 
3201   ++NumLexicalDeclContexts;
3202   RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3203   Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3204                             bytes(KindDeclPairs));
3205   return Offset;
3206 }
3207 
3208 void ASTWriter::WriteTypeDeclOffsets() {
3209   using namespace llvm;
3210 
3211   // Write the type offsets array
3212   auto Abbrev = std::make_shared<BitCodeAbbrev>();
3213   Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3214   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3215   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3216   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3217   unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3218   {
3219     RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3220                                        FirstTypeID - NUM_PREDEF_TYPE_IDS};
3221     Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3222   }
3223 
3224   // Write the declaration offsets array
3225   Abbrev = std::make_shared<BitCodeAbbrev>();
3226   Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3227   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3228   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3229   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3230   unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3231   {
3232     RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3233                                        FirstDeclID - NUM_PREDEF_DECL_IDS};
3234     Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3235   }
3236 }
3237 
3238 void ASTWriter::WriteFileDeclIDsMap() {
3239   using namespace llvm;
3240 
3241   SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
3242       FileDeclIDs.begin(), FileDeclIDs.end());
3243   llvm::sort(SortedFileDeclIDs, llvm::less_first());
3244 
3245   // Join the vectors of DeclIDs from all files.
3246   SmallVector<DeclID, 256> FileGroupedDeclIDs;
3247   for (auto &FileDeclEntry : SortedFileDeclIDs) {
3248     DeclIDInFileInfo &Info = *FileDeclEntry.second;
3249     Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3250     for (auto &LocDeclEntry : Info.DeclIDs)
3251       FileGroupedDeclIDs.push_back(LocDeclEntry.second);
3252   }
3253 
3254   auto Abbrev = std::make_shared<BitCodeAbbrev>();
3255   Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3256   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3257   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3258   unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3259   RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3260                                      FileGroupedDeclIDs.size()};
3261   Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3262 }
3263 
3264 void ASTWriter::WriteComments() {
3265   Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3266   auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
3267   if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
3268     return;
3269   RecordData Record;
3270   for (const auto &FO : Context->Comments.OrderedComments) {
3271     for (const auto &OC : FO.second) {
3272       const RawComment *I = OC.second;
3273       Record.clear();
3274       AddSourceRange(I->getSourceRange(), Record);
3275       Record.push_back(I->getKind());
3276       Record.push_back(I->isTrailingComment());
3277       Record.push_back(I->isAlmostTrailingComment());
3278       Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3279     }
3280   }
3281 }
3282 
3283 //===----------------------------------------------------------------------===//
3284 // Global Method Pool and Selector Serialization
3285 //===----------------------------------------------------------------------===//
3286 
3287 namespace {
3288 
3289 // Trait used for the on-disk hash table used in the method pool.
3290 class ASTMethodPoolTrait {
3291   ASTWriter &Writer;
3292 
3293 public:
3294   using key_type = Selector;
3295   using key_type_ref = key_type;
3296 
3297   struct data_type {
3298     SelectorID ID;
3299     ObjCMethodList Instance, Factory;
3300   };
3301   using data_type_ref = const data_type &;
3302 
3303   using hash_value_type = unsigned;
3304   using offset_type = unsigned;
3305 
3306   explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3307 
3308   static hash_value_type ComputeHash(Selector Sel) {
3309     return serialization::ComputeHash(Sel);
3310   }
3311 
3312   std::pair<unsigned, unsigned>
3313     EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3314                       data_type_ref Methods) {
3315     using namespace llvm::support;
3316 
3317     endian::Writer LE(Out, little);
3318     unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
3319     LE.write<uint16_t>(KeyLen);
3320     unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3321     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3322          Method = Method->getNext())
3323       if (Method->getMethod())
3324         DataLen += 4;
3325     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3326          Method = Method->getNext())
3327       if (Method->getMethod())
3328         DataLen += 4;
3329     LE.write<uint16_t>(DataLen);
3330     return std::make_pair(KeyLen, DataLen);
3331   }
3332 
3333   void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3334     using namespace llvm::support;
3335 
3336     endian::Writer LE(Out, little);
3337     uint64_t Start = Out.tell();
3338     assert((Start >> 32) == 0 && "Selector key offset too large");
3339     Writer.SetSelectorOffset(Sel, Start);
3340     unsigned N = Sel.getNumArgs();
3341     LE.write<uint16_t>(N);
3342     if (N == 0)
3343       N = 1;
3344     for (unsigned I = 0; I != N; ++I)
3345       LE.write<uint32_t>(
3346           Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3347   }
3348 
3349   void EmitData(raw_ostream& Out, key_type_ref,
3350                 data_type_ref Methods, unsigned DataLen) {
3351     using namespace llvm::support;
3352 
3353     endian::Writer LE(Out, little);
3354     uint64_t Start = Out.tell(); (void)Start;
3355     LE.write<uint32_t>(Methods.ID);
3356     unsigned NumInstanceMethods = 0;
3357     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3358          Method = Method->getNext())
3359       if (Method->getMethod())
3360         ++NumInstanceMethods;
3361 
3362     unsigned NumFactoryMethods = 0;
3363     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3364          Method = Method->getNext())
3365       if (Method->getMethod())
3366         ++NumFactoryMethods;
3367 
3368     unsigned InstanceBits = Methods.Instance.getBits();
3369     assert(InstanceBits < 4);
3370     unsigned InstanceHasMoreThanOneDeclBit =
3371         Methods.Instance.hasMoreThanOneDecl();
3372     unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3373                                 (InstanceHasMoreThanOneDeclBit << 2) |
3374                                 InstanceBits;
3375     unsigned FactoryBits = Methods.Factory.getBits();
3376     assert(FactoryBits < 4);
3377     unsigned FactoryHasMoreThanOneDeclBit =
3378         Methods.Factory.hasMoreThanOneDecl();
3379     unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3380                                (FactoryHasMoreThanOneDeclBit << 2) |
3381                                FactoryBits;
3382     LE.write<uint16_t>(FullInstanceBits);
3383     LE.write<uint16_t>(FullFactoryBits);
3384     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3385          Method = Method->getNext())
3386       if (Method->getMethod())
3387         LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3388     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3389          Method = Method->getNext())
3390       if (Method->getMethod())
3391         LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3392 
3393     assert(Out.tell() - Start == DataLen && "Data length is wrong");
3394   }
3395 };
3396 
3397 } // namespace
3398 
3399 /// Write ObjC data: selectors and the method pool.
3400 ///
3401 /// The method pool contains both instance and factory methods, stored
3402 /// in an on-disk hash table indexed by the selector. The hash table also
3403 /// contains an empty entry for every other selector known to Sema.
3404 void ASTWriter::WriteSelectors(Sema &SemaRef) {
3405   using namespace llvm;
3406 
3407   // Do we have to do anything at all?
3408   if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3409     return;
3410   unsigned NumTableEntries = 0;
3411   // Create and write out the blob that contains selectors and the method pool.
3412   {
3413     llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3414     ASTMethodPoolTrait Trait(*this);
3415 
3416     // Create the on-disk hash table representation. We walk through every
3417     // selector we've seen and look it up in the method pool.
3418     SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3419     for (auto &SelectorAndID : SelectorIDs) {
3420       Selector S = SelectorAndID.first;
3421       SelectorID ID = SelectorAndID.second;
3422       Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3423       ASTMethodPoolTrait::data_type Data = {
3424         ID,
3425         ObjCMethodList(),
3426         ObjCMethodList()
3427       };
3428       if (F != SemaRef.MethodPool.end()) {
3429         Data.Instance = F->second.first;
3430         Data.Factory = F->second.second;
3431       }
3432       // Only write this selector if it's not in an existing AST or something
3433       // changed.
3434       if (Chain && ID < FirstSelectorID) {
3435         // Selector already exists. Did it change?
3436         bool changed = false;
3437         for (ObjCMethodList *M = &Data.Instance;
3438              !changed && M && M->getMethod(); M = M->getNext()) {
3439           if (!M->getMethod()->isFromASTFile())
3440             changed = true;
3441         }
3442         for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
3443              M = M->getNext()) {
3444           if (!M->getMethod()->isFromASTFile())
3445             changed = true;
3446         }
3447         if (!changed)
3448           continue;
3449       } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3450         // A new method pool entry.
3451         ++NumTableEntries;
3452       }
3453       Generator.insert(S, Data, Trait);
3454     }
3455 
3456     // Create the on-disk hash table in a buffer.
3457     SmallString<4096> MethodPool;
3458     uint32_t BucketOffset;
3459     {
3460       using namespace llvm::support;
3461 
3462       ASTMethodPoolTrait Trait(*this);
3463       llvm::raw_svector_ostream Out(MethodPool);
3464       // Make sure that no bucket is at offset 0
3465       endian::write<uint32_t>(Out, 0, little);
3466       BucketOffset = Generator.Emit(Out, Trait);
3467     }
3468 
3469     // Create a blob abbreviation
3470     auto Abbrev = std::make_shared<BitCodeAbbrev>();
3471     Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3472     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3473     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3474     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3475     unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3476 
3477     // Write the method pool
3478     {
3479       RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3480                                          NumTableEntries};
3481       Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3482     }
3483 
3484     // Create a blob abbreviation for the selector table offsets.
3485     Abbrev = std::make_shared<BitCodeAbbrev>();
3486     Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3487     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3488     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3489     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3490     unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3491 
3492     // Write the selector offsets table.
3493     {
3494       RecordData::value_type Record[] = {
3495           SELECTOR_OFFSETS, SelectorOffsets.size(),
3496           FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3497       Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3498                                 bytes(SelectorOffsets));
3499     }
3500   }
3501 }
3502 
3503 /// Write the selectors referenced in @selector expression into AST file.
3504 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3505   using namespace llvm;
3506 
3507   if (SemaRef.ReferencedSelectors.empty())
3508     return;
3509 
3510   RecordData Record;
3511   ASTRecordWriter Writer(*this, Record);
3512 
3513   // Note: this writes out all references even for a dependent AST. But it is
3514   // very tricky to fix, and given that @selector shouldn't really appear in
3515   // headers, probably not worth it. It's not a correctness issue.
3516   for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3517     Selector Sel = SelectorAndLocation.first;
3518     SourceLocation Loc = SelectorAndLocation.second;
3519     Writer.AddSelectorRef(Sel);
3520     Writer.AddSourceLocation(Loc);
3521   }
3522   Writer.Emit(REFERENCED_SELECTOR_POOL);
3523 }
3524 
3525 //===----------------------------------------------------------------------===//
3526 // Identifier Table Serialization
3527 //===----------------------------------------------------------------------===//
3528 
3529 /// Determine the declaration that should be put into the name lookup table to
3530 /// represent the given declaration in this module. This is usually D itself,
3531 /// but if D was imported and merged into a local declaration, we want the most
3532 /// recent local declaration instead. The chosen declaration will be the most
3533 /// recent declaration in any module that imports this one.
3534 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3535                                         NamedDecl *D) {
3536   if (!LangOpts.Modules || !D->isFromASTFile())
3537     return D;
3538 
3539   if (Decl *Redecl = D->getPreviousDecl()) {
3540     // For Redeclarable decls, a prior declaration might be local.
3541     for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3542       // If we find a local decl, we're done.
3543       if (!Redecl->isFromASTFile()) {
3544         // Exception: in very rare cases (for injected-class-names), not all
3545         // redeclarations are in the same semantic context. Skip ones in a
3546         // different context. They don't go in this lookup table at all.
3547         if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3548                 D->getDeclContext()->getRedeclContext()))
3549           continue;
3550         return cast<NamedDecl>(Redecl);
3551       }
3552 
3553       // If we find a decl from a (chained-)PCH stop since we won't find a
3554       // local one.
3555       if (Redecl->getOwningModuleID() == 0)
3556         break;
3557     }
3558   } else if (Decl *First = D->getCanonicalDecl()) {
3559     // For Mergeable decls, the first decl might be local.
3560     if (!First->isFromASTFile())
3561       return cast<NamedDecl>(First);
3562   }
3563 
3564   // All declarations are imported. Our most recent declaration will also be
3565   // the most recent one in anyone who imports us.
3566   return D;
3567 }
3568 
3569 namespace {
3570 
3571 class ASTIdentifierTableTrait {
3572   ASTWriter &Writer;
3573   Preprocessor &PP;
3574   IdentifierResolver &IdResolver;
3575   bool IsModule;
3576   bool NeedDecls;
3577   ASTWriter::RecordData *InterestingIdentifierOffsets;
3578 
3579   /// Determines whether this is an "interesting" identifier that needs a
3580   /// full IdentifierInfo structure written into the hash table. Notably, this
3581   /// doesn't check whether the name has macros defined; use PublicMacroIterator
3582   /// to check that.
3583   bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3584     if (MacroOffset ||
3585         II->isPoisoned() ||
3586         (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
3587         II->hasRevertedTokenIDToIdentifier() ||
3588         (NeedDecls && II->getFETokenInfo()))
3589       return true;
3590 
3591     return false;
3592   }
3593 
3594 public:
3595   using key_type = IdentifierInfo *;
3596   using key_type_ref = key_type;
3597 
3598   using data_type = IdentID;
3599   using data_type_ref = data_type;
3600 
3601   using hash_value_type = unsigned;
3602   using offset_type = unsigned;
3603 
3604   ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3605                           IdentifierResolver &IdResolver, bool IsModule,
3606                           ASTWriter::RecordData *InterestingIdentifierOffsets)
3607       : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3608         NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3609         InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3610 
3611   bool needDecls() const { return NeedDecls; }
3612 
3613   static hash_value_type ComputeHash(const IdentifierInfo* II) {
3614     return llvm::djbHash(II->getName());
3615   }
3616 
3617   bool isInterestingIdentifier(const IdentifierInfo *II) {
3618     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3619     return isInterestingIdentifier(II, MacroOffset);
3620   }
3621 
3622   bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3623     return isInterestingIdentifier(II, 0);
3624   }
3625 
3626   std::pair<unsigned, unsigned>
3627   EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3628     unsigned KeyLen = II->getLength() + 1;
3629     unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3630     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3631     if (isInterestingIdentifier(II, MacroOffset)) {
3632       DataLen += 2; // 2 bytes for builtin ID
3633       DataLen += 2; // 2 bytes for flags
3634       if (MacroOffset)
3635         DataLen += 4; // MacroDirectives offset.
3636 
3637       if (NeedDecls) {
3638         for (IdentifierResolver::iterator D = IdResolver.begin(II),
3639                                        DEnd = IdResolver.end();
3640              D != DEnd; ++D)
3641           DataLen += 4;
3642       }
3643     }
3644 
3645     using namespace llvm::support;
3646 
3647     endian::Writer LE(Out, little);
3648 
3649     assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
3650     LE.write<uint16_t>(DataLen);
3651     // We emit the key length after the data length so that every
3652     // string is preceded by a 16-bit length. This matches the PTH
3653     // format for storing identifiers.
3654     LE.write<uint16_t>(KeyLen);
3655     return std::make_pair(KeyLen, DataLen);
3656   }
3657 
3658   void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3659                unsigned KeyLen) {
3660     // Record the location of the key data.  This is used when generating
3661     // the mapping from persistent IDs to strings.
3662     Writer.SetIdentifierOffset(II, Out.tell());
3663 
3664     // Emit the offset of the key/data length information to the interesting
3665     // identifiers table if necessary.
3666     if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3667       InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3668 
3669     Out.write(II->getNameStart(), KeyLen);
3670   }
3671 
3672   void EmitData(raw_ostream& Out, IdentifierInfo* II,
3673                 IdentID ID, unsigned) {
3674     using namespace llvm::support;
3675 
3676     endian::Writer LE(Out, little);
3677 
3678     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3679     if (!isInterestingIdentifier(II, MacroOffset)) {
3680       LE.write<uint32_t>(ID << 1);
3681       return;
3682     }
3683 
3684     LE.write<uint32_t>((ID << 1) | 0x01);
3685     uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3686     assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3687     LE.write<uint16_t>(Bits);
3688     Bits = 0;
3689     bool HadMacroDefinition = MacroOffset != 0;
3690     Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3691     Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3692     Bits = (Bits << 1) | unsigned(II->isPoisoned());
3693     Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
3694     Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3695     Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3696     LE.write<uint16_t>(Bits);
3697 
3698     if (HadMacroDefinition)
3699       LE.write<uint32_t>(MacroOffset);
3700 
3701     if (NeedDecls) {
3702       // Emit the declaration IDs in reverse order, because the
3703       // IdentifierResolver provides the declarations as they would be
3704       // visible (e.g., the function "stat" would come before the struct
3705       // "stat"), but the ASTReader adds declarations to the end of the list
3706       // (so we need to see the struct "stat" before the function "stat").
3707       // Only emit declarations that aren't from a chained PCH, though.
3708       SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3709                                          IdResolver.end());
3710       for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3711                                                           DEnd = Decls.rend();
3712            D != DEnd; ++D)
3713         LE.write<uint32_t>(
3714             Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3715     }
3716   }
3717 };
3718 
3719 } // namespace
3720 
3721 /// Write the identifier table into the AST file.
3722 ///
3723 /// The identifier table consists of a blob containing string data
3724 /// (the actual identifiers themselves) and a separate "offsets" index
3725 /// that maps identifier IDs to locations within the blob.
3726 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3727                                      IdentifierResolver &IdResolver,
3728                                      bool IsModule) {
3729   using namespace llvm;
3730 
3731   RecordData InterestingIdents;
3732 
3733   // Create and write out the blob that contains the identifier
3734   // strings.
3735   {
3736     llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3737     ASTIdentifierTableTrait Trait(
3738         *this, PP, IdResolver, IsModule,
3739         (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3740 
3741     // Look for any identifiers that were named while processing the
3742     // headers, but are otherwise not needed. We add these to the hash
3743     // table to enable checking of the predefines buffer in the case
3744     // where the user adds new macro definitions when building the AST
3745     // file.
3746     SmallVector<const IdentifierInfo *, 128> IIs;
3747     for (const auto &ID : PP.getIdentifierTable())
3748       IIs.push_back(ID.second);
3749     // Sort the identifiers lexicographically before getting them references so
3750     // that their order is stable.
3751     llvm::sort(IIs, llvm::less_ptr<IdentifierInfo>());
3752     for (const IdentifierInfo *II : IIs)
3753       if (Trait.isInterestingNonMacroIdentifier(II))
3754         getIdentifierRef(II);
3755 
3756     // Create the on-disk hash table representation. We only store offsets
3757     // for identifiers that appear here for the first time.
3758     IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3759     for (auto IdentIDPair : IdentifierIDs) {
3760       auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3761       IdentID ID = IdentIDPair.second;
3762       assert(II && "NULL identifier in identifier table");
3763       // Write out identifiers if either the ID is local or the identifier has
3764       // changed since it was loaded.
3765       if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3766           || II->hasChangedSinceDeserialization() ||
3767           (Trait.needDecls() &&
3768            II->hasFETokenInfoChangedSinceDeserialization()))
3769         Generator.insert(II, ID, Trait);
3770     }
3771 
3772     // Create the on-disk hash table in a buffer.
3773     SmallString<4096> IdentifierTable;
3774     uint32_t BucketOffset;
3775     {
3776       using namespace llvm::support;
3777 
3778       llvm::raw_svector_ostream Out(IdentifierTable);
3779       // Make sure that no bucket is at offset 0
3780       endian::write<uint32_t>(Out, 0, little);
3781       BucketOffset = Generator.Emit(Out, Trait);
3782     }
3783 
3784     // Create a blob abbreviation
3785     auto Abbrev = std::make_shared<BitCodeAbbrev>();
3786     Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3787     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3788     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3789     unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3790 
3791     // Write the identifier table
3792     RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3793     Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3794   }
3795 
3796   // Write the offsets table for identifier IDs.
3797   auto Abbrev = std::make_shared<BitCodeAbbrev>();
3798   Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3799   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3800   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3801   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3802   unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3803 
3804 #ifndef NDEBUG
3805   for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3806     assert(IdentifierOffsets[I] && "Missing identifier offset?");
3807 #endif
3808 
3809   RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3810                                      IdentifierOffsets.size(),
3811                                      FirstIdentID - NUM_PREDEF_IDENT_IDS};
3812   Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3813                             bytes(IdentifierOffsets));
3814 
3815   // In C++, write the list of interesting identifiers (those that are
3816   // defined as macros, poisoned, or similar unusual things).
3817   if (!InterestingIdents.empty())
3818     Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3819 }
3820 
3821 //===----------------------------------------------------------------------===//
3822 // DeclContext's Name Lookup Table Serialization
3823 //===----------------------------------------------------------------------===//
3824 
3825 namespace {
3826 
3827 // Trait used for the on-disk hash table used in the method pool.
3828 class ASTDeclContextNameLookupTrait {
3829   ASTWriter &Writer;
3830   llvm::SmallVector<DeclID, 64> DeclIDs;
3831 
3832 public:
3833   using key_type = DeclarationNameKey;
3834   using key_type_ref = key_type;
3835 
3836   /// A start and end index into DeclIDs, representing a sequence of decls.
3837   using data_type = std::pair<unsigned, unsigned>;
3838   using data_type_ref = const data_type &;
3839 
3840   using hash_value_type = unsigned;
3841   using offset_type = unsigned;
3842 
3843   explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3844 
3845   template<typename Coll>
3846   data_type getData(const Coll &Decls) {
3847     unsigned Start = DeclIDs.size();
3848     for (NamedDecl *D : Decls) {
3849       DeclIDs.push_back(
3850           Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3851     }
3852     return std::make_pair(Start, DeclIDs.size());
3853   }
3854 
3855   data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3856     unsigned Start = DeclIDs.size();
3857     for (auto ID : FromReader)
3858       DeclIDs.push_back(ID);
3859     return std::make_pair(Start, DeclIDs.size());
3860   }
3861 
3862   static bool EqualKey(key_type_ref a, key_type_ref b) {
3863     return a == b;
3864   }
3865 
3866   hash_value_type ComputeHash(DeclarationNameKey Name) {
3867     return Name.getHash();
3868   }
3869 
3870   void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3871     assert(Writer.hasChain() &&
3872            "have reference to loaded module file but no chain?");
3873 
3874     using namespace llvm::support;
3875 
3876     endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
3877   }
3878 
3879   std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3880                                                   DeclarationNameKey Name,
3881                                                   data_type_ref Lookup) {
3882     using namespace llvm::support;
3883 
3884     endian::Writer LE(Out, little);
3885     unsigned KeyLen = 1;
3886     switch (Name.getKind()) {
3887     case DeclarationName::Identifier:
3888     case DeclarationName::ObjCZeroArgSelector:
3889     case DeclarationName::ObjCOneArgSelector:
3890     case DeclarationName::ObjCMultiArgSelector:
3891     case DeclarationName::CXXLiteralOperatorName:
3892     case DeclarationName::CXXDeductionGuideName:
3893       KeyLen += 4;
3894       break;
3895     case DeclarationName::CXXOperatorName:
3896       KeyLen += 1;
3897       break;
3898     case DeclarationName::CXXConstructorName:
3899     case DeclarationName::CXXDestructorName:
3900     case DeclarationName::CXXConversionFunctionName:
3901     case DeclarationName::CXXUsingDirective:
3902       break;
3903     }
3904     LE.write<uint16_t>(KeyLen);
3905 
3906     // 4 bytes for each DeclID.
3907     unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3908     assert(uint16_t(DataLen) == DataLen &&
3909            "too many decls for serialized lookup result");
3910     LE.write<uint16_t>(DataLen);
3911 
3912     return std::make_pair(KeyLen, DataLen);
3913   }
3914 
3915   void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3916     using namespace llvm::support;
3917 
3918     endian::Writer LE(Out, little);
3919     LE.write<uint8_t>(Name.getKind());
3920     switch (Name.getKind()) {
3921     case DeclarationName::Identifier:
3922     case DeclarationName::CXXLiteralOperatorName:
3923     case DeclarationName::CXXDeductionGuideName:
3924       LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3925       return;
3926     case DeclarationName::ObjCZeroArgSelector:
3927     case DeclarationName::ObjCOneArgSelector:
3928     case DeclarationName::ObjCMultiArgSelector:
3929       LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3930       return;
3931     case DeclarationName::CXXOperatorName:
3932       assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3933              "Invalid operator?");
3934       LE.write<uint8_t>(Name.getOperatorKind());
3935       return;
3936     case DeclarationName::CXXConstructorName:
3937     case DeclarationName::CXXDestructorName:
3938     case DeclarationName::CXXConversionFunctionName:
3939     case DeclarationName::CXXUsingDirective:
3940       return;
3941     }
3942 
3943     llvm_unreachable("Invalid name kind?");
3944   }
3945 
3946   void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3947                 unsigned DataLen) {
3948     using namespace llvm::support;
3949 
3950     endian::Writer LE(Out, little);
3951     uint64_t Start = Out.tell(); (void)Start;
3952     for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3953       LE.write<uint32_t>(DeclIDs[I]);
3954     assert(Out.tell() - Start == DataLen && "Data length is wrong");
3955   }
3956 };
3957 
3958 } // namespace
3959 
3960 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3961                                        DeclContext *DC) {
3962   return Result.hasExternalDecls() &&
3963          DC->hasNeedToReconcileExternalVisibleStorage();
3964 }
3965 
3966 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3967                                                DeclContext *DC) {
3968   for (auto *D : Result.getLookupResult())
3969     if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3970       return false;
3971 
3972   return true;
3973 }
3974 
3975 void
3976 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3977                                    llvm::SmallVectorImpl<char> &LookupTable) {
3978   assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3979          !ConstDC->hasLazyExternalLexicalLookups() &&
3980          "must call buildLookups first");
3981 
3982   // FIXME: We need to build the lookups table, which is logically const.
3983   auto *DC = const_cast<DeclContext*>(ConstDC);
3984   assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3985 
3986   // Create the on-disk hash table representation.
3987   MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3988                                 ASTDeclContextNameLookupTrait> Generator;
3989   ASTDeclContextNameLookupTrait Trait(*this);
3990 
3991   // The first step is to collect the declaration names which we need to
3992   // serialize into the name lookup table, and to collect them in a stable
3993   // order.
3994   SmallVector<DeclarationName, 16> Names;
3995 
3996   // We also build up small sets of the constructor and conversion function
3997   // names which are visible.
3998   llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3999 
4000   for (auto &Lookup : *DC->buildLookup()) {
4001     auto &Name = Lookup.first;
4002     auto &Result = Lookup.second;
4003 
4004     // If there are no local declarations in our lookup result, we
4005     // don't need to write an entry for the name at all. If we can't
4006     // write out a lookup set without performing more deserialization,
4007     // just skip this entry.
4008     if (isLookupResultExternal(Result, DC) &&
4009         isLookupResultEntirelyExternal(Result, DC))
4010       continue;
4011 
4012     // We also skip empty results. If any of the results could be external and
4013     // the currently available results are empty, then all of the results are
4014     // external and we skip it above. So the only way we get here with an empty
4015     // results is when no results could have been external *and* we have
4016     // external results.
4017     //
4018     // FIXME: While we might want to start emitting on-disk entries for negative
4019     // lookups into a decl context as an optimization, today we *have* to skip
4020     // them because there are names with empty lookup results in decl contexts
4021     // which we can't emit in any stable ordering: we lookup constructors and
4022     // conversion functions in the enclosing namespace scope creating empty
4023     // results for them. This in almost certainly a bug in Clang's name lookup,
4024     // but that is likely to be hard or impossible to fix and so we tolerate it
4025     // here by omitting lookups with empty results.
4026     if (Lookup.second.getLookupResult().empty())
4027       continue;
4028 
4029     switch (Lookup.first.getNameKind()) {
4030     default:
4031       Names.push_back(Lookup.first);
4032       break;
4033 
4034     case DeclarationName::CXXConstructorName:
4035       assert(isa<CXXRecordDecl>(DC) &&
4036              "Cannot have a constructor name outside of a class!");
4037       ConstructorNameSet.insert(Name);
4038       break;
4039 
4040     case DeclarationName::CXXConversionFunctionName:
4041       assert(isa<CXXRecordDecl>(DC) &&
4042              "Cannot have a conversion function name outside of a class!");
4043       ConversionNameSet.insert(Name);
4044       break;
4045     }
4046   }
4047 
4048   // Sort the names into a stable order.
4049   llvm::sort(Names);
4050 
4051   if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
4052     // We need to establish an ordering of constructor and conversion function
4053     // names, and they don't have an intrinsic ordering.
4054 
4055     // First we try the easy case by forming the current context's constructor
4056     // name and adding that name first. This is a very useful optimization to
4057     // avoid walking the lexical declarations in many cases, and it also
4058     // handles the only case where a constructor name can come from some other
4059     // lexical context -- when that name is an implicit constructor merged from
4060     // another declaration in the redecl chain. Any non-implicit constructor or
4061     // conversion function which doesn't occur in all the lexical contexts
4062     // would be an ODR violation.
4063     auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
4064         Context->getCanonicalType(Context->getRecordType(D)));
4065     if (ConstructorNameSet.erase(ImplicitCtorName))
4066       Names.push_back(ImplicitCtorName);
4067 
4068     // If we still have constructors or conversion functions, we walk all the
4069     // names in the decl and add the constructors and conversion functions
4070     // which are visible in the order they lexically occur within the context.
4071     if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
4072       for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
4073         if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4074           auto Name = ChildND->getDeclName();
4075           switch (Name.getNameKind()) {
4076           default:
4077             continue;
4078 
4079           case DeclarationName::CXXConstructorName:
4080             if (ConstructorNameSet.erase(Name))
4081               Names.push_back(Name);
4082             break;
4083 
4084           case DeclarationName::CXXConversionFunctionName:
4085             if (ConversionNameSet.erase(Name))
4086               Names.push_back(Name);
4087             break;
4088           }
4089 
4090           if (ConstructorNameSet.empty() && ConversionNameSet.empty())
4091             break;
4092         }
4093 
4094     assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
4095                                          "constructors by walking all the "
4096                                          "lexical members of the context.");
4097     assert(ConversionNameSet.empty() && "Failed to find all of the visible "
4098                                         "conversion functions by walking all "
4099                                         "the lexical members of the context.");
4100   }
4101 
4102   // Next we need to do a lookup with each name into this decl context to fully
4103   // populate any results from external sources. We don't actually use the
4104   // results of these lookups because we only want to use the results after all
4105   // results have been loaded and the pointers into them will be stable.
4106   for (auto &Name : Names)
4107     DC->lookup(Name);
4108 
4109   // Now we need to insert the results for each name into the hash table. For
4110   // constructor names and conversion function names, we actually need to merge
4111   // all of the results for them into one list of results each and insert
4112   // those.
4113   SmallVector<NamedDecl *, 8> ConstructorDecls;
4114   SmallVector<NamedDecl *, 8> ConversionDecls;
4115 
4116   // Now loop over the names, either inserting them or appending for the two
4117   // special cases.
4118   for (auto &Name : Names) {
4119     DeclContext::lookup_result Result = DC->noload_lookup(Name);
4120 
4121     switch (Name.getNameKind()) {
4122     default:
4123       Generator.insert(Name, Trait.getData(Result), Trait);
4124       break;
4125 
4126     case DeclarationName::CXXConstructorName:
4127       ConstructorDecls.append(Result.begin(), Result.end());
4128       break;
4129 
4130     case DeclarationName::CXXConversionFunctionName:
4131       ConversionDecls.append(Result.begin(), Result.end());
4132       break;
4133     }
4134   }
4135 
4136   // Handle our two special cases if we ended up having any. We arbitrarily use
4137   // the first declaration's name here because the name itself isn't part of
4138   // the key, only the kind of name is used.
4139   if (!ConstructorDecls.empty())
4140     Generator.insert(ConstructorDecls.front()->getDeclName(),
4141                      Trait.getData(ConstructorDecls), Trait);
4142   if (!ConversionDecls.empty())
4143     Generator.insert(ConversionDecls.front()->getDeclName(),
4144                      Trait.getData(ConversionDecls), Trait);
4145 
4146   // Create the on-disk hash table. Also emit the existing imported and
4147   // merged table if there is one.
4148   auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4149   Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4150 }
4151 
4152 /// Write the block containing all of the declaration IDs
4153 /// visible from the given DeclContext.
4154 ///
4155 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4156 /// bitstream, or 0 if no block was written.
4157 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4158                                                  DeclContext *DC) {
4159   // If we imported a key declaration of this namespace, write the visible
4160   // lookup results as an update record for it rather than including them
4161   // on this declaration. We will only look at key declarations on reload.
4162   if (isa<NamespaceDecl>(DC) && Chain &&
4163       Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4164     // Only do this once, for the first local declaration of the namespace.
4165     for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4166          Prev = Prev->getPreviousDecl())
4167       if (!Prev->isFromASTFile())
4168         return 0;
4169 
4170     // Note that we need to emit an update record for the primary context.
4171     UpdatedDeclContexts.insert(DC->getPrimaryContext());
4172 
4173     // Make sure all visible decls are written. They will be recorded later. We
4174     // do this using a side data structure so we can sort the names into
4175     // a deterministic order.
4176     StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4177     SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4178         LookupResults;
4179     if (Map) {
4180       LookupResults.reserve(Map->size());
4181       for (auto &Entry : *Map)
4182         LookupResults.push_back(
4183             std::make_pair(Entry.first, Entry.second.getLookupResult()));
4184     }
4185 
4186     llvm::sort(LookupResults, llvm::less_first());
4187     for (auto &NameAndResult : LookupResults) {
4188       DeclarationName Name = NameAndResult.first;
4189       DeclContext::lookup_result Result = NameAndResult.second;
4190       if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4191           Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4192         // We have to work around a name lookup bug here where negative lookup
4193         // results for these names get cached in namespace lookup tables (these
4194         // names should never be looked up in a namespace).
4195         assert(Result.empty() && "Cannot have a constructor or conversion "
4196                                  "function name in a namespace!");
4197         continue;
4198       }
4199 
4200       for (NamedDecl *ND : Result)
4201         if (!ND->isFromASTFile())
4202           GetDeclRef(ND);
4203     }
4204 
4205     return 0;
4206   }
4207 
4208   if (DC->getPrimaryContext() != DC)
4209     return 0;
4210 
4211   // Skip contexts which don't support name lookup.
4212   if (!DC->isLookupContext())
4213     return 0;
4214 
4215   // If not in C++, we perform name lookup for the translation unit via the
4216   // IdentifierInfo chains, don't bother to build a visible-declarations table.
4217   if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4218     return 0;
4219 
4220   // Serialize the contents of the mapping used for lookup. Note that,
4221   // although we have two very different code paths, the serialized
4222   // representation is the same for both cases: a declaration name,
4223   // followed by a size, followed by references to the visible
4224   // declarations that have that name.
4225   uint64_t Offset = Stream.GetCurrentBitNo();
4226   StoredDeclsMap *Map = DC->buildLookup();
4227   if (!Map || Map->empty())
4228     return 0;
4229 
4230   // Create the on-disk hash table in a buffer.
4231   SmallString<4096> LookupTable;
4232   GenerateNameLookupTable(DC, LookupTable);
4233 
4234   // Write the lookup table
4235   RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4236   Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4237                             LookupTable);
4238   ++NumVisibleDeclContexts;
4239   return Offset;
4240 }
4241 
4242 /// Write an UPDATE_VISIBLE block for the given context.
4243 ///
4244 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4245 /// DeclContext in a dependent AST file. As such, they only exist for the TU
4246 /// (in C++), for namespaces, and for classes with forward-declared unscoped
4247 /// enumeration members (in C++11).
4248 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4249   StoredDeclsMap *Map = DC->getLookupPtr();
4250   if (!Map || Map->empty())
4251     return;
4252 
4253   // Create the on-disk hash table in a buffer.
4254   SmallString<4096> LookupTable;
4255   GenerateNameLookupTable(DC, LookupTable);
4256 
4257   // If we're updating a namespace, select a key declaration as the key for the
4258   // update record; those are the only ones that will be checked on reload.
4259   if (isa<NamespaceDecl>(DC))
4260     DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4261 
4262   // Write the lookup table
4263   RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
4264   Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4265 }
4266 
4267 /// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4268 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
4269   RecordData::value_type Record[] = {Opts.getInt()};
4270   Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4271 }
4272 
4273 /// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4274 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4275   if (!SemaRef.Context.getLangOpts().OpenCL)
4276     return;
4277 
4278   const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4279   RecordData Record;
4280   for (const auto &I:Opts.OptMap) {
4281     AddString(I.getKey(), Record);
4282     auto V = I.getValue();
4283     Record.push_back(V.Supported ? 1 : 0);
4284     Record.push_back(V.Enabled ? 1 : 0);
4285     Record.push_back(V.Avail);
4286     Record.push_back(V.Core);
4287   }
4288   Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4289 }
4290 
4291 void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
4292   if (!SemaRef.Context.getLangOpts().OpenCL)
4293     return;
4294 
4295   // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
4296   // without copying them.
4297   const llvm::DenseMap<const Type *, std::set<std::string>> &OpenCLTypeExtMap =
4298       SemaRef.OpenCLTypeExtMap;
4299   using ElementTy = std::pair<TypeID, const std::set<std::string> *>;
4300   llvm::SmallVector<ElementTy, 8> StableOpenCLTypeExtMap;
4301   StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
4302 
4303   for (const auto &I : OpenCLTypeExtMap)
4304     StableOpenCLTypeExtMap.emplace_back(
4305         getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
4306 
4307   auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
4308     return E1.first < E2.first;
4309   };
4310   llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
4311 
4312   RecordData Record;
4313   for (const ElementTy &E : StableOpenCLTypeExtMap) {
4314     Record.push_back(E.first); // TypeID
4315     const std::set<std::string> *ExtSet = E.second;
4316     Record.push_back(static_cast<unsigned>(ExtSet->size()));
4317     for (const std::string &Ext : *ExtSet)
4318       AddString(Ext, Record);
4319   }
4320 
4321   Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
4322 }
4323 
4324 void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
4325   if (!SemaRef.Context.getLangOpts().OpenCL)
4326     return;
4327 
4328   // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
4329   // without copying them.
4330   const llvm::DenseMap<const Decl *, std::set<std::string>> &OpenCLDeclExtMap =
4331       SemaRef.OpenCLDeclExtMap;
4332   using ElementTy = std::pair<DeclID, const std::set<std::string> *>;
4333   llvm::SmallVector<ElementTy, 8> StableOpenCLDeclExtMap;
4334   StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
4335 
4336   for (const auto &I : OpenCLDeclExtMap)
4337     StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
4338 
4339   auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
4340     return E1.first < E2.first;
4341   };
4342   llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
4343 
4344   RecordData Record;
4345   for (const ElementTy &E : StableOpenCLDeclExtMap) {
4346     Record.push_back(E.first); // DeclID
4347     const std::set<std::string> *ExtSet = E.second;
4348     Record.push_back(static_cast<unsigned>(ExtSet->size()));
4349     for (const std::string &Ext : *ExtSet)
4350       AddString(Ext, Record);
4351   }
4352 
4353   Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
4354 }
4355 
4356 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4357   if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4358     RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4359     Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4360   }
4361 }
4362 
4363 void ASTWriter::WriteObjCCategories() {
4364   SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4365   RecordData Categories;
4366 
4367   for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4368     unsigned Size = 0;
4369     unsigned StartIndex = Categories.size();
4370 
4371     ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4372 
4373     // Allocate space for the size.
4374     Categories.push_back(0);
4375 
4376     // Add the categories.
4377     for (ObjCInterfaceDecl::known_categories_iterator
4378            Cat = Class->known_categories_begin(),
4379            CatEnd = Class->known_categories_end();
4380          Cat != CatEnd; ++Cat, ++Size) {
4381       assert(getDeclID(*Cat) != 0 && "Bogus category");
4382       AddDeclRef(*Cat, Categories);
4383     }
4384 
4385     // Update the size.
4386     Categories[StartIndex] = Size;
4387 
4388     // Record this interface -> category map.
4389     ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4390     CategoriesMap.push_back(CatInfo);
4391   }
4392 
4393   // Sort the categories map by the definition ID, since the reader will be
4394   // performing binary searches on this information.
4395   llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4396 
4397   // Emit the categories map.
4398   using namespace llvm;
4399 
4400   auto Abbrev = std::make_shared<BitCodeAbbrev>();
4401   Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4402   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4403   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4404   unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4405 
4406   RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4407   Stream.EmitRecordWithBlob(AbbrevID, Record,
4408                             reinterpret_cast<char *>(CategoriesMap.data()),
4409                             CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4410 
4411   // Emit the category lists.
4412   Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4413 }
4414 
4415 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4416   Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4417 
4418   if (LPTMap.empty())
4419     return;
4420 
4421   RecordData Record;
4422   for (auto &LPTMapEntry : LPTMap) {
4423     const FunctionDecl *FD = LPTMapEntry.first;
4424     LateParsedTemplate &LPT = *LPTMapEntry.second;
4425     AddDeclRef(FD, Record);
4426     AddDeclRef(LPT.D, Record);
4427     Record.push_back(LPT.Toks.size());
4428 
4429     for (const auto &Tok : LPT.Toks) {
4430       AddToken(Tok, Record);
4431     }
4432   }
4433   Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4434 }
4435 
4436 /// Write the state of 'pragma clang optimize' at the end of the module.
4437 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4438   RecordData Record;
4439   SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4440   AddSourceLocation(PragmaLoc, Record);
4441   Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4442 }
4443 
4444 /// Write the state of 'pragma ms_struct' at the end of the module.
4445 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4446   RecordData Record;
4447   Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4448   Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4449 }
4450 
4451 /// Write the state of 'pragma pointers_to_members' at the end of the
4452 //module.
4453 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4454   RecordData Record;
4455   Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4456   AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4457   Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4458 }
4459 
4460 /// Write the state of 'pragma pack' at the end of the module.
4461 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4462   // Don't serialize pragma pack state for modules, since it should only take
4463   // effect on a per-submodule basis.
4464   if (WritingModule)
4465     return;
4466 
4467   RecordData Record;
4468   Record.push_back(SemaRef.PackStack.CurrentValue);
4469   AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4470   Record.push_back(SemaRef.PackStack.Stack.size());
4471   for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4472     Record.push_back(StackEntry.Value);
4473     AddSourceLocation(StackEntry.PragmaLocation, Record);
4474     AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4475     AddString(StackEntry.StackSlotLabel, Record);
4476   }
4477   Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4478 }
4479 
4480 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4481                                          ModuleFileExtensionWriter &Writer) {
4482   // Enter the extension block.
4483   Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4484 
4485   // Emit the metadata record abbreviation.
4486   auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4487   Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4488   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4489   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4490   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4491   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4492   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4493   unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4494 
4495   // Emit the metadata record.
4496   RecordData Record;
4497   auto Metadata = Writer.getExtension()->getExtensionMetadata();
4498   Record.push_back(EXTENSION_METADATA);
4499   Record.push_back(Metadata.MajorVersion);
4500   Record.push_back(Metadata.MinorVersion);
4501   Record.push_back(Metadata.BlockName.size());
4502   Record.push_back(Metadata.UserInfo.size());
4503   SmallString<64> Buffer;
4504   Buffer += Metadata.BlockName;
4505   Buffer += Metadata.UserInfo;
4506   Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4507 
4508   // Emit the contents of the extension block.
4509   Writer.writeExtensionContents(SemaRef, Stream);
4510 
4511   // Exit the extension block.
4512   Stream.ExitBlock();
4513 }
4514 
4515 //===----------------------------------------------------------------------===//
4516 // General Serialization Routines
4517 //===----------------------------------------------------------------------===//
4518 
4519 void ASTRecordWriter::AddAttr(const Attr *A) {
4520   auto &Record = *this;
4521   if (!A)
4522     return Record.push_back(0);
4523   Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4524   Record.AddSourceRange(A->getRange());
4525 
4526 #include "clang/Serialization/AttrPCHWrite.inc"
4527 }
4528 
4529 /// Emit the list of attributes to the specified record.
4530 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4531   push_back(Attrs.size());
4532   for (const auto *A : Attrs)
4533     AddAttr(A);
4534 }
4535 
4536 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4537   AddSourceLocation(Tok.getLocation(), Record);
4538   Record.push_back(Tok.getLength());
4539 
4540   // FIXME: When reading literal tokens, reconstruct the literal pointer
4541   // if it is needed.
4542   AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4543   // FIXME: Should translate token kind to a stable encoding.
4544   Record.push_back(Tok.getKind());
4545   // FIXME: Should translate token flags to a stable encoding.
4546   Record.push_back(Tok.getFlags());
4547 }
4548 
4549 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4550   Record.push_back(Str.size());
4551   Record.insert(Record.end(), Str.begin(), Str.end());
4552 }
4553 
4554 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4555   assert(Context && "should have context when outputting path");
4556 
4557   bool Changed =
4558       cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4559 
4560   // Remove a prefix to make the path relative, if relevant.
4561   const char *PathBegin = Path.data();
4562   const char *PathPtr =
4563       adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4564   if (PathPtr != PathBegin) {
4565     Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4566     Changed = true;
4567   }
4568 
4569   return Changed;
4570 }
4571 
4572 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4573   SmallString<128> FilePath(Path);
4574   PreparePathForOutput(FilePath);
4575   AddString(FilePath, Record);
4576 }
4577 
4578 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4579                                    StringRef Path) {
4580   SmallString<128> FilePath(Path);
4581   PreparePathForOutput(FilePath);
4582   Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4583 }
4584 
4585 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4586                                 RecordDataImpl &Record) {
4587   Record.push_back(Version.getMajor());
4588   if (Optional<unsigned> Minor = Version.getMinor())
4589     Record.push_back(*Minor + 1);
4590   else
4591     Record.push_back(0);
4592   if (Optional<unsigned> Subminor = Version.getSubminor())
4593     Record.push_back(*Subminor + 1);
4594   else
4595     Record.push_back(0);
4596 }
4597 
4598 /// Note that the identifier II occurs at the given offset
4599 /// within the identifier table.
4600 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4601   IdentID ID = IdentifierIDs[II];
4602   // Only store offsets new to this AST file. Other identifier names are looked
4603   // up earlier in the chain and thus don't need an offset.
4604   if (ID >= FirstIdentID)
4605     IdentifierOffsets[ID - FirstIdentID] = Offset;
4606 }
4607 
4608 /// Note that the selector Sel occurs at the given offset
4609 /// within the method pool/selector table.
4610 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4611   unsigned ID = SelectorIDs[Sel];
4612   assert(ID && "Unknown selector");
4613   // Don't record offsets for selectors that are also available in a different
4614   // file.
4615   if (ID < FirstSelectorID)
4616     return;
4617   SelectorOffsets[ID - FirstSelectorID] = Offset;
4618 }
4619 
4620 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4621                      SmallVectorImpl<char> &Buffer,
4622                      InMemoryModuleCache &ModuleCache,
4623                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4624                      bool IncludeTimestamps)
4625     : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
4626       IncludeTimestamps(IncludeTimestamps) {
4627   for (const auto &Ext : Extensions) {
4628     if (auto Writer = Ext->createExtensionWriter(*this))
4629       ModuleFileExtensionWriters.push_back(std::move(Writer));
4630   }
4631 }
4632 
4633 ASTWriter::~ASTWriter() {
4634   llvm::DeleteContainerSeconds(FileDeclIDs);
4635 }
4636 
4637 const LangOptions &ASTWriter::getLangOpts() const {
4638   assert(WritingAST && "can't determine lang opts when not writing AST");
4639   return Context->getLangOpts();
4640 }
4641 
4642 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4643   return IncludeTimestamps ? E->getModificationTime() : 0;
4644 }
4645 
4646 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4647                                      const std::string &OutputFile,
4648                                      Module *WritingModule, StringRef isysroot,
4649                                      bool hasErrors,
4650                                      bool ShouldCacheASTInMemory) {
4651   WritingAST = true;
4652 
4653   ASTHasCompilerErrors = hasErrors;
4654 
4655   // Emit the file header.
4656   Stream.Emit((unsigned)'C', 8);
4657   Stream.Emit((unsigned)'P', 8);
4658   Stream.Emit((unsigned)'C', 8);
4659   Stream.Emit((unsigned)'H', 8);
4660 
4661   WriteBlockInfoBlock();
4662 
4663   Context = &SemaRef.Context;
4664   PP = &SemaRef.PP;
4665   this->WritingModule = WritingModule;
4666   ASTFileSignature Signature =
4667       WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4668   Context = nullptr;
4669   PP = nullptr;
4670   this->WritingModule = nullptr;
4671   this->BaseDirectory.clear();
4672 
4673   WritingAST = false;
4674   if (ShouldCacheASTInMemory) {
4675     // Construct MemoryBuffer and update buffer manager.
4676     ModuleCache.addBuiltPCM(OutputFile,
4677                             llvm::MemoryBuffer::getMemBufferCopy(
4678                                 StringRef(Buffer.begin(), Buffer.size())));
4679   }
4680   return Signature;
4681 }
4682 
4683 template<typename Vector>
4684 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4685                                ASTWriter::RecordData &Record) {
4686   for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4687        I != E; ++I) {
4688     Writer.AddDeclRef(*I, Record);
4689   }
4690 }
4691 
4692 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4693                                          const std::string &OutputFile,
4694                                          Module *WritingModule) {
4695   using namespace llvm;
4696 
4697   bool isModule = WritingModule != nullptr;
4698 
4699   // Make sure that the AST reader knows to finalize itself.
4700   if (Chain)
4701     Chain->finalizeForWriting();
4702 
4703   ASTContext &Context = SemaRef.Context;
4704   Preprocessor &PP = SemaRef.PP;
4705 
4706   // Set up predefined declaration IDs.
4707   auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4708     if (D) {
4709       assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4710       DeclIDs[D] = ID;
4711     }
4712   };
4713   RegisterPredefDecl(Context.getTranslationUnitDecl(),
4714                      PREDEF_DECL_TRANSLATION_UNIT_ID);
4715   RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4716   RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4717   RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4718   RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4719                      PREDEF_DECL_OBJC_PROTOCOL_ID);
4720   RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4721   RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4722   RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4723                      PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4724   RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4725   RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4726   RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4727                      PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4728   RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4729   RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4730                      PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4731   RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4732                      PREDEF_DECL_CF_CONSTANT_STRING_ID);
4733   RegisterPredefDecl(Context.CFConstantStringTagDecl,
4734                      PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4735   RegisterPredefDecl(Context.TypePackElementDecl,
4736                      PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4737 
4738   // Build a record containing all of the tentative definitions in this file, in
4739   // TentativeDefinitions order.  Generally, this record will be empty for
4740   // headers.
4741   RecordData TentativeDefinitions;
4742   AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4743 
4744   // Build a record containing all of the file scoped decls in this file.
4745   RecordData UnusedFileScopedDecls;
4746   if (!isModule)
4747     AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4748                        UnusedFileScopedDecls);
4749 
4750   // Build a record containing all of the delegating constructors we still need
4751   // to resolve.
4752   RecordData DelegatingCtorDecls;
4753   if (!isModule)
4754     AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4755 
4756   // Write the set of weak, undeclared identifiers. We always write the
4757   // entire table, since later PCH files in a PCH chain are only interested in
4758   // the results at the end of the chain.
4759   RecordData WeakUndeclaredIdentifiers;
4760   for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4761     IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4762     WeakInfo &WI = WeakUndeclaredIdentifier.second;
4763     AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4764     AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4765     AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4766     WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4767   }
4768 
4769   // Build a record containing all of the ext_vector declarations.
4770   RecordData ExtVectorDecls;
4771   AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4772 
4773   // Build a record containing all of the VTable uses information.
4774   RecordData VTableUses;
4775   if (!SemaRef.VTableUses.empty()) {
4776     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4777       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4778       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4779       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4780     }
4781   }
4782 
4783   // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4784   RecordData UnusedLocalTypedefNameCandidates;
4785   for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4786     AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4787 
4788   // Build a record containing all of pending implicit instantiations.
4789   RecordData PendingInstantiations;
4790   for (const auto &I : SemaRef.PendingInstantiations) {
4791     AddDeclRef(I.first, PendingInstantiations);
4792     AddSourceLocation(I.second, PendingInstantiations);
4793   }
4794   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4795          "There are local ones at end of translation unit!");
4796 
4797   // Build a record containing some declaration references.
4798   RecordData SemaDeclRefs;
4799   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4800     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4801     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4802     AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4803   }
4804 
4805   RecordData CUDASpecialDeclRefs;
4806   if (Context.getcudaConfigureCallDecl()) {
4807     AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4808   }
4809 
4810   // Build a record containing all of the known namespaces.
4811   RecordData KnownNamespaces;
4812   for (const auto &I : SemaRef.KnownNamespaces) {
4813     if (!I.second)
4814       AddDeclRef(I.first, KnownNamespaces);
4815   }
4816 
4817   // Build a record of all used, undefined objects that require definitions.
4818   RecordData UndefinedButUsed;
4819 
4820   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4821   SemaRef.getUndefinedButUsed(Undefined);
4822   for (const auto &I : Undefined) {
4823     AddDeclRef(I.first, UndefinedButUsed);
4824     AddSourceLocation(I.second, UndefinedButUsed);
4825   }
4826 
4827   // Build a record containing all delete-expressions that we would like to
4828   // analyze later in AST.
4829   RecordData DeleteExprsToAnalyze;
4830 
4831   if (!isModule) {
4832     for (const auto &DeleteExprsInfo :
4833          SemaRef.getMismatchingDeleteExpressions()) {
4834       AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4835       DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4836       for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4837         AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4838         DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4839       }
4840     }
4841   }
4842 
4843   // Write the control block
4844   WriteControlBlock(PP, Context, isysroot, OutputFile);
4845 
4846   // Write the remaining AST contents.
4847   Stream.EnterSubblock(AST_BLOCK_ID, 5);
4848 
4849   // This is so that older clang versions, before the introduction
4850   // of the control block, can read and reject the newer PCH format.
4851   {
4852     RecordData Record = {VERSION_MAJOR};
4853     Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4854   }
4855 
4856   // Create a lexical update block containing all of the declarations in the
4857   // translation unit that do not come from other AST files.
4858   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4859   SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4860   for (const auto *D : TU->noload_decls()) {
4861     if (!D->isFromASTFile()) {
4862       NewGlobalKindDeclPairs.push_back(D->getKind());
4863       NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4864     }
4865   }
4866 
4867   auto Abv = std::make_shared<BitCodeAbbrev>();
4868   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4869   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4870   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4871   {
4872     RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4873     Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4874                               bytes(NewGlobalKindDeclPairs));
4875   }
4876 
4877   // And a visible updates block for the translation unit.
4878   Abv = std::make_shared<BitCodeAbbrev>();
4879   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4880   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4881   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4882   UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4883   WriteDeclContextVisibleUpdate(TU);
4884 
4885   // If we have any extern "C" names, write out a visible update for them.
4886   if (Context.ExternCContext)
4887     WriteDeclContextVisibleUpdate(Context.ExternCContext);
4888 
4889   // If the translation unit has an anonymous namespace, and we don't already
4890   // have an update block for it, write it as an update block.
4891   // FIXME: Why do we not do this if there's already an update block?
4892   if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4893     ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4894     if (Record.empty())
4895       Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4896   }
4897 
4898   // Add update records for all mangling numbers and static local numbers.
4899   // These aren't really update records, but this is a convenient way of
4900   // tagging this rare extra data onto the declarations.
4901   for (const auto &Number : Context.MangleNumbers)
4902     if (!Number.first->isFromASTFile())
4903       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4904                                                      Number.second));
4905   for (const auto &Number : Context.StaticLocalNumbers)
4906     if (!Number.first->isFromASTFile())
4907       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4908                                                      Number.second));
4909 
4910   // Make sure visible decls, added to DeclContexts previously loaded from
4911   // an AST file, are registered for serialization. Likewise for template
4912   // specializations added to imported templates.
4913   for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4914     GetDeclRef(I);
4915   }
4916 
4917   // Make sure all decls associated with an identifier are registered for
4918   // serialization, if we're storing decls with identifiers.
4919   if (!WritingModule || !getLangOpts().CPlusPlus) {
4920     llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4921     for (const auto &ID : PP.getIdentifierTable()) {
4922       const IdentifierInfo *II = ID.second;
4923       if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4924         IIs.push_back(II);
4925     }
4926     // Sort the identifiers to visit based on their name.
4927     llvm::sort(IIs, llvm::less_ptr<IdentifierInfo>());
4928     for (const IdentifierInfo *II : IIs) {
4929       for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4930                                      DEnd = SemaRef.IdResolver.end();
4931            D != DEnd; ++D) {
4932         GetDeclRef(*D);
4933       }
4934     }
4935   }
4936 
4937   // For method pool in the module, if it contains an entry for a selector,
4938   // the entry should be complete, containing everything introduced by that
4939   // module and all modules it imports. It's possible that the entry is out of
4940   // date, so we need to pull in the new content here.
4941 
4942   // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4943   // safe, we copy all selectors out.
4944   llvm::SmallVector<Selector, 256> AllSelectors;
4945   for (auto &SelectorAndID : SelectorIDs)
4946     AllSelectors.push_back(SelectorAndID.first);
4947   for (auto &Selector : AllSelectors)
4948     SemaRef.updateOutOfDateSelector(Selector);
4949 
4950   // Form the record of special types.
4951   RecordData SpecialTypes;
4952   AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4953   AddTypeRef(Context.getFILEType(), SpecialTypes);
4954   AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4955   AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4956   AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4957   AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4958   AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4959   AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4960 
4961   if (Chain) {
4962     // Write the mapping information describing our module dependencies and how
4963     // each of those modules were mapped into our own offset/ID space, so that
4964     // the reader can build the appropriate mapping to its own offset/ID space.
4965     // The map consists solely of a blob with the following format:
4966     // *(module-kind:i8
4967     //   module-name-len:i16 module-name:len*i8
4968     //   source-location-offset:i32
4969     //   identifier-id:i32
4970     //   preprocessed-entity-id:i32
4971     //   macro-definition-id:i32
4972     //   submodule-id:i32
4973     //   selector-id:i32
4974     //   declaration-id:i32
4975     //   c++-base-specifiers-id:i32
4976     //   type-id:i32)
4977     //
4978     // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4979     // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4980     // it is the module file name.
4981     auto Abbrev = std::make_shared<BitCodeAbbrev>();
4982     Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4983     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4984     unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4985     SmallString<2048> Buffer;
4986     {
4987       llvm::raw_svector_ostream Out(Buffer);
4988       for (ModuleFile &M : Chain->ModuleMgr) {
4989         using namespace llvm::support;
4990 
4991         endian::Writer LE(Out, little);
4992         LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4993         StringRef Name =
4994           M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
4995           ? M.ModuleName
4996           : M.FileName;
4997         LE.write<uint16_t>(Name.size());
4998         Out.write(Name.data(), Name.size());
4999 
5000         // Note: if a base ID was uint max, it would not be possible to load
5001         // another module after it or have more than one entity inside it.
5002         uint32_t None = std::numeric_limits<uint32_t>::max();
5003 
5004         auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
5005           assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
5006           if (ShouldWrite)
5007             LE.write<uint32_t>(BaseID);
5008           else
5009             LE.write<uint32_t>(None);
5010         };
5011 
5012         // These values should be unique within a chain, since they will be read
5013         // as keys into ContinuousRangeMaps.
5014         writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
5015         writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
5016         writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
5017         writeBaseIDOrNone(M.BasePreprocessedEntityID,
5018                           M.NumPreprocessedEntities);
5019         writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
5020         writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
5021         writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
5022         writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
5023       }
5024     }
5025     RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
5026     Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
5027                               Buffer.data(), Buffer.size());
5028   }
5029 
5030   RecordData DeclUpdatesOffsetsRecord;
5031 
5032   // Keep writing types, declarations, and declaration update records
5033   // until we've emitted all of them.
5034   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
5035   WriteTypeAbbrevs();
5036   WriteDeclAbbrevs();
5037   do {
5038     WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
5039     while (!DeclTypesToEmit.empty()) {
5040       DeclOrType DOT = DeclTypesToEmit.front();
5041       DeclTypesToEmit.pop();
5042       if (DOT.isType())
5043         WriteType(DOT.getType());
5044       else
5045         WriteDecl(Context, DOT.getDecl());
5046     }
5047   } while (!DeclUpdates.empty());
5048   Stream.ExitBlock();
5049 
5050   DoneWritingDeclsAndTypes = true;
5051 
5052   // These things can only be done once we've written out decls and types.
5053   WriteTypeDeclOffsets();
5054   if (!DeclUpdatesOffsetsRecord.empty())
5055     Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
5056   WriteFileDeclIDsMap();
5057   WriteSourceManagerBlock(Context.getSourceManager(), PP);
5058   WriteComments();
5059   WritePreprocessor(PP, isModule);
5060   WriteHeaderSearch(PP.getHeaderSearchInfo());
5061   WriteSelectors(SemaRef);
5062   WriteReferencedSelectorsPool(SemaRef);
5063   WriteLateParsedTemplates(SemaRef);
5064   WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
5065   WriteFPPragmaOptions(SemaRef.getFPOptions());
5066   WriteOpenCLExtensions(SemaRef);
5067   WriteOpenCLExtensionTypes(SemaRef);
5068   WriteCUDAPragmas(SemaRef);
5069 
5070   // If we're emitting a module, write out the submodule information.
5071   if (WritingModule)
5072     WriteSubmodules(WritingModule);
5073 
5074   // We need to have information about submodules to correctly deserialize
5075   // decls from OpenCLExtensionDecls block
5076   WriteOpenCLExtensionDecls(SemaRef);
5077 
5078   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
5079 
5080   // Write the record containing external, unnamed definitions.
5081   if (!EagerlyDeserializedDecls.empty())
5082     Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
5083 
5084   if (!ModularCodegenDecls.empty())
5085     Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
5086 
5087   // Write the record containing tentative definitions.
5088   if (!TentativeDefinitions.empty())
5089     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
5090 
5091   // Write the record containing unused file scoped decls.
5092   if (!UnusedFileScopedDecls.empty())
5093     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
5094 
5095   // Write the record containing weak undeclared identifiers.
5096   if (!WeakUndeclaredIdentifiers.empty())
5097     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
5098                       WeakUndeclaredIdentifiers);
5099 
5100   // Write the record containing ext_vector type names.
5101   if (!ExtVectorDecls.empty())
5102     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
5103 
5104   // Write the record containing VTable uses information.
5105   if (!VTableUses.empty())
5106     Stream.EmitRecord(VTABLE_USES, VTableUses);
5107 
5108   // Write the record containing potentially unused local typedefs.
5109   if (!UnusedLocalTypedefNameCandidates.empty())
5110     Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
5111                       UnusedLocalTypedefNameCandidates);
5112 
5113   // Write the record containing pending implicit instantiations.
5114   if (!PendingInstantiations.empty())
5115     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
5116 
5117   // Write the record containing declaration references of Sema.
5118   if (!SemaDeclRefs.empty())
5119     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
5120 
5121   // Write the record containing CUDA-specific declaration references.
5122   if (!CUDASpecialDeclRefs.empty())
5123     Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
5124 
5125   // Write the delegating constructors.
5126   if (!DelegatingCtorDecls.empty())
5127     Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
5128 
5129   // Write the known namespaces.
5130   if (!KnownNamespaces.empty())
5131     Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
5132 
5133   // Write the undefined internal functions and variables, and inline functions.
5134   if (!UndefinedButUsed.empty())
5135     Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
5136 
5137   if (!DeleteExprsToAnalyze.empty())
5138     Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
5139 
5140   // Write the visible updates to DeclContexts.
5141   for (auto *DC : UpdatedDeclContexts)
5142     WriteDeclContextVisibleUpdate(DC);
5143 
5144   if (!WritingModule) {
5145     // Write the submodules that were imported, if any.
5146     struct ModuleInfo {
5147       uint64_t ID;
5148       Module *M;
5149       ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
5150     };
5151     llvm::SmallVector<ModuleInfo, 64> Imports;
5152     for (const auto *I : Context.local_imports()) {
5153       assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
5154       Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
5155                          I->getImportedModule()));
5156     }
5157 
5158     if (!Imports.empty()) {
5159       auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
5160         return A.ID < B.ID;
5161       };
5162       auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
5163         return A.ID == B.ID;
5164       };
5165 
5166       // Sort and deduplicate module IDs.
5167       llvm::sort(Imports, Cmp);
5168       Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
5169                     Imports.end());
5170 
5171       RecordData ImportedModules;
5172       for (const auto &Import : Imports) {
5173         ImportedModules.push_back(Import.ID);
5174         // FIXME: If the module has macros imported then later has declarations
5175         // imported, this location won't be the right one as a location for the
5176         // declaration imports.
5177         AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
5178       }
5179 
5180       Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5181     }
5182   }
5183 
5184   WriteObjCCategories();
5185   if(!WritingModule) {
5186     WriteOptimizePragmaOptions(SemaRef);
5187     WriteMSStructPragmaOptions(SemaRef);
5188     WriteMSPointersToMembersPragmaOptions(SemaRef);
5189   }
5190   WritePackPragmaOptions(SemaRef);
5191 
5192   // Some simple statistics
5193   RecordData::value_type Record[] = {
5194       NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
5195   Stream.EmitRecord(STATISTICS, Record);
5196   Stream.ExitBlock();
5197 
5198   // Write the module file extension blocks.
5199   for (const auto &ExtWriter : ModuleFileExtensionWriters)
5200     WriteModuleFileExtension(SemaRef, *ExtWriter);
5201 
5202   return writeUnhashedControlBlock(PP, Context);
5203 }
5204 
5205 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
5206   if (DeclUpdates.empty())
5207     return;
5208 
5209   DeclUpdateMap LocalUpdates;
5210   LocalUpdates.swap(DeclUpdates);
5211 
5212   for (auto &DeclUpdate : LocalUpdates) {
5213     const Decl *D = DeclUpdate.first;
5214 
5215     bool HasUpdatedBody = false;
5216     RecordData RecordData;
5217     ASTRecordWriter Record(*this, RecordData);
5218     for (auto &Update : DeclUpdate.second) {
5219       DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
5220 
5221       // An updated body is emitted last, so that the reader doesn't need
5222       // to skip over the lazy body to reach statements for other records.
5223       if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
5224         HasUpdatedBody = true;
5225       else
5226         Record.push_back(Kind);
5227 
5228       switch (Kind) {
5229       case UPD_CXX_ADDED_IMPLICIT_MEMBER:
5230       case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
5231       case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
5232         assert(Update.getDecl() && "no decl to add?");
5233         Record.push_back(GetDeclRef(Update.getDecl()));
5234         break;
5235 
5236       case UPD_CXX_ADDED_FUNCTION_DEFINITION:
5237         break;
5238 
5239       case UPD_CXX_POINT_OF_INSTANTIATION:
5240         // FIXME: Do we need to also save the template specialization kind here?
5241         Record.AddSourceLocation(Update.getLoc());
5242         break;
5243 
5244       case UPD_CXX_ADDED_VAR_DEFINITION: {
5245         const VarDecl *VD = cast<VarDecl>(D);
5246         Record.push_back(VD->isInline());
5247         Record.push_back(VD->isInlineSpecified());
5248         if (VD->getInit()) {
5249           Record.push_back(!VD->isInitKnownICE() ? 1
5250                                                  : (VD->isInitICE() ? 3 : 2));
5251           Record.AddStmt(const_cast<Expr*>(VD->getInit()));
5252         } else {
5253           Record.push_back(0);
5254         }
5255         break;
5256       }
5257 
5258       case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
5259         Record.AddStmt(const_cast<Expr *>(
5260             cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
5261         break;
5262 
5263       case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5264         Record.AddStmt(
5265             cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5266         break;
5267 
5268       case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5269         auto *RD = cast<CXXRecordDecl>(D);
5270         UpdatedDeclContexts.insert(RD->getPrimaryContext());
5271         Record.push_back(RD->isParamDestroyedInCallee());
5272         Record.push_back(RD->getArgPassingRestrictions());
5273         Record.AddCXXDefinitionData(RD);
5274         Record.AddOffset(WriteDeclContextLexicalBlock(
5275             *Context, const_cast<CXXRecordDecl *>(RD)));
5276 
5277         // This state is sometimes updated by template instantiation, when we
5278         // switch from the specialization referring to the template declaration
5279         // to it referring to the template definition.
5280         if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5281           Record.push_back(MSInfo->getTemplateSpecializationKind());
5282           Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
5283         } else {
5284           auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5285           Record.push_back(Spec->getTemplateSpecializationKind());
5286           Record.AddSourceLocation(Spec->getPointOfInstantiation());
5287 
5288           // The instantiation might have been resolved to a partial
5289           // specialization. If so, record which one.
5290           auto From = Spec->getInstantiatedFrom();
5291           if (auto PartialSpec =
5292                 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5293             Record.push_back(true);
5294             Record.AddDeclRef(PartialSpec);
5295             Record.AddTemplateArgumentList(
5296                 &Spec->getTemplateInstantiationArgs());
5297           } else {
5298             Record.push_back(false);
5299           }
5300         }
5301         Record.push_back(RD->getTagKind());
5302         Record.AddSourceLocation(RD->getLocation());
5303         Record.AddSourceLocation(RD->getBeginLoc());
5304         Record.AddSourceRange(RD->getBraceRange());
5305 
5306         // Instantiation may change attributes; write them all out afresh.
5307         Record.push_back(D->hasAttrs());
5308         if (D->hasAttrs())
5309           Record.AddAttributes(D->getAttrs());
5310 
5311         // FIXME: Ensure we don't get here for explicit instantiations.
5312         break;
5313       }
5314 
5315       case UPD_CXX_RESOLVED_DTOR_DELETE:
5316         Record.AddDeclRef(Update.getDecl());
5317         Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
5318         break;
5319 
5320       case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
5321         addExceptionSpec(
5322             cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
5323             Record);
5324         break;
5325 
5326       case UPD_CXX_DEDUCED_RETURN_TYPE:
5327         Record.push_back(GetOrCreateTypeID(Update.getType()));
5328         break;
5329 
5330       case UPD_DECL_MARKED_USED:
5331         break;
5332 
5333       case UPD_MANGLING_NUMBER:
5334       case UPD_STATIC_LOCAL_NUMBER:
5335         Record.push_back(Update.getNumber());
5336         break;
5337 
5338       case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
5339         Record.AddSourceRange(
5340             D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5341         break;
5342 
5343       case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
5344         auto *A = D->getAttr<OMPAllocateDeclAttr>();
5345         Record.push_back(A->getAllocatorType());
5346         Record.AddStmt(A->getAllocator());
5347         Record.AddSourceRange(A->getRange());
5348         break;
5349       }
5350 
5351       case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5352         Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
5353         Record.AddSourceRange(
5354             D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5355         break;
5356 
5357       case UPD_DECL_EXPORTED:
5358         Record.push_back(getSubmoduleID(Update.getModule()));
5359         break;
5360 
5361       case UPD_ADDED_ATTR_TO_RECORD:
5362         Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
5363         break;
5364       }
5365     }
5366 
5367     if (HasUpdatedBody) {
5368       const auto *Def = cast<FunctionDecl>(D);
5369       Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
5370       Record.push_back(Def->isInlined());
5371       Record.AddSourceLocation(Def->getInnerLocStart());
5372       Record.AddFunctionDefinition(Def);
5373     }
5374 
5375     OffsetsRecord.push_back(GetDeclRef(D));
5376     OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5377   }
5378 }
5379 
5380 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
5381   uint32_t Raw = Loc.getRawEncoding();
5382   Record.push_back((Raw << 1) | (Raw >> 31));
5383 }
5384 
5385 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
5386   AddSourceLocation(Range.getBegin(), Record);
5387   AddSourceLocation(Range.getEnd(), Record);
5388 }
5389 
5390 void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
5391   Record->push_back(Value.getBitWidth());
5392   const uint64_t *Words = Value.getRawData();
5393   Record->append(Words, Words + Value.getNumWords());
5394 }
5395 
5396 void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
5397   Record->push_back(Value.isUnsigned());
5398   AddAPInt(Value);
5399 }
5400 
5401 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5402   AddAPInt(Value.bitcastToAPInt());
5403 }
5404 
5405 static void WriteFixedPointSemantics(ASTRecordWriter &Record,
5406                                      FixedPointSemantics FPSema) {
5407   Record.push_back(FPSema.getWidth());
5408   Record.push_back(FPSema.getScale());
5409   Record.push_back(FPSema.isSigned() | FPSema.isSaturated() << 1 |
5410                    FPSema.hasUnsignedPadding() << 2);
5411 }
5412 
5413 void ASTRecordWriter::AddAPValue(const APValue &Value) {
5414   APValue::ValueKind Kind = Value.getKind();
5415   push_back(static_cast<uint64_t>(Kind));
5416   switch (Kind) {
5417   case APValue::None:
5418   case APValue::Indeterminate:
5419     return;
5420   case APValue::Int:
5421     AddAPSInt(Value.getInt());
5422     return;
5423   case APValue::Float:
5424     push_back(static_cast<uint64_t>(
5425         llvm::APFloatBase::SemanticsToEnum(Value.getFloat().getSemantics())));
5426     AddAPFloat(Value.getFloat());
5427     return;
5428   case APValue::FixedPoint: {
5429     WriteFixedPointSemantics(*this, Value.getFixedPoint().getSemantics());
5430     AddAPSInt(Value.getFixedPoint().getValue());
5431     return;
5432   }
5433   case APValue::ComplexInt: {
5434     AddAPSInt(Value.getComplexIntReal());
5435     AddAPSInt(Value.getComplexIntImag());
5436     return;
5437   }
5438   case APValue::ComplexFloat: {
5439     push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5440         Value.getComplexFloatReal().getSemantics())));
5441     AddAPFloat(Value.getComplexFloatReal());
5442     push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5443         Value.getComplexFloatImag().getSemantics())));
5444     AddAPFloat(Value.getComplexFloatImag());
5445     return;
5446   }
5447   case APValue::LValue:
5448   case APValue::Vector:
5449   case APValue::Array:
5450   case APValue::Struct:
5451   case APValue::Union:
5452   case APValue::MemberPointer:
5453   case APValue::AddrLabelDiff:
5454     // TODO : Handle all these APValue::ValueKind.
5455     return;
5456   }
5457   llvm_unreachable("Invalid APValue::ValueKind");
5458 }
5459 
5460 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
5461   Record.push_back(getIdentifierRef(II));
5462 }
5463 
5464 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
5465   if (!II)
5466     return 0;
5467 
5468   IdentID &ID = IdentifierIDs[II];
5469   if (ID == 0)
5470     ID = NextIdentID++;
5471   return ID;
5472 }
5473 
5474 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
5475   // Don't emit builtin macros like __LINE__ to the AST file unless they
5476   // have been redefined by the header (in which case they are not
5477   // isBuiltinMacro).
5478   if (!MI || MI->isBuiltinMacro())
5479     return 0;
5480 
5481   MacroID &ID = MacroIDs[MI];
5482   if (ID == 0) {
5483     ID = NextMacroID++;
5484     MacroInfoToEmitData Info = { Name, MI, ID };
5485     MacroInfosToEmit.push_back(Info);
5486   }
5487   return ID;
5488 }
5489 
5490 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
5491   if (!MI || MI->isBuiltinMacro())
5492     return 0;
5493 
5494   assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5495   return MacroIDs[MI];
5496 }
5497 
5498 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
5499   return IdentMacroDirectivesOffsetMap.lookup(Name);
5500 }
5501 
5502 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5503   Record->push_back(Writer->getSelectorRef(SelRef));
5504 }
5505 
5506 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5507   if (Sel.getAsOpaquePtr() == nullptr) {
5508     return 0;
5509   }
5510 
5511   SelectorID SID = SelectorIDs[Sel];
5512   if (SID == 0 && Chain) {
5513     // This might trigger a ReadSelector callback, which will set the ID for
5514     // this selector.
5515     Chain->LoadSelector(Sel);
5516     SID = SelectorIDs[Sel];
5517   }
5518   if (SID == 0) {
5519     SID = NextSelectorID++;
5520     SelectorIDs[Sel] = SID;
5521   }
5522   return SID;
5523 }
5524 
5525 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5526   AddDeclRef(Temp->getDestructor());
5527 }
5528 
5529 void ASTRecordWriter::AddTemplateArgumentLocInfo(
5530     TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5531   switch (Kind) {
5532   case TemplateArgument::Expression:
5533     AddStmt(Arg.getAsExpr());
5534     break;
5535   case TemplateArgument::Type:
5536     AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5537     break;
5538   case TemplateArgument::Template:
5539     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5540     AddSourceLocation(Arg.getTemplateNameLoc());
5541     break;
5542   case TemplateArgument::TemplateExpansion:
5543     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5544     AddSourceLocation(Arg.getTemplateNameLoc());
5545     AddSourceLocation(Arg.getTemplateEllipsisLoc());
5546     break;
5547   case TemplateArgument::Null:
5548   case TemplateArgument::Integral:
5549   case TemplateArgument::Declaration:
5550   case TemplateArgument::NullPtr:
5551   case TemplateArgument::Pack:
5552     // FIXME: Is this right?
5553     break;
5554   }
5555 }
5556 
5557 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5558   AddTemplateArgument(Arg.getArgument());
5559 
5560   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5561     bool InfoHasSameExpr
5562       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5563     Record->push_back(InfoHasSameExpr);
5564     if (InfoHasSameExpr)
5565       return; // Avoid storing the same expr twice.
5566   }
5567   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5568 }
5569 
5570 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5571   if (!TInfo) {
5572     AddTypeRef(QualType());
5573     return;
5574   }
5575 
5576   AddTypeRef(TInfo->getType());
5577   AddTypeLoc(TInfo->getTypeLoc());
5578 }
5579 
5580 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
5581   TypeLocWriter TLW(*this);
5582   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5583     TLW.Visit(TL);
5584 }
5585 
5586 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5587   Record.push_back(GetOrCreateTypeID(T));
5588 }
5589 
5590 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5591   assert(Context);
5592   return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5593     if (T.isNull())
5594       return TypeIdx();
5595     assert(!T.getLocalFastQualifiers());
5596 
5597     TypeIdx &Idx = TypeIdxs[T];
5598     if (Idx.getIndex() == 0) {
5599       if (DoneWritingDeclsAndTypes) {
5600         assert(0 && "New type seen after serializing all the types to emit!");
5601         return TypeIdx();
5602       }
5603 
5604       // We haven't seen this type before. Assign it a new ID and put it
5605       // into the queue of types to emit.
5606       Idx = TypeIdx(NextTypeID++);
5607       DeclTypesToEmit.push(T);
5608     }
5609     return Idx;
5610   });
5611 }
5612 
5613 TypeID ASTWriter::getTypeID(QualType T) const {
5614   assert(Context);
5615   return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5616     if (T.isNull())
5617       return TypeIdx();
5618     assert(!T.getLocalFastQualifiers());
5619 
5620     TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5621     assert(I != TypeIdxs.end() && "Type not emitted!");
5622     return I->second;
5623   });
5624 }
5625 
5626 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5627   Record.push_back(GetDeclRef(D));
5628 }
5629 
5630 DeclID ASTWriter::GetDeclRef(const Decl *D) {
5631   assert(WritingAST && "Cannot request a declaration ID before AST writing");
5632 
5633   if (!D) {
5634     return 0;
5635   }
5636 
5637   // If D comes from an AST file, its declaration ID is already known and
5638   // fixed.
5639   if (D->isFromASTFile())
5640     return D->getGlobalID();
5641 
5642   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5643   DeclID &ID = DeclIDs[D];
5644   if (ID == 0) {
5645     if (DoneWritingDeclsAndTypes) {
5646       assert(0 && "New decl seen after serializing all the decls to emit!");
5647       return 0;
5648     }
5649 
5650     // We haven't seen this declaration before. Give it a new ID and
5651     // enqueue it in the list of declarations to emit.
5652     ID = NextDeclID++;
5653     DeclTypesToEmit.push(const_cast<Decl *>(D));
5654   }
5655 
5656   return ID;
5657 }
5658 
5659 DeclID ASTWriter::getDeclID(const Decl *D) {
5660   if (!D)
5661     return 0;
5662 
5663   // If D comes from an AST file, its declaration ID is already known and
5664   // fixed.
5665   if (D->isFromASTFile())
5666     return D->getGlobalID();
5667 
5668   assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5669   return DeclIDs[D];
5670 }
5671 
5672 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5673   assert(ID);
5674   assert(D);
5675 
5676   SourceLocation Loc = D->getLocation();
5677   if (Loc.isInvalid())
5678     return;
5679 
5680   // We only keep track of the file-level declarations of each file.
5681   if (!D->getLexicalDeclContext()->isFileContext())
5682     return;
5683   // FIXME: ParmVarDecls that are part of a function type of a parameter of
5684   // a function/objc method, should not have TU as lexical context.
5685   // TemplateTemplateParmDecls that are part of an alias template, should not
5686   // have TU as lexical context.
5687   if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
5688     return;
5689 
5690   SourceManager &SM = Context->getSourceManager();
5691   SourceLocation FileLoc = SM.getFileLoc(Loc);
5692   assert(SM.isLocalSourceLocation(FileLoc));
5693   FileID FID;
5694   unsigned Offset;
5695   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5696   if (FID.isInvalid())
5697     return;
5698   assert(SM.getSLocEntry(FID).isFile());
5699 
5700   DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5701   if (!Info)
5702     Info = new DeclIDInFileInfo();
5703 
5704   std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5705   LocDeclIDsTy &Decls = Info->DeclIDs;
5706 
5707   if (Decls.empty() || Decls.back().first <= Offset) {
5708     Decls.push_back(LocDecl);
5709     return;
5710   }
5711 
5712   LocDeclIDsTy::iterator I =
5713       llvm::upper_bound(Decls, LocDecl, llvm::less_first());
5714 
5715   Decls.insert(I, LocDecl);
5716 }
5717 
5718 void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
5719   // FIXME: Emit a stable enum for NameKind.  0 = Identifier etc.
5720   Record->push_back(Name.getNameKind());
5721   switch (Name.getNameKind()) {
5722   case DeclarationName::Identifier:
5723     AddIdentifierRef(Name.getAsIdentifierInfo());
5724     break;
5725 
5726   case DeclarationName::ObjCZeroArgSelector:
5727   case DeclarationName::ObjCOneArgSelector:
5728   case DeclarationName::ObjCMultiArgSelector:
5729     AddSelectorRef(Name.getObjCSelector());
5730     break;
5731 
5732   case DeclarationName::CXXConstructorName:
5733   case DeclarationName::CXXDestructorName:
5734   case DeclarationName::CXXConversionFunctionName:
5735     AddTypeRef(Name.getCXXNameType());
5736     break;
5737 
5738   case DeclarationName::CXXDeductionGuideName:
5739     AddDeclRef(Name.getCXXDeductionGuideTemplate());
5740     break;
5741 
5742   case DeclarationName::CXXOperatorName:
5743     Record->push_back(Name.getCXXOverloadedOperator());
5744     break;
5745 
5746   case DeclarationName::CXXLiteralOperatorName:
5747     AddIdentifierRef(Name.getCXXLiteralIdentifier());
5748     break;
5749 
5750   case DeclarationName::CXXUsingDirective:
5751     // No extra data to emit
5752     break;
5753   }
5754 }
5755 
5756 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5757   assert(needsAnonymousDeclarationNumber(D) &&
5758          "expected an anonymous declaration");
5759 
5760   // Number the anonymous declarations within this context, if we've not
5761   // already done so.
5762   auto It = AnonymousDeclarationNumbers.find(D);
5763   if (It == AnonymousDeclarationNumbers.end()) {
5764     auto *DC = D->getLexicalDeclContext();
5765     numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5766       AnonymousDeclarationNumbers[ND] = Number;
5767     });
5768 
5769     It = AnonymousDeclarationNumbers.find(D);
5770     assert(It != AnonymousDeclarationNumbers.end() &&
5771            "declaration not found within its lexical context");
5772   }
5773 
5774   return It->second;
5775 }
5776 
5777 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5778                                             DeclarationName Name) {
5779   switch (Name.getNameKind()) {
5780   case DeclarationName::CXXConstructorName:
5781   case DeclarationName::CXXDestructorName:
5782   case DeclarationName::CXXConversionFunctionName:
5783     AddTypeSourceInfo(DNLoc.NamedType.TInfo);
5784     break;
5785 
5786   case DeclarationName::CXXOperatorName:
5787     AddSourceLocation(SourceLocation::getFromRawEncoding(
5788         DNLoc.CXXOperatorName.BeginOpNameLoc));
5789     AddSourceLocation(
5790         SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
5791     break;
5792 
5793   case DeclarationName::CXXLiteralOperatorName:
5794     AddSourceLocation(SourceLocation::getFromRawEncoding(
5795         DNLoc.CXXLiteralOperatorName.OpNameLoc));
5796     break;
5797 
5798   case DeclarationName::Identifier:
5799   case DeclarationName::ObjCZeroArgSelector:
5800   case DeclarationName::ObjCOneArgSelector:
5801   case DeclarationName::ObjCMultiArgSelector:
5802   case DeclarationName::CXXUsingDirective:
5803   case DeclarationName::CXXDeductionGuideName:
5804     break;
5805   }
5806 }
5807 
5808 void ASTRecordWriter::AddDeclarationNameInfo(
5809     const DeclarationNameInfo &NameInfo) {
5810   AddDeclarationName(NameInfo.getName());
5811   AddSourceLocation(NameInfo.getLoc());
5812   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5813 }
5814 
5815 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5816   AddNestedNameSpecifierLoc(Info.QualifierLoc);
5817   Record->push_back(Info.NumTemplParamLists);
5818   for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5819     AddTemplateParameterList(Info.TemplParamLists[i]);
5820 }
5821 
5822 void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
5823   // Nested name specifiers usually aren't too long. I think that 8 would
5824   // typically accommodate the vast majority.
5825   SmallVector<NestedNameSpecifier *, 8> NestedNames;
5826 
5827   // Push each of the NNS's onto a stack for serialization in reverse order.
5828   while (NNS) {
5829     NestedNames.push_back(NNS);
5830     NNS = NNS->getPrefix();
5831   }
5832 
5833   Record->push_back(NestedNames.size());
5834   while(!NestedNames.empty()) {
5835     NNS = NestedNames.pop_back_val();
5836     NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5837     Record->push_back(Kind);
5838     switch (Kind) {
5839     case NestedNameSpecifier::Identifier:
5840       AddIdentifierRef(NNS->getAsIdentifier());
5841       break;
5842 
5843     case NestedNameSpecifier::Namespace:
5844       AddDeclRef(NNS->getAsNamespace());
5845       break;
5846 
5847     case NestedNameSpecifier::NamespaceAlias:
5848       AddDeclRef(NNS->getAsNamespaceAlias());
5849       break;
5850 
5851     case NestedNameSpecifier::TypeSpec:
5852     case NestedNameSpecifier::TypeSpecWithTemplate:
5853       AddTypeRef(QualType(NNS->getAsType(), 0));
5854       Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5855       break;
5856 
5857     case NestedNameSpecifier::Global:
5858       // Don't need to write an associated value.
5859       break;
5860 
5861     case NestedNameSpecifier::Super:
5862       AddDeclRef(NNS->getAsRecordDecl());
5863       break;
5864     }
5865   }
5866 }
5867 
5868 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5869   // Nested name specifiers usually aren't too long. I think that 8 would
5870   // typically accommodate the vast majority.
5871   SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5872 
5873   // Push each of the nested-name-specifiers's onto a stack for
5874   // serialization in reverse order.
5875   while (NNS) {
5876     NestedNames.push_back(NNS);
5877     NNS = NNS.getPrefix();
5878   }
5879 
5880   Record->push_back(NestedNames.size());
5881   while(!NestedNames.empty()) {
5882     NNS = NestedNames.pop_back_val();
5883     NestedNameSpecifier::SpecifierKind Kind
5884       = NNS.getNestedNameSpecifier()->getKind();
5885     Record->push_back(Kind);
5886     switch (Kind) {
5887     case NestedNameSpecifier::Identifier:
5888       AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5889       AddSourceRange(NNS.getLocalSourceRange());
5890       break;
5891 
5892     case NestedNameSpecifier::Namespace:
5893       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5894       AddSourceRange(NNS.getLocalSourceRange());
5895       break;
5896 
5897     case NestedNameSpecifier::NamespaceAlias:
5898       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5899       AddSourceRange(NNS.getLocalSourceRange());
5900       break;
5901 
5902     case NestedNameSpecifier::TypeSpec:
5903     case NestedNameSpecifier::TypeSpecWithTemplate:
5904       Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5905       AddTypeRef(NNS.getTypeLoc().getType());
5906       AddTypeLoc(NNS.getTypeLoc());
5907       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5908       break;
5909 
5910     case NestedNameSpecifier::Global:
5911       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5912       break;
5913 
5914     case NestedNameSpecifier::Super:
5915       AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5916       AddSourceRange(NNS.getLocalSourceRange());
5917       break;
5918     }
5919   }
5920 }
5921 
5922 void ASTRecordWriter::AddTemplateName(TemplateName Name) {
5923   TemplateName::NameKind Kind = Name.getKind();
5924   Record->push_back(Kind);
5925   switch (Kind) {
5926   case TemplateName::Template:
5927     AddDeclRef(Name.getAsTemplateDecl());
5928     break;
5929 
5930   case TemplateName::OverloadedTemplate: {
5931     OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5932     Record->push_back(OvT->size());
5933     for (const auto &I : *OvT)
5934       AddDeclRef(I);
5935     break;
5936   }
5937 
5938   case TemplateName::AssumedTemplate: {
5939     AssumedTemplateStorage *ADLT = Name.getAsAssumedTemplateName();
5940     AddDeclarationName(ADLT->getDeclName());
5941     break;
5942   }
5943 
5944   case TemplateName::QualifiedTemplate: {
5945     QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5946     AddNestedNameSpecifier(QualT->getQualifier());
5947     Record->push_back(QualT->hasTemplateKeyword());
5948     AddDeclRef(QualT->getTemplateDecl());
5949     break;
5950   }
5951 
5952   case TemplateName::DependentTemplate: {
5953     DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5954     AddNestedNameSpecifier(DepT->getQualifier());
5955     Record->push_back(DepT->isIdentifier());
5956     if (DepT->isIdentifier())
5957       AddIdentifierRef(DepT->getIdentifier());
5958     else
5959       Record->push_back(DepT->getOperator());
5960     break;
5961   }
5962 
5963   case TemplateName::SubstTemplateTemplateParm: {
5964     SubstTemplateTemplateParmStorage *subst
5965       = Name.getAsSubstTemplateTemplateParm();
5966     AddDeclRef(subst->getParameter());
5967     AddTemplateName(subst->getReplacement());
5968     break;
5969   }
5970 
5971   case TemplateName::SubstTemplateTemplateParmPack: {
5972     SubstTemplateTemplateParmPackStorage *SubstPack
5973       = Name.getAsSubstTemplateTemplateParmPack();
5974     AddDeclRef(SubstPack->getParameterPack());
5975     AddTemplateArgument(SubstPack->getArgumentPack());
5976     break;
5977   }
5978   }
5979 }
5980 
5981 void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5982   Record->push_back(Arg.getKind());
5983   switch (Arg.getKind()) {
5984   case TemplateArgument::Null:
5985     break;
5986   case TemplateArgument::Type:
5987     AddTypeRef(Arg.getAsType());
5988     break;
5989   case TemplateArgument::Declaration:
5990     AddDeclRef(Arg.getAsDecl());
5991     AddTypeRef(Arg.getParamTypeForDecl());
5992     break;
5993   case TemplateArgument::NullPtr:
5994     AddTypeRef(Arg.getNullPtrType());
5995     break;
5996   case TemplateArgument::Integral:
5997     AddAPSInt(Arg.getAsIntegral());
5998     AddTypeRef(Arg.getIntegralType());
5999     break;
6000   case TemplateArgument::Template:
6001     AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
6002     break;
6003   case TemplateArgument::TemplateExpansion:
6004     AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
6005     if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
6006       Record->push_back(*NumExpansions + 1);
6007     else
6008       Record->push_back(0);
6009     break;
6010   case TemplateArgument::Expression:
6011     AddStmt(Arg.getAsExpr());
6012     break;
6013   case TemplateArgument::Pack:
6014     Record->push_back(Arg.pack_size());
6015     for (const auto &P : Arg.pack_elements())
6016       AddTemplateArgument(P);
6017     break;
6018   }
6019 }
6020 
6021 void ASTRecordWriter::AddTemplateParameterList(
6022     const TemplateParameterList *TemplateParams) {
6023   assert(TemplateParams && "No TemplateParams!");
6024   AddSourceLocation(TemplateParams->getTemplateLoc());
6025   AddSourceLocation(TemplateParams->getLAngleLoc());
6026   AddSourceLocation(TemplateParams->getRAngleLoc());
6027   // TODO: Concepts
6028   Record->push_back(TemplateParams->size());
6029   for (const auto &P : *TemplateParams)
6030     AddDeclRef(P);
6031 }
6032 
6033 /// Emit a template argument list.
6034 void ASTRecordWriter::AddTemplateArgumentList(
6035     const TemplateArgumentList *TemplateArgs) {
6036   assert(TemplateArgs && "No TemplateArgs!");
6037   Record->push_back(TemplateArgs->size());
6038   for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
6039     AddTemplateArgument(TemplateArgs->get(i));
6040 }
6041 
6042 void ASTRecordWriter::AddASTTemplateArgumentListInfo(
6043     const ASTTemplateArgumentListInfo *ASTTemplArgList) {
6044   assert(ASTTemplArgList && "No ASTTemplArgList!");
6045   AddSourceLocation(ASTTemplArgList->LAngleLoc);
6046   AddSourceLocation(ASTTemplArgList->RAngleLoc);
6047   Record->push_back(ASTTemplArgList->NumTemplateArgs);
6048   const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
6049   for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
6050     AddTemplateArgumentLoc(TemplArgs[i]);
6051 }
6052 
6053 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
6054   Record->push_back(Set.size());
6055   for (ASTUnresolvedSet::const_iterator
6056          I = Set.begin(), E = Set.end(); I != E; ++I) {
6057     AddDeclRef(I.getDecl());
6058     Record->push_back(I.getAccess());
6059   }
6060 }
6061 
6062 // FIXME: Move this out of the main ASTRecordWriter interface.
6063 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
6064   Record->push_back(Base.isVirtual());
6065   Record->push_back(Base.isBaseOfClass());
6066   Record->push_back(Base.getAccessSpecifierAsWritten());
6067   Record->push_back(Base.getInheritConstructors());
6068   AddTypeSourceInfo(Base.getTypeSourceInfo());
6069   AddSourceRange(Base.getSourceRange());
6070   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
6071                                           : SourceLocation());
6072 }
6073 
6074 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
6075                                       ArrayRef<CXXBaseSpecifier> Bases) {
6076   ASTWriter::RecordData Record;
6077   ASTRecordWriter Writer(W, Record);
6078   Writer.push_back(Bases.size());
6079 
6080   for (auto &Base : Bases)
6081     Writer.AddCXXBaseSpecifier(Base);
6082 
6083   return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
6084 }
6085 
6086 // FIXME: Move this out of the main ASTRecordWriter interface.
6087 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
6088   AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
6089 }
6090 
6091 static uint64_t
6092 EmitCXXCtorInitializers(ASTWriter &W,
6093                         ArrayRef<CXXCtorInitializer *> CtorInits) {
6094   ASTWriter::RecordData Record;
6095   ASTRecordWriter Writer(W, Record);
6096   Writer.push_back(CtorInits.size());
6097 
6098   for (auto *Init : CtorInits) {
6099     if (Init->isBaseInitializer()) {
6100       Writer.push_back(CTOR_INITIALIZER_BASE);
6101       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
6102       Writer.push_back(Init->isBaseVirtual());
6103     } else if (Init->isDelegatingInitializer()) {
6104       Writer.push_back(CTOR_INITIALIZER_DELEGATING);
6105       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
6106     } else if (Init->isMemberInitializer()){
6107       Writer.push_back(CTOR_INITIALIZER_MEMBER);
6108       Writer.AddDeclRef(Init->getMember());
6109     } else {
6110       Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
6111       Writer.AddDeclRef(Init->getIndirectMember());
6112     }
6113 
6114     Writer.AddSourceLocation(Init->getMemberLocation());
6115     Writer.AddStmt(Init->getInit());
6116     Writer.AddSourceLocation(Init->getLParenLoc());
6117     Writer.AddSourceLocation(Init->getRParenLoc());
6118     Writer.push_back(Init->isWritten());
6119     if (Init->isWritten())
6120       Writer.push_back(Init->getSourceOrder());
6121   }
6122 
6123   return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
6124 }
6125 
6126 // FIXME: Move this out of the main ASTRecordWriter interface.
6127 void ASTRecordWriter::AddCXXCtorInitializers(
6128     ArrayRef<CXXCtorInitializer *> CtorInits) {
6129   AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
6130 }
6131 
6132 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
6133   auto &Data = D->data();
6134   Record->push_back(Data.IsLambda);
6135   Record->push_back(Data.UserDeclaredConstructor);
6136   Record->push_back(Data.UserDeclaredSpecialMembers);
6137   Record->push_back(Data.Aggregate);
6138   Record->push_back(Data.PlainOldData);
6139   Record->push_back(Data.Empty);
6140   Record->push_back(Data.Polymorphic);
6141   Record->push_back(Data.Abstract);
6142   Record->push_back(Data.IsStandardLayout);
6143   Record->push_back(Data.IsCXX11StandardLayout);
6144   Record->push_back(Data.HasBasesWithFields);
6145   Record->push_back(Data.HasBasesWithNonStaticDataMembers);
6146   Record->push_back(Data.HasPrivateFields);
6147   Record->push_back(Data.HasProtectedFields);
6148   Record->push_back(Data.HasPublicFields);
6149   Record->push_back(Data.HasMutableFields);
6150   Record->push_back(Data.HasVariantMembers);
6151   Record->push_back(Data.HasOnlyCMembers);
6152   Record->push_back(Data.HasInClassInitializer);
6153   Record->push_back(Data.HasUninitializedReferenceMember);
6154   Record->push_back(Data.HasUninitializedFields);
6155   Record->push_back(Data.HasInheritedConstructor);
6156   Record->push_back(Data.HasInheritedAssignment);
6157   Record->push_back(Data.NeedOverloadResolutionForCopyConstructor);
6158   Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
6159   Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
6160   Record->push_back(Data.NeedOverloadResolutionForDestructor);
6161   Record->push_back(Data.DefaultedCopyConstructorIsDeleted);
6162   Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
6163   Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
6164   Record->push_back(Data.DefaultedDestructorIsDeleted);
6165   Record->push_back(Data.HasTrivialSpecialMembers);
6166   Record->push_back(Data.HasTrivialSpecialMembersForCall);
6167   Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
6168   Record->push_back(Data.DeclaredNonTrivialSpecialMembersForCall);
6169   Record->push_back(Data.HasIrrelevantDestructor);
6170   Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
6171   Record->push_back(Data.HasDefaultedDefaultConstructor);
6172   Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
6173   Record->push_back(Data.HasConstexprDefaultConstructor);
6174   Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
6175   Record->push_back(Data.ComputedVisibleConversions);
6176   Record->push_back(Data.UserProvidedDefaultConstructor);
6177   Record->push_back(Data.DeclaredSpecialMembers);
6178   Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForVBase);
6179   Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase);
6180   Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
6181   Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
6182   Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
6183 
6184   // getODRHash will compute the ODRHash if it has not been previously computed.
6185   Record->push_back(D->getODRHash());
6186   bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
6187                           Writer->WritingModule && !D->isDependentType();
6188   Record->push_back(ModulesDebugInfo);
6189   if (ModulesDebugInfo)
6190     Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
6191 
6192   // IsLambda bit is already saved.
6193 
6194   Record->push_back(Data.NumBases);
6195   if (Data.NumBases > 0)
6196     AddCXXBaseSpecifiers(Data.bases());
6197 
6198   // FIXME: Make VBases lazily computed when needed to avoid storing them.
6199   Record->push_back(Data.NumVBases);
6200   if (Data.NumVBases > 0)
6201     AddCXXBaseSpecifiers(Data.vbases());
6202 
6203   AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
6204   AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
6205   // Data.Definition is the owning decl, no need to write it.
6206   AddDeclRef(D->getFirstFriend());
6207 
6208   // Add lambda-specific data.
6209   if (Data.IsLambda) {
6210     auto &Lambda = D->getLambdaData();
6211     Record->push_back(Lambda.Dependent);
6212     Record->push_back(Lambda.IsGenericLambda);
6213     Record->push_back(Lambda.CaptureDefault);
6214     Record->push_back(Lambda.NumCaptures);
6215     Record->push_back(Lambda.NumExplicitCaptures);
6216     Record->push_back(Lambda.ManglingNumber);
6217     AddDeclRef(D->getLambdaContextDecl());
6218     AddTypeSourceInfo(Lambda.MethodTyInfo);
6219     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
6220       const LambdaCapture &Capture = Lambda.Captures[I];
6221       AddSourceLocation(Capture.getLocation());
6222       Record->push_back(Capture.isImplicit());
6223       Record->push_back(Capture.getCaptureKind());
6224       switch (Capture.getCaptureKind()) {
6225       case LCK_StarThis:
6226       case LCK_This:
6227       case LCK_VLAType:
6228         break;
6229       case LCK_ByCopy:
6230       case LCK_ByRef:
6231         VarDecl *Var =
6232             Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
6233         AddDeclRef(Var);
6234         AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
6235                                                     : SourceLocation());
6236         break;
6237       }
6238     }
6239   }
6240 }
6241 
6242 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
6243   assert(Reader && "Cannot remove chain");
6244   assert((!Chain || Chain == Reader) && "Cannot replace chain");
6245   assert(FirstDeclID == NextDeclID &&
6246          FirstTypeID == NextTypeID &&
6247          FirstIdentID == NextIdentID &&
6248          FirstMacroID == NextMacroID &&
6249          FirstSubmoduleID == NextSubmoduleID &&
6250          FirstSelectorID == NextSelectorID &&
6251          "Setting chain after writing has started.");
6252 
6253   Chain = Reader;
6254 
6255   // Note, this will get called multiple times, once one the reader starts up
6256   // and again each time it's done reading a PCH or module.
6257   FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
6258   FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
6259   FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
6260   FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
6261   FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
6262   FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
6263   NextDeclID = FirstDeclID;
6264   NextTypeID = FirstTypeID;
6265   NextIdentID = FirstIdentID;
6266   NextMacroID = FirstMacroID;
6267   NextSelectorID = FirstSelectorID;
6268   NextSubmoduleID = FirstSubmoduleID;
6269 }
6270 
6271 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
6272   // Always keep the highest ID. See \p TypeRead() for more information.
6273   IdentID &StoredID = IdentifierIDs[II];
6274   if (ID > StoredID)
6275     StoredID = ID;
6276 }
6277 
6278 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
6279   // Always keep the highest ID. See \p TypeRead() for more information.
6280   MacroID &StoredID = MacroIDs[MI];
6281   if (ID > StoredID)
6282     StoredID = ID;
6283 }
6284 
6285 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
6286   // Always take the highest-numbered type index. This copes with an interesting
6287   // case for chained AST writing where we schedule writing the type and then,
6288   // later, deserialize the type from another AST. In this case, we want to
6289   // keep the higher-numbered entry so that we can properly write it out to
6290   // the AST file.
6291   TypeIdx &StoredIdx = TypeIdxs[T];
6292   if (Idx.getIndex() >= StoredIdx.getIndex())
6293     StoredIdx = Idx;
6294 }
6295 
6296 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
6297   // Always keep the highest ID. See \p TypeRead() for more information.
6298   SelectorID &StoredID = SelectorIDs[S];
6299   if (ID > StoredID)
6300     StoredID = ID;
6301 }
6302 
6303 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
6304                                     MacroDefinitionRecord *MD) {
6305   assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
6306   MacroDefinitions[MD] = ID;
6307 }
6308 
6309 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
6310   assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
6311   SubmoduleIDs[Mod] = ID;
6312 }
6313 
6314 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
6315   if (Chain && Chain->isProcessingUpdateRecords()) return;
6316   assert(D->isCompleteDefinition());
6317   assert(!WritingAST && "Already writing the AST!");
6318   if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6319     // We are interested when a PCH decl is modified.
6320     if (RD->isFromASTFile()) {
6321       // A forward reference was mutated into a definition. Rewrite it.
6322       // FIXME: This happens during template instantiation, should we
6323       // have created a new definition decl instead ?
6324       assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
6325              "completed a tag from another module but not by instantiation?");
6326       DeclUpdates[RD].push_back(
6327           DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
6328     }
6329   }
6330 }
6331 
6332 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
6333   if (D->isFromASTFile())
6334     return true;
6335 
6336   // The predefined __va_list_tag struct is imported if we imported any decls.
6337   // FIXME: This is a gross hack.
6338   return D == D->getASTContext().getVaListTagDecl();
6339 }
6340 
6341 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
6342   if (Chain && Chain->isProcessingUpdateRecords()) return;
6343   assert(DC->isLookupContext() &&
6344           "Should not add lookup results to non-lookup contexts!");
6345 
6346   // TU is handled elsewhere.
6347   if (isa<TranslationUnitDecl>(DC))
6348     return;
6349 
6350   // Namespaces are handled elsewhere, except for template instantiations of
6351   // FunctionTemplateDecls in namespaces. We are interested in cases where the
6352   // local instantiations are added to an imported context. Only happens when
6353   // adding ADL lookup candidates, for example templated friends.
6354   if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
6355       !isa<FunctionTemplateDecl>(D))
6356     return;
6357 
6358   // We're only interested in cases where a local declaration is added to an
6359   // imported context.
6360   if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
6361     return;
6362 
6363   assert(DC == DC->getPrimaryContext() && "added to non-primary context");
6364   assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
6365   assert(!WritingAST && "Already writing the AST!");
6366   if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
6367     // We're adding a visible declaration to a predefined decl context. Ensure
6368     // that we write out all of its lookup results so we don't get a nasty
6369     // surprise when we try to emit its lookup table.
6370     for (auto *Child : DC->decls())
6371       DeclsToEmitEvenIfUnreferenced.push_back(Child);
6372   }
6373   DeclsToEmitEvenIfUnreferenced.push_back(D);
6374 }
6375 
6376 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
6377   if (Chain && Chain->isProcessingUpdateRecords()) return;
6378   assert(D->isImplicit());
6379 
6380   // We're only interested in cases where a local declaration is added to an
6381   // imported context.
6382   if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
6383     return;
6384 
6385   if (!isa<CXXMethodDecl>(D))
6386     return;
6387 
6388   // A decl coming from PCH was modified.
6389   assert(RD->isCompleteDefinition());
6390   assert(!WritingAST && "Already writing the AST!");
6391   DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
6392 }
6393 
6394 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
6395   if (Chain && Chain->isProcessingUpdateRecords()) return;
6396   assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
6397   if (!Chain) return;
6398   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6399     // If we don't already know the exception specification for this redecl
6400     // chain, add an update record for it.
6401     if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
6402                                       ->getType()
6403                                       ->castAs<FunctionProtoType>()
6404                                       ->getExceptionSpecType()))
6405       DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
6406   });
6407 }
6408 
6409 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
6410   if (Chain && Chain->isProcessingUpdateRecords()) return;
6411   assert(!WritingAST && "Already writing the AST!");
6412   if (!Chain) return;
6413   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6414     DeclUpdates[D].push_back(
6415         DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
6416   });
6417 }
6418 
6419 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
6420                                        const FunctionDecl *Delete,
6421                                        Expr *ThisArg) {
6422   if (Chain && Chain->isProcessingUpdateRecords()) return;
6423   assert(!WritingAST && "Already writing the AST!");
6424   assert(Delete && "Not given an operator delete");
6425   if (!Chain) return;
6426   Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
6427     DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
6428   });
6429 }
6430 
6431 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
6432   if (Chain && Chain->isProcessingUpdateRecords()) return;
6433   assert(!WritingAST && "Already writing the AST!");
6434   if (!D->isFromASTFile())
6435     return; // Declaration not imported from PCH.
6436 
6437   // Implicit function decl from a PCH was defined.
6438   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6439 }
6440 
6441 void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
6442   if (Chain && Chain->isProcessingUpdateRecords()) return;
6443   assert(!WritingAST && "Already writing the AST!");
6444   if (!D->isFromASTFile())
6445     return;
6446 
6447   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
6448 }
6449 
6450 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
6451   if (Chain && Chain->isProcessingUpdateRecords()) return;
6452   assert(!WritingAST && "Already writing the AST!");
6453   if (!D->isFromASTFile())
6454     return;
6455 
6456   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6457 }
6458 
6459 void ASTWriter::InstantiationRequested(const ValueDecl *D) {
6460   if (Chain && Chain->isProcessingUpdateRecords()) return;
6461   assert(!WritingAST && "Already writing the AST!");
6462   if (!D->isFromASTFile())
6463     return;
6464 
6465   // Since the actual instantiation is delayed, this really means that we need
6466   // to update the instantiation location.
6467   SourceLocation POI;
6468   if (auto *VD = dyn_cast<VarDecl>(D))
6469     POI = VD->getPointOfInstantiation();
6470   else
6471     POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
6472   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
6473 }
6474 
6475 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
6476   if (Chain && Chain->isProcessingUpdateRecords()) return;
6477   assert(!WritingAST && "Already writing the AST!");
6478   if (!D->isFromASTFile())
6479     return;
6480 
6481   DeclUpdates[D].push_back(
6482       DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
6483 }
6484 
6485 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
6486   assert(!WritingAST && "Already writing the AST!");
6487   if (!D->isFromASTFile())
6488     return;
6489 
6490   DeclUpdates[D].push_back(
6491       DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
6492 }
6493 
6494 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
6495                                              const ObjCInterfaceDecl *IFD) {
6496   if (Chain && Chain->isProcessingUpdateRecords()) return;
6497   assert(!WritingAST && "Already writing the AST!");
6498   if (!IFD->isFromASTFile())
6499     return; // Declaration not imported from PCH.
6500 
6501   assert(IFD->getDefinition() && "Category on a class without a definition?");
6502   ObjCClassesWithCategories.insert(
6503     const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
6504 }
6505 
6506 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
6507   if (Chain && Chain->isProcessingUpdateRecords()) return;
6508   assert(!WritingAST && "Already writing the AST!");
6509 
6510   // If there is *any* declaration of the entity that's not from an AST file,
6511   // we can skip writing the update record. We make sure that isUsed() triggers
6512   // completion of the redeclaration chain of the entity.
6513   for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
6514     if (IsLocalDecl(Prev))
6515       return;
6516 
6517   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
6518 }
6519 
6520 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
6521   if (Chain && Chain->isProcessingUpdateRecords()) return;
6522   assert(!WritingAST && "Already writing the AST!");
6523   if (!D->isFromASTFile())
6524     return;
6525 
6526   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
6527 }
6528 
6529 void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
6530   if (Chain && Chain->isProcessingUpdateRecords()) return;
6531   assert(!WritingAST && "Already writing the AST!");
6532   if (!D->isFromASTFile())
6533     return;
6534 
6535   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
6536 }
6537 
6538 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6539                                                      const Attr *Attr) {
6540   if (Chain && Chain->isProcessingUpdateRecords()) return;
6541   assert(!WritingAST && "Already writing the AST!");
6542   if (!D->isFromASTFile())
6543     return;
6544 
6545   DeclUpdates[D].push_back(
6546       DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
6547 }
6548 
6549 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
6550   if (Chain && Chain->isProcessingUpdateRecords()) return;
6551   assert(!WritingAST && "Already writing the AST!");
6552   assert(D->isHidden() && "expected a hidden declaration");
6553   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
6554 }
6555 
6556 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6557                                        const RecordDecl *Record) {
6558   if (Chain && Chain->isProcessingUpdateRecords()) return;
6559   assert(!WritingAST && "Already writing the AST!");
6560   if (!Record->isFromASTFile())
6561     return;
6562   DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6563 }
6564 
6565 void ASTWriter::AddedCXXTemplateSpecialization(
6566     const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6567   assert(!WritingAST && "Already writing the AST!");
6568 
6569   if (!TD->getFirstDecl()->isFromASTFile())
6570     return;
6571   if (Chain && Chain->isProcessingUpdateRecords())
6572     return;
6573 
6574   DeclsToEmitEvenIfUnreferenced.push_back(D);
6575 }
6576 
6577 void ASTWriter::AddedCXXTemplateSpecialization(
6578     const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6579   assert(!WritingAST && "Already writing the AST!");
6580 
6581   if (!TD->getFirstDecl()->isFromASTFile())
6582     return;
6583   if (Chain && Chain->isProcessingUpdateRecords())
6584     return;
6585 
6586   DeclsToEmitEvenIfUnreferenced.push_back(D);
6587 }
6588 
6589 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6590                                                const FunctionDecl *D) {
6591   assert(!WritingAST && "Already writing the AST!");
6592 
6593   if (!TD->getFirstDecl()->isFromASTFile())
6594     return;
6595   if (Chain && Chain->isProcessingUpdateRecords())
6596     return;
6597 
6598   DeclsToEmitEvenIfUnreferenced.push_back(D);
6599 }
6600 
6601 //===----------------------------------------------------------------------===//
6602 //// OMPClause Serialization
6603 ////===----------------------------------------------------------------------===//
6604 
6605 void OMPClauseWriter::writeClause(OMPClause *C) {
6606   Record.push_back(C->getClauseKind());
6607   Visit(C);
6608   Record.AddSourceLocation(C->getBeginLoc());
6609   Record.AddSourceLocation(C->getEndLoc());
6610 }
6611 
6612 void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
6613   Record.push_back(C->getCaptureRegion());
6614   Record.AddStmt(C->getPreInitStmt());
6615 }
6616 
6617 void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6618   VisitOMPClauseWithPreInit(C);
6619   Record.AddStmt(C->getPostUpdateExpr());
6620 }
6621 
6622 void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6623   VisitOMPClauseWithPreInit(C);
6624   Record.push_back(C->getNameModifier());
6625   Record.AddSourceLocation(C->getNameModifierLoc());
6626   Record.AddSourceLocation(C->getColonLoc());
6627   Record.AddStmt(C->getCondition());
6628   Record.AddSourceLocation(C->getLParenLoc());
6629 }
6630 
6631 void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
6632   Record.AddStmt(C->getCondition());
6633   Record.AddSourceLocation(C->getLParenLoc());
6634 }
6635 
6636 void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6637   VisitOMPClauseWithPreInit(C);
6638   Record.AddStmt(C->getNumThreads());
6639   Record.AddSourceLocation(C->getLParenLoc());
6640 }
6641 
6642 void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6643   Record.AddStmt(C->getSafelen());
6644   Record.AddSourceLocation(C->getLParenLoc());
6645 }
6646 
6647 void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6648   Record.AddStmt(C->getSimdlen());
6649   Record.AddSourceLocation(C->getLParenLoc());
6650 }
6651 
6652 void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6653   Record.AddStmt(C->getAllocator());
6654   Record.AddSourceLocation(C->getLParenLoc());
6655 }
6656 
6657 void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6658   Record.AddStmt(C->getNumForLoops());
6659   Record.AddSourceLocation(C->getLParenLoc());
6660 }
6661 
6662 void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
6663   Record.push_back(C->getDefaultKind());
6664   Record.AddSourceLocation(C->getLParenLoc());
6665   Record.AddSourceLocation(C->getDefaultKindKwLoc());
6666 }
6667 
6668 void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
6669   Record.push_back(C->getProcBindKind());
6670   Record.AddSourceLocation(C->getLParenLoc());
6671   Record.AddSourceLocation(C->getProcBindKindKwLoc());
6672 }
6673 
6674 void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6675   VisitOMPClauseWithPreInit(C);
6676   Record.push_back(C->getScheduleKind());
6677   Record.push_back(C->getFirstScheduleModifier());
6678   Record.push_back(C->getSecondScheduleModifier());
6679   Record.AddStmt(C->getChunkSize());
6680   Record.AddSourceLocation(C->getLParenLoc());
6681   Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6682   Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6683   Record.AddSourceLocation(C->getScheduleKindLoc());
6684   Record.AddSourceLocation(C->getCommaLoc());
6685 }
6686 
6687 void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6688   Record.push_back(C->getLoopNumIterations().size());
6689   Record.AddStmt(C->getNumForLoops());
6690   for (Expr *NumIter : C->getLoopNumIterations())
6691     Record.AddStmt(NumIter);
6692   for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
6693     Record.AddStmt(C->getLoopCounter(I));
6694   Record.AddSourceLocation(C->getLParenLoc());
6695 }
6696 
6697 void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6698 
6699 void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6700 
6701 void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6702 
6703 void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6704 
6705 void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6706 
6707 void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *) {}
6708 
6709 void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6710 
6711 void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6712 
6713 void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6714 
6715 void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6716 
6717 void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6718 
6719 void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
6720   Record.push_back(C->varlist_size());
6721   Record.AddSourceLocation(C->getLParenLoc());
6722   for (auto *VE : C->varlists()) {
6723     Record.AddStmt(VE);
6724   }
6725   for (auto *VE : C->private_copies()) {
6726     Record.AddStmt(VE);
6727   }
6728 }
6729 
6730 void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
6731   Record.push_back(C->varlist_size());
6732   VisitOMPClauseWithPreInit(C);
6733   Record.AddSourceLocation(C->getLParenLoc());
6734   for (auto *VE : C->varlists()) {
6735     Record.AddStmt(VE);
6736   }
6737   for (auto *VE : C->private_copies()) {
6738     Record.AddStmt(VE);
6739   }
6740   for (auto *VE : C->inits()) {
6741     Record.AddStmt(VE);
6742   }
6743 }
6744 
6745 void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
6746   Record.push_back(C->varlist_size());
6747   VisitOMPClauseWithPostUpdate(C);
6748   Record.AddSourceLocation(C->getLParenLoc());
6749   for (auto *VE : C->varlists())
6750     Record.AddStmt(VE);
6751   for (auto *E : C->private_copies())
6752     Record.AddStmt(E);
6753   for (auto *E : C->source_exprs())
6754     Record.AddStmt(E);
6755   for (auto *E : C->destination_exprs())
6756     Record.AddStmt(E);
6757   for (auto *E : C->assignment_ops())
6758     Record.AddStmt(E);
6759 }
6760 
6761 void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
6762   Record.push_back(C->varlist_size());
6763   Record.AddSourceLocation(C->getLParenLoc());
6764   for (auto *VE : C->varlists())
6765     Record.AddStmt(VE);
6766 }
6767 
6768 void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
6769   Record.push_back(C->varlist_size());
6770   VisitOMPClauseWithPostUpdate(C);
6771   Record.AddSourceLocation(C->getLParenLoc());
6772   Record.AddSourceLocation(C->getColonLoc());
6773   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6774   Record.AddDeclarationNameInfo(C->getNameInfo());
6775   for (auto *VE : C->varlists())
6776     Record.AddStmt(VE);
6777   for (auto *VE : C->privates())
6778     Record.AddStmt(VE);
6779   for (auto *E : C->lhs_exprs())
6780     Record.AddStmt(E);
6781   for (auto *E : C->rhs_exprs())
6782     Record.AddStmt(E);
6783   for (auto *E : C->reduction_ops())
6784     Record.AddStmt(E);
6785 }
6786 
6787 void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
6788   Record.push_back(C->varlist_size());
6789   VisitOMPClauseWithPostUpdate(C);
6790   Record.AddSourceLocation(C->getLParenLoc());
6791   Record.AddSourceLocation(C->getColonLoc());
6792   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6793   Record.AddDeclarationNameInfo(C->getNameInfo());
6794   for (auto *VE : C->varlists())
6795     Record.AddStmt(VE);
6796   for (auto *VE : C->privates())
6797     Record.AddStmt(VE);
6798   for (auto *E : C->lhs_exprs())
6799     Record.AddStmt(E);
6800   for (auto *E : C->rhs_exprs())
6801     Record.AddStmt(E);
6802   for (auto *E : C->reduction_ops())
6803     Record.AddStmt(E);
6804 }
6805 
6806 void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
6807   Record.push_back(C->varlist_size());
6808   VisitOMPClauseWithPostUpdate(C);
6809   Record.AddSourceLocation(C->getLParenLoc());
6810   Record.AddSourceLocation(C->getColonLoc());
6811   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6812   Record.AddDeclarationNameInfo(C->getNameInfo());
6813   for (auto *VE : C->varlists())
6814     Record.AddStmt(VE);
6815   for (auto *VE : C->privates())
6816     Record.AddStmt(VE);
6817   for (auto *E : C->lhs_exprs())
6818     Record.AddStmt(E);
6819   for (auto *E : C->rhs_exprs())
6820     Record.AddStmt(E);
6821   for (auto *E : C->reduction_ops())
6822     Record.AddStmt(E);
6823   for (auto *E : C->taskgroup_descriptors())
6824     Record.AddStmt(E);
6825 }
6826 
6827 void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
6828   Record.push_back(C->varlist_size());
6829   VisitOMPClauseWithPostUpdate(C);
6830   Record.AddSourceLocation(C->getLParenLoc());
6831   Record.AddSourceLocation(C->getColonLoc());
6832   Record.push_back(C->getModifier());
6833   Record.AddSourceLocation(C->getModifierLoc());
6834   for (auto *VE : C->varlists()) {
6835     Record.AddStmt(VE);
6836   }
6837   for (auto *VE : C->privates()) {
6838     Record.AddStmt(VE);
6839   }
6840   for (auto *VE : C->inits()) {
6841     Record.AddStmt(VE);
6842   }
6843   for (auto *VE : C->updates()) {
6844     Record.AddStmt(VE);
6845   }
6846   for (auto *VE : C->finals()) {
6847     Record.AddStmt(VE);
6848   }
6849   Record.AddStmt(C->getStep());
6850   Record.AddStmt(C->getCalcStep());
6851   for (auto *VE : C->used_expressions())
6852     Record.AddStmt(VE);
6853 }
6854 
6855 void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
6856   Record.push_back(C->varlist_size());
6857   Record.AddSourceLocation(C->getLParenLoc());
6858   Record.AddSourceLocation(C->getColonLoc());
6859   for (auto *VE : C->varlists())
6860     Record.AddStmt(VE);
6861   Record.AddStmt(C->getAlignment());
6862 }
6863 
6864 void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
6865   Record.push_back(C->varlist_size());
6866   Record.AddSourceLocation(C->getLParenLoc());
6867   for (auto *VE : C->varlists())
6868     Record.AddStmt(VE);
6869   for (auto *E : C->source_exprs())
6870     Record.AddStmt(E);
6871   for (auto *E : C->destination_exprs())
6872     Record.AddStmt(E);
6873   for (auto *E : C->assignment_ops())
6874     Record.AddStmt(E);
6875 }
6876 
6877 void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
6878   Record.push_back(C->varlist_size());
6879   Record.AddSourceLocation(C->getLParenLoc());
6880   for (auto *VE : C->varlists())
6881     Record.AddStmt(VE);
6882   for (auto *E : C->source_exprs())
6883     Record.AddStmt(E);
6884   for (auto *E : C->destination_exprs())
6885     Record.AddStmt(E);
6886   for (auto *E : C->assignment_ops())
6887     Record.AddStmt(E);
6888 }
6889 
6890 void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
6891   Record.push_back(C->varlist_size());
6892   Record.AddSourceLocation(C->getLParenLoc());
6893   for (auto *VE : C->varlists())
6894     Record.AddStmt(VE);
6895 }
6896 
6897 void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
6898   Record.push_back(C->varlist_size());
6899   Record.push_back(C->getNumLoops());
6900   Record.AddSourceLocation(C->getLParenLoc());
6901   Record.push_back(C->getDependencyKind());
6902   Record.AddSourceLocation(C->getDependencyLoc());
6903   Record.AddSourceLocation(C->getColonLoc());
6904   for (auto *VE : C->varlists())
6905     Record.AddStmt(VE);
6906   for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
6907     Record.AddStmt(C->getLoopData(I));
6908 }
6909 
6910 void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
6911   VisitOMPClauseWithPreInit(C);
6912   Record.AddStmt(C->getDevice());
6913   Record.AddSourceLocation(C->getLParenLoc());
6914 }
6915 
6916 void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
6917   Record.push_back(C->varlist_size());
6918   Record.push_back(C->getUniqueDeclarationsNum());
6919   Record.push_back(C->getTotalComponentListNum());
6920   Record.push_back(C->getTotalComponentsNum());
6921   Record.AddSourceLocation(C->getLParenLoc());
6922   for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
6923     Record.push_back(C->getMapTypeModifier(I));
6924     Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
6925   }
6926   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6927   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6928   Record.push_back(C->getMapType());
6929   Record.AddSourceLocation(C->getMapLoc());
6930   Record.AddSourceLocation(C->getColonLoc());
6931   for (auto *E : C->varlists())
6932     Record.AddStmt(E);
6933   for (auto *E : C->mapperlists())
6934     Record.AddStmt(E);
6935   for (auto *D : C->all_decls())
6936     Record.AddDeclRef(D);
6937   for (auto N : C->all_num_lists())
6938     Record.push_back(N);
6939   for (auto N : C->all_lists_sizes())
6940     Record.push_back(N);
6941   for (auto &M : C->all_components()) {
6942     Record.AddStmt(M.getAssociatedExpression());
6943     Record.AddDeclRef(M.getAssociatedDeclaration());
6944   }
6945 }
6946 
6947 void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
6948   Record.push_back(C->varlist_size());
6949   Record.AddSourceLocation(C->getLParenLoc());
6950   Record.AddSourceLocation(C->getColonLoc());
6951   Record.AddStmt(C->getAllocator());
6952   for (auto *VE : C->varlists())
6953     Record.AddStmt(VE);
6954 }
6955 
6956 void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
6957   VisitOMPClauseWithPreInit(C);
6958   Record.AddStmt(C->getNumTeams());
6959   Record.AddSourceLocation(C->getLParenLoc());
6960 }
6961 
6962 void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
6963   VisitOMPClauseWithPreInit(C);
6964   Record.AddStmt(C->getThreadLimit());
6965   Record.AddSourceLocation(C->getLParenLoc());
6966 }
6967 
6968 void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
6969   Record.AddStmt(C->getPriority());
6970   Record.AddSourceLocation(C->getLParenLoc());
6971 }
6972 
6973 void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
6974   Record.AddStmt(C->getGrainsize());
6975   Record.AddSourceLocation(C->getLParenLoc());
6976 }
6977 
6978 void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
6979   Record.AddStmt(C->getNumTasks());
6980   Record.AddSourceLocation(C->getLParenLoc());
6981 }
6982 
6983 void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
6984   Record.AddStmt(C->getHint());
6985   Record.AddSourceLocation(C->getLParenLoc());
6986 }
6987 
6988 void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
6989   VisitOMPClauseWithPreInit(C);
6990   Record.push_back(C->getDistScheduleKind());
6991   Record.AddStmt(C->getChunkSize());
6992   Record.AddSourceLocation(C->getLParenLoc());
6993   Record.AddSourceLocation(C->getDistScheduleKindLoc());
6994   Record.AddSourceLocation(C->getCommaLoc());
6995 }
6996 
6997 void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
6998   Record.push_back(C->getDefaultmapKind());
6999   Record.push_back(C->getDefaultmapModifier());
7000   Record.AddSourceLocation(C->getLParenLoc());
7001   Record.AddSourceLocation(C->getDefaultmapModifierLoc());
7002   Record.AddSourceLocation(C->getDefaultmapKindLoc());
7003 }
7004 
7005 void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
7006   Record.push_back(C->varlist_size());
7007   Record.push_back(C->getUniqueDeclarationsNum());
7008   Record.push_back(C->getTotalComponentListNum());
7009   Record.push_back(C->getTotalComponentsNum());
7010   Record.AddSourceLocation(C->getLParenLoc());
7011   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
7012   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
7013   for (auto *E : C->varlists())
7014     Record.AddStmt(E);
7015   for (auto *E : C->mapperlists())
7016     Record.AddStmt(E);
7017   for (auto *D : C->all_decls())
7018     Record.AddDeclRef(D);
7019   for (auto N : C->all_num_lists())
7020     Record.push_back(N);
7021   for (auto N : C->all_lists_sizes())
7022     Record.push_back(N);
7023   for (auto &M : C->all_components()) {
7024     Record.AddStmt(M.getAssociatedExpression());
7025     Record.AddDeclRef(M.getAssociatedDeclaration());
7026   }
7027 }
7028 
7029 void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
7030   Record.push_back(C->varlist_size());
7031   Record.push_back(C->getUniqueDeclarationsNum());
7032   Record.push_back(C->getTotalComponentListNum());
7033   Record.push_back(C->getTotalComponentsNum());
7034   Record.AddSourceLocation(C->getLParenLoc());
7035   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
7036   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
7037   for (auto *E : C->varlists())
7038     Record.AddStmt(E);
7039   for (auto *E : C->mapperlists())
7040     Record.AddStmt(E);
7041   for (auto *D : C->all_decls())
7042     Record.AddDeclRef(D);
7043   for (auto N : C->all_num_lists())
7044     Record.push_back(N);
7045   for (auto N : C->all_lists_sizes())
7046     Record.push_back(N);
7047   for (auto &M : C->all_components()) {
7048     Record.AddStmt(M.getAssociatedExpression());
7049     Record.AddDeclRef(M.getAssociatedDeclaration());
7050   }
7051 }
7052 
7053 void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
7054   Record.push_back(C->varlist_size());
7055   Record.push_back(C->getUniqueDeclarationsNum());
7056   Record.push_back(C->getTotalComponentListNum());
7057   Record.push_back(C->getTotalComponentsNum());
7058   Record.AddSourceLocation(C->getLParenLoc());
7059   for (auto *E : C->varlists())
7060     Record.AddStmt(E);
7061   for (auto *VE : C->private_copies())
7062     Record.AddStmt(VE);
7063   for (auto *VE : C->inits())
7064     Record.AddStmt(VE);
7065   for (auto *D : C->all_decls())
7066     Record.AddDeclRef(D);
7067   for (auto N : C->all_num_lists())
7068     Record.push_back(N);
7069   for (auto N : C->all_lists_sizes())
7070     Record.push_back(N);
7071   for (auto &M : C->all_components()) {
7072     Record.AddStmt(M.getAssociatedExpression());
7073     Record.AddDeclRef(M.getAssociatedDeclaration());
7074   }
7075 }
7076 
7077 void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
7078   Record.push_back(C->varlist_size());
7079   Record.push_back(C->getUniqueDeclarationsNum());
7080   Record.push_back(C->getTotalComponentListNum());
7081   Record.push_back(C->getTotalComponentsNum());
7082   Record.AddSourceLocation(C->getLParenLoc());
7083   for (auto *E : C->varlists())
7084     Record.AddStmt(E);
7085   for (auto *D : C->all_decls())
7086     Record.AddDeclRef(D);
7087   for (auto N : C->all_num_lists())
7088     Record.push_back(N);
7089   for (auto N : C->all_lists_sizes())
7090     Record.push_back(N);
7091   for (auto &M : C->all_components()) {
7092     Record.AddStmt(M.getAssociatedExpression());
7093     Record.AddDeclRef(M.getAssociatedDeclaration());
7094   }
7095 }
7096 
7097 void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
7098 
7099 void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
7100     OMPUnifiedSharedMemoryClause *) {}
7101 
7102 void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
7103 
7104 void
7105 OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
7106 }
7107 
7108 void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
7109     OMPAtomicDefaultMemOrderClause *C) {
7110   Record.push_back(C->getAtomicDefaultMemOrderKind());
7111   Record.AddSourceLocation(C->getLParenLoc());
7112   Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
7113 }
7114