clang  3.9.0
ASTWriter.cpp
Go to the documentation of this file.
1 //===--- ASTWriter.cpp - AST File Writer ------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ASTWriter class, which writes AST files.
11 //
12 //===----------------------------------------------------------------------===//
13 
16 #include "ASTCommon.h"
17 #include "ASTReaderInternals.h"
18 #include "MultiOnDiskHashTable.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclFriend.h"
23 #include "clang/AST/DeclLookups.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/Type.h"
34 #include "clang/Basic/TargetInfo.h"
36 #include "clang/Basic/Version.h"
38 #include "clang/Lex/HeaderSearch.h"
40 #include "clang/Lex/MacroInfo.h"
42 #include "clang/Lex/Preprocessor.h"
45 #include "clang/Sema/Sema.h"
48 #include "llvm/ADT/APFloat.h"
49 #include "llvm/ADT/APInt.h"
50 #include "llvm/ADT/Hashing.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/Bitcode/BitstreamWriter.h"
53 #include "llvm/Support/Compression.h"
54 #include "llvm/Support/EndianStream.h"
55 #include "llvm/Support/FileSystem.h"
56 #include "llvm/Support/MemoryBuffer.h"
57 #include "llvm/Support/OnDiskHashTable.h"
58 #include "llvm/Support/Path.h"
59 #include "llvm/Support/Process.h"
60 #include <algorithm>
61 #include <cstdio>
62 #include <string.h>
63 #include <utility>
64 
65 using namespace clang;
66 using namespace clang::serialization;
67 
68 template <typename T, typename Allocator>
69 static StringRef bytes(const std::vector<T, Allocator> &v) {
70  if (v.empty()) return StringRef();
71  return StringRef(reinterpret_cast<const char*>(&v[0]),
72  sizeof(T) * v.size());
73 }
74 
75 template <typename T>
76 static StringRef bytes(const SmallVectorImpl<T> &v) {
77  return StringRef(reinterpret_cast<const char*>(v.data()),
78  sizeof(T) * v.size());
79 }
80 
81 //===----------------------------------------------------------------------===//
82 // Type serialization
83 //===----------------------------------------------------------------------===//
84 
85 namespace clang {
86  class ASTTypeWriter {
87  ASTWriter &Writer;
88  ASTRecordWriter Record;
89 
90  /// \brief Type code that corresponds to the record generated.
91  TypeCode Code;
92  /// \brief Abbreviation to use for the record, if any.
93  unsigned AbbrevToUse;
94 
95  public:
97  : Writer(Writer), Record(Writer, Record), Code((TypeCode)0), AbbrevToUse(0) { }
98 
99  uint64_t Emit() {
100  return Record.Emit(Code, AbbrevToUse);
101  }
102 
103  void Visit(QualType T) {
104  if (T.hasLocalNonFastQualifiers()) {
106  Record.AddTypeRef(T.getLocalUnqualifiedType());
107  Record.push_back(Qs.getAsOpaqueValue());
108  Code = TYPE_EXT_QUAL;
109  AbbrevToUse = Writer.TypeExtQualAbbrev;
110  } else {
111  switch (T->getTypeClass()) {
112  // For all of the concrete, non-dependent types, call the
113  // appropriate visitor function.
114 #define TYPE(Class, Base) \
115  case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
116 #define ABSTRACT_TYPE(Class, Base)
117 #include "clang/AST/TypeNodes.def"
118  }
119  }
120  }
121 
122  void VisitArrayType(const ArrayType *T);
123  void VisitFunctionType(const FunctionType *T);
124  void VisitTagType(const TagType *T);
125 
126 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
127 #define ABSTRACT_TYPE(Class, Base)
128 #include "clang/AST/TypeNodes.def"
129  };
130 } // end namespace clang
131 
132 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
133  llvm_unreachable("Built-in types are never serialized");
134 }
135 
136 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
137  Record.AddTypeRef(T->getElementType());
138  Code = TYPE_COMPLEX;
139 }
140 
141 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
142  Record.AddTypeRef(T->getPointeeType());
143  Code = TYPE_POINTER;
144 }
145 
146 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
147  Record.AddTypeRef(T->getOriginalType());
148  Code = TYPE_DECAYED;
149 }
150 
151 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
152  Record.AddTypeRef(T->getOriginalType());
153  Record.AddTypeRef(T->getAdjustedType());
154  Code = TYPE_ADJUSTED;
155 }
156 
157 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
158  Record.AddTypeRef(T->getPointeeType());
159  Code = TYPE_BLOCK_POINTER;
160 }
161 
162 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
163  Record.AddTypeRef(T->getPointeeTypeAsWritten());
164  Record.push_back(T->isSpelledAsLValue());
165  Code = TYPE_LVALUE_REFERENCE;
166 }
167 
168 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
169  Record.AddTypeRef(T->getPointeeTypeAsWritten());
170  Code = TYPE_RVALUE_REFERENCE;
171 }
172 
173 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
174  Record.AddTypeRef(T->getPointeeType());
175  Record.AddTypeRef(QualType(T->getClass(), 0));
176  Code = TYPE_MEMBER_POINTER;
177 }
178 
180  Record.AddTypeRef(T->getElementType());
181  Record.push_back(T->getSizeModifier()); // FIXME: stable values
182  Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
183 }
184 
185 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
186  VisitArrayType(T);
187  Record.AddAPInt(T->getSize());
188  Code = TYPE_CONSTANT_ARRAY;
189 }
190 
191 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
192  VisitArrayType(T);
193  Code = TYPE_INCOMPLETE_ARRAY;
194 }
195 
196 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
197  VisitArrayType(T);
198  Record.AddSourceLocation(T->getLBracketLoc());
199  Record.AddSourceLocation(T->getRBracketLoc());
200  Record.AddStmt(T->getSizeExpr());
201  Code = TYPE_VARIABLE_ARRAY;
202 }
203 
204 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
205  Record.AddTypeRef(T->getElementType());
206  Record.push_back(T->getNumElements());
207  Record.push_back(T->getVectorKind());
208  Code = TYPE_VECTOR;
209 }
210 
211 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
212  VisitVectorType(T);
213  Code = TYPE_EXT_VECTOR;
214 }
215 
217  Record.AddTypeRef(T->getReturnType());
219  Record.push_back(C.getNoReturn());
220  Record.push_back(C.getHasRegParm());
221  Record.push_back(C.getRegParm());
222  // FIXME: need to stabilize encoding of calling convention...
223  Record.push_back(C.getCC());
224  Record.push_back(C.getProducesResult());
225 
226  if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
227  AbbrevToUse = 0;
228 }
229 
230 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
231  VisitFunctionType(T);
232  Code = TYPE_FUNCTION_NO_PROTO;
233 }
234 
235 static void addExceptionSpec(const FunctionProtoType *T,
236  ASTRecordWriter &Record) {
237  Record.push_back(T->getExceptionSpecType());
238  if (T->getExceptionSpecType() == EST_Dynamic) {
239  Record.push_back(T->getNumExceptions());
240  for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
241  Record.AddTypeRef(T->getExceptionType(I));
242  } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
243  Record.AddStmt(T->getNoexceptExpr());
244  } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
245  Record.AddDeclRef(T->getExceptionSpecDecl());
247  } else if (T->getExceptionSpecType() == EST_Unevaluated) {
248  Record.AddDeclRef(T->getExceptionSpecDecl());
249  }
250 }
251 
252 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
253  VisitFunctionType(T);
254 
255  Record.push_back(T->isVariadic());
256  Record.push_back(T->hasTrailingReturn());
257  Record.push_back(T->getTypeQuals());
258  Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
259  addExceptionSpec(T, Record);
260 
261  Record.push_back(T->getNumParams());
262  for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
263  Record.AddTypeRef(T->getParamType(I));
264 
265  if (T->hasExtParameterInfos()) {
266  for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
267  Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
268  }
269 
270  if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
273  AbbrevToUse = 0;
274 
275  Code = TYPE_FUNCTION_PROTO;
276 }
277 
278 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
279  Record.AddDeclRef(T->getDecl());
280  Code = TYPE_UNRESOLVED_USING;
281 }
282 
283 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
284  Record.AddDeclRef(T->getDecl());
285  assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
286  Record.AddTypeRef(T->getCanonicalTypeInternal());
287  Code = TYPE_TYPEDEF;
288 }
289 
290 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
291  Record.AddStmt(T->getUnderlyingExpr());
292  Code = TYPE_TYPEOF_EXPR;
293 }
294 
295 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
296  Record.AddTypeRef(T->getUnderlyingType());
297  Code = TYPE_TYPEOF;
298 }
299 
300 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
301  Record.AddTypeRef(T->getUnderlyingType());
302  Record.AddStmt(T->getUnderlyingExpr());
303  Code = TYPE_DECLTYPE;
304 }
305 
306 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
307  Record.AddTypeRef(T->getBaseType());
308  Record.AddTypeRef(T->getUnderlyingType());
309  Record.push_back(T->getUTTKind());
310  Code = TYPE_UNARY_TRANSFORM;
311 }
312 
313 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
314  Record.AddTypeRef(T->getDeducedType());
315  Record.push_back((unsigned)T->getKeyword());
316  if (T->getDeducedType().isNull())
317  Record.push_back(T->isDependentType());
318  Code = TYPE_AUTO;
319 }
320 
322  Record.push_back(T->isDependentType());
323  Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
324  assert(!T->isBeingDefined() &&
325  "Cannot serialize in the middle of a type definition");
326 }
327 
328 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
329  VisitTagType(T);
330  Code = TYPE_RECORD;
331 }
332 
333 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
334  VisitTagType(T);
335  Code = TYPE_ENUM;
336 }
337 
338 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
339  Record.AddTypeRef(T->getModifiedType());
340  Record.AddTypeRef(T->getEquivalentType());
341  Record.push_back(T->getAttrKind());
342  Code = TYPE_ATTRIBUTED;
343 }
344 
345 void
346 ASTTypeWriter::VisitSubstTemplateTypeParmType(
347  const SubstTemplateTypeParmType *T) {
348  Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
349  Record.AddTypeRef(T->getReplacementType());
351 }
352 
353 void
354 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
356  Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
357  Record.AddTemplateArgument(T->getArgumentPack());
359 }
360 
361 void
362 ASTTypeWriter::VisitTemplateSpecializationType(
363  const TemplateSpecializationType *T) {
364  Record.push_back(T->isDependentType());
365  Record.AddTemplateName(T->getTemplateName());
366  Record.push_back(T->getNumArgs());
367  for (const auto &ArgI : *T)
368  Record.AddTemplateArgument(ArgI);
369  Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
370  : T->isCanonicalUnqualified()
371  ? QualType()
372  : T->getCanonicalTypeInternal());
374 }
375 
376 void
377 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
378  VisitArrayType(T);
379  Record.AddStmt(T->getSizeExpr());
380  Record.AddSourceRange(T->getBracketsRange());
382 }
383 
384 void
385 ASTTypeWriter::VisitDependentSizedExtVectorType(
386  const DependentSizedExtVectorType *T) {
387  // FIXME: Serialize this type (C++ only)
388  llvm_unreachable("Cannot serialize dependent sized extended vector types");
389 }
390 
391 void
392 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
393  Record.push_back(T->getDepth());
394  Record.push_back(T->getIndex());
395  Record.push_back(T->isParameterPack());
396  Record.AddDeclRef(T->getDecl());
398 }
399 
400 void
401 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
402  Record.push_back(T->getKeyword());
403  Record.AddNestedNameSpecifier(T->getQualifier());
404  Record.AddIdentifierRef(T->getIdentifier());
405  Record.AddTypeRef(
406  T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
407  Code = TYPE_DEPENDENT_NAME;
408 }
409 
410 void
411 ASTTypeWriter::VisitDependentTemplateSpecializationType(
413  Record.push_back(T->getKeyword());
414  Record.AddNestedNameSpecifier(T->getQualifier());
415  Record.AddIdentifierRef(T->getIdentifier());
416  Record.push_back(T->getNumArgs());
417  for (const auto &I : *T)
418  Record.AddTemplateArgument(I);
420 }
421 
422 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
423  Record.AddTypeRef(T->getPattern());
424  if (Optional<unsigned> NumExpansions = T->getNumExpansions())
425  Record.push_back(*NumExpansions + 1);
426  else
427  Record.push_back(0);
428  Code = TYPE_PACK_EXPANSION;
429 }
430 
431 void ASTTypeWriter::VisitParenType(const ParenType *T) {
432  Record.AddTypeRef(T->getInnerType());
433  Code = TYPE_PAREN;
434 }
435 
436 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
437  Record.push_back(T->getKeyword());
438  Record.AddNestedNameSpecifier(T->getQualifier());
439  Record.AddTypeRef(T->getNamedType());
440  Code = TYPE_ELABORATED;
441 }
442 
443 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
444  Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
445  Record.AddTypeRef(T->getInjectedSpecializationType());
447 }
448 
449 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
450  Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
451  Code = TYPE_OBJC_INTERFACE;
452 }
453 
454 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
455  Record.AddTypeRef(T->getBaseType());
456  Record.push_back(T->getTypeArgsAsWritten().size());
457  for (auto TypeArg : T->getTypeArgsAsWritten())
458  Record.AddTypeRef(TypeArg);
459  Record.push_back(T->getNumProtocols());
460  for (const auto *I : T->quals())
461  Record.AddDeclRef(I);
462  Record.push_back(T->isKindOfTypeAsWritten());
463  Code = TYPE_OBJC_OBJECT;
464 }
465 
466 void
467 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
468  Record.AddTypeRef(T->getPointeeType());
470 }
471 
472 void
473 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
474  Record.AddTypeRef(T->getValueType());
475  Code = TYPE_ATOMIC;
476 }
477 
478 void
479 ASTTypeWriter::VisitPipeType(const PipeType *T) {
480  Record.AddTypeRef(T->getElementType());
481  Code = TYPE_PIPE;
482 }
483 
484 namespace {
485 
486 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
487  ASTRecordWriter &Record;
488 
489 public:
490  TypeLocWriter(ASTRecordWriter &Record)
491  : Record(Record) { }
492 
493 #define ABSTRACT_TYPELOC(CLASS, PARENT)
494 #define TYPELOC(CLASS, PARENT) \
495  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
496 #include "clang/AST/TypeLocNodes.def"
497 
498  void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
499  void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
500 };
501 
502 } // end anonymous namespace
503 
504 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
505  // nothing to do
506 }
507 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
508  Record.AddSourceLocation(TL.getBuiltinLoc());
509  if (TL.needsExtraLocalData()) {
510  Record.push_back(TL.getWrittenTypeSpec());
511  Record.push_back(TL.getWrittenSignSpec());
512  Record.push_back(TL.getWrittenWidthSpec());
513  Record.push_back(TL.hasModeAttr());
514  }
515 }
516 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
517  Record.AddSourceLocation(TL.getNameLoc());
518 }
519 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
520  Record.AddSourceLocation(TL.getStarLoc());
521 }
522 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
523  // nothing to do
524 }
525 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
526  // nothing to do
527 }
528 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
529  Record.AddSourceLocation(TL.getCaretLoc());
530 }
531 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
532  Record.AddSourceLocation(TL.getAmpLoc());
533 }
534 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
535  Record.AddSourceLocation(TL.getAmpAmpLoc());
536 }
537 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
538  Record.AddSourceLocation(TL.getStarLoc());
539  Record.AddTypeSourceInfo(TL.getClassTInfo());
540 }
541 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
542  Record.AddSourceLocation(TL.getLBracketLoc());
543  Record.AddSourceLocation(TL.getRBracketLoc());
544  Record.push_back(TL.getSizeExpr() ? 1 : 0);
545  if (TL.getSizeExpr())
546  Record.AddStmt(TL.getSizeExpr());
547 }
548 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
549  VisitArrayTypeLoc(TL);
550 }
551 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
552  VisitArrayTypeLoc(TL);
553 }
554 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
555  VisitArrayTypeLoc(TL);
556 }
557 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
559  VisitArrayTypeLoc(TL);
560 }
561 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
563  Record.AddSourceLocation(TL.getNameLoc());
564 }
565 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
566  Record.AddSourceLocation(TL.getNameLoc());
567 }
568 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
569  Record.AddSourceLocation(TL.getNameLoc());
570 }
571 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
572  Record.AddSourceLocation(TL.getLocalRangeBegin());
573  Record.AddSourceLocation(TL.getLParenLoc());
574  Record.AddSourceLocation(TL.getRParenLoc());
575  Record.AddSourceLocation(TL.getLocalRangeEnd());
576  for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
577  Record.AddDeclRef(TL.getParam(i));
578 }
579 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
580  VisitFunctionTypeLoc(TL);
581 }
582 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
583  VisitFunctionTypeLoc(TL);
584 }
585 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
586  Record.AddSourceLocation(TL.getNameLoc());
587 }
588 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
589  Record.AddSourceLocation(TL.getNameLoc());
590 }
591 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
592  Record.AddSourceLocation(TL.getTypeofLoc());
593  Record.AddSourceLocation(TL.getLParenLoc());
594  Record.AddSourceLocation(TL.getRParenLoc());
595 }
596 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
597  Record.AddSourceLocation(TL.getTypeofLoc());
598  Record.AddSourceLocation(TL.getLParenLoc());
599  Record.AddSourceLocation(TL.getRParenLoc());
600  Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
601 }
602 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
603  Record.AddSourceLocation(TL.getNameLoc());
604 }
605 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
606  Record.AddSourceLocation(TL.getKWLoc());
607  Record.AddSourceLocation(TL.getLParenLoc());
608  Record.AddSourceLocation(TL.getRParenLoc());
609  Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
610 }
611 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
612  Record.AddSourceLocation(TL.getNameLoc());
613 }
614 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
615  Record.AddSourceLocation(TL.getNameLoc());
616 }
617 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
618  Record.AddSourceLocation(TL.getNameLoc());
619 }
620 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
621  Record.AddSourceLocation(TL.getAttrNameLoc());
622  if (TL.hasAttrOperand()) {
624  Record.AddSourceLocation(range.getBegin());
625  Record.AddSourceLocation(range.getEnd());
626  }
627  if (TL.hasAttrExprOperand()) {
628  Expr *operand = TL.getAttrExprOperand();
629  Record.push_back(operand ? 1 : 0);
630  if (operand) Record.AddStmt(operand);
631  } else if (TL.hasAttrEnumOperand()) {
632  Record.AddSourceLocation(TL.getAttrEnumOperandLoc());
633  }
634 }
635 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
636  Record.AddSourceLocation(TL.getNameLoc());
637 }
638 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
640  Record.AddSourceLocation(TL.getNameLoc());
641 }
642 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
644  Record.AddSourceLocation(TL.getNameLoc());
645 }
646 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
648  Record.AddSourceLocation(TL.getTemplateKeywordLoc());
649  Record.AddSourceLocation(TL.getTemplateNameLoc());
650  Record.AddSourceLocation(TL.getLAngleLoc());
651  Record.AddSourceLocation(TL.getRAngleLoc());
652  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
653  Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
654  TL.getArgLoc(i).getLocInfo());
655 }
656 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
657  Record.AddSourceLocation(TL.getLParenLoc());
658  Record.AddSourceLocation(TL.getRParenLoc());
659 }
660 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
661  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
662  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
663 }
664 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
665  Record.AddSourceLocation(TL.getNameLoc());
666 }
667 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
668  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
669  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
670  Record.AddSourceLocation(TL.getNameLoc());
671 }
672 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
674  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
675  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
676  Record.AddSourceLocation(TL.getTemplateKeywordLoc());
677  Record.AddSourceLocation(TL.getTemplateNameLoc());
678  Record.AddSourceLocation(TL.getLAngleLoc());
679  Record.AddSourceLocation(TL.getRAngleLoc());
680  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
681  Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
682  TL.getArgLoc(I).getLocInfo());
683 }
684 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
685  Record.AddSourceLocation(TL.getEllipsisLoc());
686 }
687 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
688  Record.AddSourceLocation(TL.getNameLoc());
689 }
690 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
691  Record.push_back(TL.hasBaseTypeAsWritten());
692  Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
693  Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
694  for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
695  Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
696  Record.AddSourceLocation(TL.getProtocolLAngleLoc());
697  Record.AddSourceLocation(TL.getProtocolRAngleLoc());
698  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
699  Record.AddSourceLocation(TL.getProtocolLoc(i));
700 }
701 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
702  Record.AddSourceLocation(TL.getStarLoc());
703 }
704 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
705  Record.AddSourceLocation(TL.getKWLoc());
706  Record.AddSourceLocation(TL.getLParenLoc());
707  Record.AddSourceLocation(TL.getRParenLoc());
708 }
709 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
710  Record.AddSourceLocation(TL.getKWLoc());
711 }
712 
713 void ASTWriter::WriteTypeAbbrevs() {
714  using namespace llvm;
715 
716  BitCodeAbbrev *Abv;
717 
718  // Abbreviation for TYPE_EXT_QUAL
719  Abv = new BitCodeAbbrev();
720  Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
721  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
722  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
723  TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
724 
725  // Abbreviation for TYPE_FUNCTION_PROTO
726  Abv = new BitCodeAbbrev();
727  Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
728  // FunctionType
729  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
730  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
731  Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
732  Abv->Add(BitCodeAbbrevOp(0)); // RegParm
733  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
734  Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
735  // FunctionProtoType
736  Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
737  Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
738  Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
739  Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
740  Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
741  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
742  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
743  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
744  TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
745 }
746 
747 //===----------------------------------------------------------------------===//
748 // ASTWriter Implementation
749 //===----------------------------------------------------------------------===//
750 
751 static void EmitBlockID(unsigned ID, const char *Name,
752  llvm::BitstreamWriter &Stream,
753  ASTWriter::RecordDataImpl &Record) {
754  Record.clear();
755  Record.push_back(ID);
756  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
757 
758  // Emit the block name if present.
759  if (!Name || Name[0] == 0)
760  return;
761  Record.clear();
762  while (*Name)
763  Record.push_back(*Name++);
764  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
765 }
766 
767 static void EmitRecordID(unsigned ID, const char *Name,
768  llvm::BitstreamWriter &Stream,
769  ASTWriter::RecordDataImpl &Record) {
770  Record.clear();
771  Record.push_back(ID);
772  while (*Name)
773  Record.push_back(*Name++);
774  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
775 }
776 
777 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
778  ASTWriter::RecordDataImpl &Record) {
779 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
780  RECORD(STMT_STOP);
783  RECORD(STMT_NULL);
785  RECORD(STMT_CASE);
789  RECORD(STMT_IF);
792  RECORD(STMT_DO);
793  RECORD(STMT_FOR);
794  RECORD(STMT_GOTO);
799  RECORD(STMT_DECL);
814  RECORD(EXPR_CALL);
830  RECORD(EXPR_STMT);
903 #undef RECORD
904 }
905 
906 void ASTWriter::WriteBlockInfoBlock() {
907  RecordData Record;
908  Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
909 
910 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
911 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
912 
913  // Control Block.
914  BLOCK(CONTROL_BLOCK);
915  RECORD(METADATA);
916  RECORD(SIGNATURE);
920  RECORD(IMPORTS);
925 
926  BLOCK(OPTIONS_BLOCK);
933 
934  BLOCK(INPUT_FILES_BLOCK);
936 
937  // AST Top-Level Block.
938  BLOCK(AST_BLOCK);
986 
987  // SourceManager Block.
988  BLOCK(SOURCE_MANAGER_BLOCK);
994 
995  // Preprocessor Block.
996  BLOCK(PREPROCESSOR_BLOCK);
1001  RECORD(PP_TOKEN);
1002 
1003  // Submodule Block.
1004  BLOCK(SUBMODULE_BLOCK);
1021 
1022  // Comments Block.
1023  BLOCK(COMMENTS_BLOCK);
1025 
1026  // Decls and Types block.
1027  BLOCK(DECLTYPES_BLOCK);
1046  RECORD(TYPE_ENUM);
1060  RECORD(TYPE_PAREN);
1064  RECORD(TYPE_AUTO);
1072  RECORD(DECL_ENUM);
1087  RECORD(DECL_FIELD);
1089  RECORD(DECL_VAR);
1093  RECORD(DECL_BLOCK);
1098  RECORD(DECL_USING);
1133  RECORD(DECL_EMPTY);
1139 
1140  // Statements and Exprs can occur in the Decls and Types block.
1141  AddStmtsExprs(Stream, Record);
1142 
1143  BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1147 
1148  // Decls and Types block.
1149  BLOCK(EXTENSION_BLOCK);
1151 
1152 #undef RECORD
1153 #undef BLOCK
1154  Stream.ExitBlock();
1155 }
1156 
1157 /// \brief Prepares a path for being written to an AST file by converting it
1158 /// to an absolute path and removing nested './'s.
1159 ///
1160 /// \return \c true if the path was changed.
1161 static bool cleanPathForOutput(FileManager &FileMgr,
1162  SmallVectorImpl<char> &Path) {
1163  bool Changed = FileMgr.makeAbsolutePath(Path);
1164  return Changed | llvm::sys::path::remove_dots(Path);
1165 }
1166 
1167 /// \brief Adjusts the given filename to only write out the portion of the
1168 /// filename that is not part of the system root directory.
1169 ///
1170 /// \param Filename the file name to adjust.
1171 ///
1172 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1173 /// the returned filename will be adjusted by this root directory.
1174 ///
1175 /// \returns either the original filename (if it needs no adjustment) or the
1176 /// adjusted filename (which points into the @p Filename parameter).
1177 static const char *
1178 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1179  assert(Filename && "No file name to adjust?");
1180 
1181  if (BaseDir.empty())
1182  return Filename;
1183 
1184  // Verify that the filename and the system root have the same prefix.
1185  unsigned Pos = 0;
1186  for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1187  if (Filename[Pos] != BaseDir[Pos])
1188  return Filename; // Prefixes don't match.
1189 
1190  // We hit the end of the filename before we hit the end of the system root.
1191  if (!Filename[Pos])
1192  return Filename;
1193 
1194  // If there's not a path separator at the end of the base directory nor
1195  // immediately after it, then this isn't within the base directory.
1196  if (!llvm::sys::path::is_separator(Filename[Pos])) {
1197  if (!llvm::sys::path::is_separator(BaseDir.back()))
1198  return Filename;
1199  } else {
1200  // If the file name has a '/' at the current position, skip over the '/'.
1201  // We distinguish relative paths from absolute paths by the
1202  // absence of '/' at the beginning of relative paths.
1203  //
1204  // FIXME: This is wrong. We distinguish them by asking if the path is
1205  // absolute, which isn't the same thing. And there might be multiple '/'s
1206  // in a row. Use a better mechanism to indicate whether we have emitted an
1207  // absolute or relative path.
1208  ++Pos;
1209  }
1210 
1211  return Filename + Pos;
1212 }
1213 
1215  while (1) {
1216  if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1217  return S;
1218  // Rely on GetRandomNumber to eventually return non-zero...
1219  }
1220 }
1221 
1222 /// \brief Write the control block.
1223 uint64_t ASTWriter::WriteControlBlock(Preprocessor &PP,
1225  StringRef isysroot,
1226  const std::string &OutputFile) {
1227  ASTFileSignature Signature = 0;
1228 
1229  using namespace llvm;
1230  Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1231  RecordData Record;
1232 
1233  // Metadata
1234  auto *MetadataAbbrev = new BitCodeAbbrev();
1235  MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1236  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1237  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1238  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1239  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1240  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1241  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1242  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1243  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1244  unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
1245  assert((!WritingModule || isysroot.empty()) &&
1246  "writing module as a relocatable PCH?");
1247  {
1248  RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1249  CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1250  !isysroot.empty(), IncludeTimestamps,
1251  ASTHasCompilerErrors};
1252  Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1254  }
1255  if (WritingModule) {
1256  // For implicit modules we output a signature that we can use to ensure
1257  // duplicate module builds don't collide in the cache as their output order
1258  // is non-deterministic.
1259  // FIXME: Remove this when output is deterministic.
1260  if (Context.getLangOpts().ImplicitModules) {
1261  Signature = getSignature();
1262  RecordData::value_type Record[] = {Signature};
1263  Stream.EmitRecord(SIGNATURE, Record);
1264  }
1265 
1266  // Module name
1267  auto *Abbrev = new BitCodeAbbrev();
1268  Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1269  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1270  unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1271  RecordData::value_type Record[] = {MODULE_NAME};
1272  Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1273  }
1274 
1275  if (WritingModule && WritingModule->Directory) {
1276  SmallString<128> BaseDir(WritingModule->Directory->getName());
1277  cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1278 
1279  // If the home of the module is the current working directory, then we
1280  // want to pick up the cwd of the build process loading the module, not
1281  // our cwd, when we load this module.
1282  if (!PP.getHeaderSearchInfo()
1285  WritingModule->Directory->getName() != StringRef(".")) {
1286  // Module directory.
1287  auto *Abbrev = new BitCodeAbbrev();
1288  Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1289  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1290  unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1291 
1292  RecordData::value_type Record[] = {MODULE_DIRECTORY};
1293  Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1294  }
1295 
1296  // Write out all other paths relative to the base directory if possible.
1297  BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1298  } else if (!isysroot.empty()) {
1299  // Write out paths relative to the sysroot if possible.
1300  BaseDirectory = isysroot;
1301  }
1302 
1303  // Module map file
1304  if (WritingModule) {
1305  Record.clear();
1306 
1307  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1308 
1309  // Primary module map file.
1310  AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
1311 
1312  // Additional module map files.
1313  if (auto *AdditionalModMaps =
1314  Map.getAdditionalModuleMapFiles(WritingModule)) {
1315  Record.push_back(AdditionalModMaps->size());
1316  for (const FileEntry *F : *AdditionalModMaps)
1317  AddPath(F->getName(), Record);
1318  } else {
1319  Record.push_back(0);
1320  }
1321 
1322  Stream.EmitRecord(MODULE_MAP_FILE, Record);
1323  }
1324 
1325  // Imports
1326  if (Chain) {
1327  serialization::ModuleManager &Mgr = Chain->getModuleManager();
1328  Record.clear();
1329 
1330  for (auto *M : Mgr) {
1331  // Skip modules that weren't directly imported.
1332  if (!M->isDirectlyImported())
1333  continue;
1334 
1335  Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1336  AddSourceLocation(M->ImportLoc, Record);
1337  Record.push_back(M->File->getSize());
1338  Record.push_back(getTimestampForOutput(M->File));
1339  Record.push_back(M->Signature);
1340  AddPath(M->FileName, Record);
1341  }
1342  Stream.EmitRecord(IMPORTS, Record);
1343  }
1344 
1345  // Write the options block.
1346  Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1347 
1348  // Language options.
1349  Record.clear();
1350  const LangOptions &LangOpts = Context.getLangOpts();
1351 #define LANGOPT(Name, Bits, Default, Description) \
1352  Record.push_back(LangOpts.Name);
1353 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1354  Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1355 #include "clang/Basic/LangOptions.def"
1356 #define SANITIZER(NAME, ID) \
1357  Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1358 #include "clang/Basic/Sanitizers.def"
1359 
1360  Record.push_back(LangOpts.ModuleFeatures.size());
1361  for (StringRef Feature : LangOpts.ModuleFeatures)
1362  AddString(Feature, Record);
1363 
1364  Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1365  AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1366 
1367  AddString(LangOpts.CurrentModule, Record);
1368 
1369  // Comment options.
1370  Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1371  for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1372  AddString(I, Record);
1373  }
1374  Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1375 
1376  // OpenMP offloading options.
1377  Record.push_back(LangOpts.OMPTargetTriples.size());
1378  for (auto &T : LangOpts.OMPTargetTriples)
1379  AddString(T.getTriple(), Record);
1380 
1381  AddString(LangOpts.OMPHostIRFile, Record);
1382 
1383  Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1384 
1385  // Target options.
1386  Record.clear();
1387  const TargetInfo &Target = Context.getTargetInfo();
1388  const TargetOptions &TargetOpts = Target.getTargetOpts();
1389  AddString(TargetOpts.Triple, Record);
1390  AddString(TargetOpts.CPU, Record);
1391  AddString(TargetOpts.ABI, Record);
1392  Record.push_back(TargetOpts.FeaturesAsWritten.size());
1393  for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1394  AddString(TargetOpts.FeaturesAsWritten[I], Record);
1395  }
1396  Record.push_back(TargetOpts.Features.size());
1397  for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1398  AddString(TargetOpts.Features[I], Record);
1399  }
1400  Stream.EmitRecord(TARGET_OPTIONS, Record);
1401 
1402  // Diagnostic options.
1403  Record.clear();
1404  const DiagnosticOptions &DiagOpts
1405  = Context.getDiagnostics().getDiagnosticOptions();
1406 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1407 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1408  Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1409 #include "clang/Basic/DiagnosticOptions.def"
1410  Record.push_back(DiagOpts.Warnings.size());
1411  for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1412  AddString(DiagOpts.Warnings[I], Record);
1413  Record.push_back(DiagOpts.Remarks.size());
1414  for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1415  AddString(DiagOpts.Remarks[I], Record);
1416  // Note: we don't serialize the log or serialization file names, because they
1417  // are generally transient files and will almost always be overridden.
1418  Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1419 
1420  // File system options.
1421  Record.clear();
1422  const FileSystemOptions &FSOpts =
1424  AddString(FSOpts.WorkingDir, Record);
1425  Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1426 
1427  // Header search options.
1428  Record.clear();
1429  const HeaderSearchOptions &HSOpts
1431  AddString(HSOpts.Sysroot, Record);
1432 
1433  // Include entries.
1434  Record.push_back(HSOpts.UserEntries.size());
1435  for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1436  const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1437  AddString(Entry.Path, Record);
1438  Record.push_back(static_cast<unsigned>(Entry.Group));
1439  Record.push_back(Entry.IsFramework);
1440  Record.push_back(Entry.IgnoreSysRoot);
1441  }
1442 
1443  // System header prefixes.
1444  Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1445  for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1446  AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1447  Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1448  }
1449 
1450  AddString(HSOpts.ResourceDir, Record);
1451  AddString(HSOpts.ModuleCachePath, Record);
1452  AddString(HSOpts.ModuleUserBuildPath, Record);
1453  Record.push_back(HSOpts.DisableModuleHash);
1454  Record.push_back(HSOpts.UseBuiltinIncludes);
1455  Record.push_back(HSOpts.UseStandardSystemIncludes);
1456  Record.push_back(HSOpts.UseStandardCXXIncludes);
1457  Record.push_back(HSOpts.UseLibcxx);
1458  // Write out the specific module cache path that contains the module files.
1459  AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1460  Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1461 
1462  // Preprocessor options.
1463  Record.clear();
1464  const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1465 
1466  // Macro definitions.
1467  Record.push_back(PPOpts.Macros.size());
1468  for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1469  AddString(PPOpts.Macros[I].first, Record);
1470  Record.push_back(PPOpts.Macros[I].second);
1471  }
1472 
1473  // Includes
1474  Record.push_back(PPOpts.Includes.size());
1475  for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1476  AddString(PPOpts.Includes[I], Record);
1477 
1478  // Macro includes
1479  Record.push_back(PPOpts.MacroIncludes.size());
1480  for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1481  AddString(PPOpts.MacroIncludes[I], Record);
1482 
1483  Record.push_back(PPOpts.UsePredefines);
1484  // Detailed record is important since it is used for the module cache hash.
1485  Record.push_back(PPOpts.DetailedRecord);
1486  AddString(PPOpts.ImplicitPCHInclude, Record);
1487  AddString(PPOpts.ImplicitPTHInclude, Record);
1488  Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1489  Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1490 
1491  // Leave the options block.
1492  Stream.ExitBlock();
1493 
1494  // Original file name and file ID
1495  SourceManager &SM = Context.getSourceManager();
1496  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1497  auto *FileAbbrev = new BitCodeAbbrev();
1498  FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1499  FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1500  FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1501  unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1502 
1503  Record.clear();
1504  Record.push_back(ORIGINAL_FILE);
1505  Record.push_back(SM.getMainFileID().getOpaqueValue());
1506  EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1507  }
1508 
1509  Record.clear();
1510  Record.push_back(SM.getMainFileID().getOpaqueValue());
1511  Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1512 
1513  // Original PCH directory
1514  if (!OutputFile.empty() && OutputFile != "-") {
1515  auto *Abbrev = new BitCodeAbbrev();
1516  Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1517  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1518  unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1519 
1520  SmallString<128> OutputPath(OutputFile);
1521 
1522  SM.getFileManager().makeAbsolutePath(OutputPath);
1523  StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1524 
1525  RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1526  Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1527  }
1528 
1529  WriteInputFiles(Context.SourceMgr,
1531  PP.getLangOpts().Modules);
1532  Stream.ExitBlock();
1533  return Signature;
1534 }
1535 
1536 namespace {
1537  /// \brief An input file.
1538  struct InputFileEntry {
1539  const FileEntry *File;
1540  bool IsSystemFile;
1541  bool IsTransient;
1542  bool BufferOverridden;
1543  };
1544 } // end anonymous namespace
1545 
1546 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1547  HeaderSearchOptions &HSOpts,
1548  bool Modules) {
1549  using namespace llvm;
1550  Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1551 
1552  // Create input-file abbreviation.
1553  auto *IFAbbrev = new BitCodeAbbrev();
1554  IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1555  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1556  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1557  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1558  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1559  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1560  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1561  unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1562 
1563  // Get all ContentCache objects for files, sorted by whether the file is a
1564  // system one or not. System files go at the back, users files at the front.
1565  std::deque<InputFileEntry> SortedFiles;
1566  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1567  // Get this source location entry.
1568  const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1569  assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1570 
1571  // We only care about file entries that were not overridden.
1572  if (!SLoc->isFile())
1573  continue;
1574  const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1575  if (!Cache->OrigEntry)
1576  continue;
1577 
1578  InputFileEntry Entry;
1579  Entry.File = Cache->OrigEntry;
1580  Entry.IsSystemFile = Cache->IsSystemFile;
1581  Entry.IsTransient = Cache->IsTransient;
1582  Entry.BufferOverridden = Cache->BufferOverridden;
1583  if (Cache->IsSystemFile)
1584  SortedFiles.push_back(Entry);
1585  else
1586  SortedFiles.push_front(Entry);
1587  }
1588 
1589  unsigned UserFilesNum = 0;
1590  // Write out all of the input files.
1591  std::vector<uint64_t> InputFileOffsets;
1592  for (const auto &Entry : SortedFiles) {
1593  uint32_t &InputFileID = InputFileIDs[Entry.File];
1594  if (InputFileID != 0)
1595  continue; // already recorded this file.
1596 
1597  // Record this entry's offset.
1598  InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1599 
1600  InputFileID = InputFileOffsets.size();
1601 
1602  if (!Entry.IsSystemFile)
1603  ++UserFilesNum;
1604 
1605  // Emit size/modification time for this file.
1606  // And whether this file was overridden.
1607  RecordData::value_type Record[] = {
1608  INPUT_FILE,
1609  InputFileOffsets.size(),
1610  (uint64_t)Entry.File->getSize(),
1611  (uint64_t)getTimestampForOutput(Entry.File),
1612  Entry.BufferOverridden,
1613  Entry.IsTransient};
1614 
1615  EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1616  }
1617 
1618  Stream.ExitBlock();
1619 
1620  // Create input file offsets abbreviation.
1621  auto *OffsetsAbbrev = new BitCodeAbbrev();
1622  OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1623  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1624  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1625  // input files
1626  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1627  unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1628 
1629  // Write input file offsets.
1630  RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1631  InputFileOffsets.size(), UserFilesNum};
1632  Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1633 }
1634 
1635 //===----------------------------------------------------------------------===//
1636 // Source Manager Serialization
1637 //===----------------------------------------------------------------------===//
1638 
1639 /// \brief Create an abbreviation for the SLocEntry that refers to a
1640 /// file.
1641 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1642  using namespace llvm;
1643 
1644  auto *Abbrev = new BitCodeAbbrev();
1645  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1646  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1647  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1648  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1649  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1650  // FileEntry fields.
1651  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1652  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1653  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1654  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1655  return Stream.EmitAbbrev(Abbrev);
1656 }
1657 
1658 /// \brief Create an abbreviation for the SLocEntry that refers to a
1659 /// buffer.
1660 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1661  using namespace llvm;
1662 
1663  auto *Abbrev = new BitCodeAbbrev();
1664  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1665  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1666  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1667  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1668  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1669  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1670  return Stream.EmitAbbrev(Abbrev);
1671 }
1672 
1673 /// \brief Create an abbreviation for the SLocEntry that refers to a
1674 /// buffer's blob.
1675 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1676  bool Compressed) {
1677  using namespace llvm;
1678 
1679  auto *Abbrev = new BitCodeAbbrev();
1680  Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1681  : SM_SLOC_BUFFER_BLOB));
1682  if (Compressed)
1683  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1684  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1685  return Stream.EmitAbbrev(Abbrev);
1686 }
1687 
1688 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1689 /// expansion.
1690 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1691  using namespace llvm;
1692 
1693  auto *Abbrev = new BitCodeAbbrev();
1694  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1695  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1696  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1697  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1698  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1699  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1700  return Stream.EmitAbbrev(Abbrev);
1701 }
1702 
1703 namespace {
1704  // Trait used for the on-disk hash table of header search information.
1705  class HeaderFileInfoTrait {
1706  ASTWriter &Writer;
1707  const HeaderSearch &HS;
1708 
1709  // Keep track of the framework names we've used during serialization.
1710  SmallVector<char, 128> FrameworkStringData;
1711  llvm::StringMap<unsigned> FrameworkNameOffset;
1712 
1713  public:
1714  HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1715  : Writer(Writer), HS(HS) { }
1716 
1717  struct key_type {
1718  const FileEntry *FE;
1719  const char *Filename;
1720  };
1721  typedef const key_type &key_type_ref;
1722 
1723  typedef HeaderFileInfo data_type;
1724  typedef const data_type &data_type_ref;
1725  typedef unsigned hash_value_type;
1726  typedef unsigned offset_type;
1727 
1728  hash_value_type ComputeHash(key_type_ref key) {
1729  // The hash is based only on size/time of the file, so that the reader can
1730  // match even when symlinking or excess path elements ("foo/../", "../")
1731  // change the form of the name. However, complete path is still the key.
1732  return llvm::hash_combine(key.FE->getSize(),
1733  Writer.getTimestampForOutput(key.FE));
1734  }
1735 
1736  std::pair<unsigned,unsigned>
1737  EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1738  using namespace llvm::support;
1739  endian::Writer<little> LE(Out);
1740  unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
1741  LE.write<uint16_t>(KeyLen);
1742  unsigned DataLen = 1 + 2 + 4 + 4;
1743  for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE))
1744  if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1745  DataLen += 4;
1746  LE.write<uint8_t>(DataLen);
1747  return std::make_pair(KeyLen, DataLen);
1748  }
1749 
1750  void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1751  using namespace llvm::support;
1752  endian::Writer<little> LE(Out);
1753  LE.write<uint64_t>(key.FE->getSize());
1754  KeyLen -= 8;
1755  LE.write<uint64_t>(Writer.getTimestampForOutput(key.FE));
1756  KeyLen -= 8;
1757  Out.write(key.Filename, KeyLen);
1758  }
1759 
1760  void EmitData(raw_ostream &Out, key_type_ref key,
1761  data_type_ref Data, unsigned DataLen) {
1762  using namespace llvm::support;
1763  endian::Writer<little> LE(Out);
1764  uint64_t Start = Out.tell(); (void)Start;
1765 
1766  unsigned char Flags = (Data.isImport << 4)
1767  | (Data.isPragmaOnce << 3)
1768  | (Data.DirInfo << 1)
1769  | Data.IndexHeaderMapHeader;
1770  LE.write<uint8_t>(Flags);
1771  LE.write<uint16_t>(Data.NumIncludes);
1772 
1773  if (!Data.ControllingMacro)
1774  LE.write<uint32_t>(Data.ControllingMacroID);
1775  else
1776  LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
1777 
1778  unsigned Offset = 0;
1779  if (!Data.Framework.empty()) {
1780  // If this header refers into a framework, save the framework name.
1782  = FrameworkNameOffset.find(Data.Framework);
1783  if (Pos == FrameworkNameOffset.end()) {
1784  Offset = FrameworkStringData.size() + 1;
1785  FrameworkStringData.append(Data.Framework.begin(),
1786  Data.Framework.end());
1787  FrameworkStringData.push_back(0);
1788 
1789  FrameworkNameOffset[Data.Framework] = Offset;
1790  } else
1791  Offset = Pos->second;
1792  }
1793  LE.write<uint32_t>(Offset);
1794 
1795  // FIXME: If the header is excluded, we should write out some
1796  // record of that fact.
1797  for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE)) {
1798  if (uint32_t ModID =
1799  Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) {
1800  uint32_t Value = (ModID << 2) | (unsigned)ModInfo.getRole();
1801  assert((Value >> 2) == ModID && "overflow in header module info");
1802  LE.write<uint32_t>(Value);
1803  }
1804  }
1805 
1806  assert(Out.tell() - Start == DataLen && "Wrong data length");
1807  }
1808 
1809  const char *strings_begin() const { return FrameworkStringData.begin(); }
1810  const char *strings_end() const { return FrameworkStringData.end(); }
1811  };
1812 } // end anonymous namespace
1813 
1814 /// \brief Write the header search block for the list of files that
1815 ///
1816 /// \param HS The header search structure to save.
1817 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1819  HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1820 
1821  if (FilesByUID.size() > HS.header_file_size())
1822  FilesByUID.resize(HS.header_file_size());
1823 
1824  HeaderFileInfoTrait GeneratorTrait(*this, HS);
1825  llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1826  SmallVector<const char *, 4> SavedStrings;
1827  unsigned NumHeaderSearchEntries = 0;
1828  for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1829  const FileEntry *File = FilesByUID[UID];
1830  if (!File)
1831  continue;
1832 
1833  // Get the file info. This will load info from the external source if
1834  // necessary. Skip emitting this file if we have no information on it
1835  // as a header file (in which case HFI will be null) or if it hasn't
1836  // changed since it was loaded. Also skip it if it's for a modular header
1837  // from a different module; in that case, we rely on the module(s)
1838  // containing the header to provide this information.
1839  const HeaderFileInfo *HFI =
1840  HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1841  if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
1842  continue;
1843 
1844  // Massage the file path into an appropriate form.
1845  const char *Filename = File->getName();
1846  SmallString<128> FilenameTmp(Filename);
1847  if (PreparePathForOutput(FilenameTmp)) {
1848  // If we performed any translation on the file name at all, we need to
1849  // save this string, since the generator will refer to it later.
1850  Filename = strdup(FilenameTmp.c_str());
1851  SavedStrings.push_back(Filename);
1852  }
1853 
1854  HeaderFileInfoTrait::key_type key = { File, Filename };
1855  Generator.insert(key, *HFI, GeneratorTrait);
1856  ++NumHeaderSearchEntries;
1857  }
1858 
1859  // Create the on-disk hash table in a buffer.
1860  SmallString<4096> TableData;
1861  uint32_t BucketOffset;
1862  {
1863  using namespace llvm::support;
1864  llvm::raw_svector_ostream Out(TableData);
1865  // Make sure that no bucket is at offset 0
1866  endian::Writer<little>(Out).write<uint32_t>(0);
1867  BucketOffset = Generator.Emit(Out, GeneratorTrait);
1868  }
1869 
1870  // Create a blob abbreviation
1871  using namespace llvm;
1872 
1873  auto *Abbrev = new BitCodeAbbrev();
1874  Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1875  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1876  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1877  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1878  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1879  unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1880 
1881  // Write the header search table
1882  RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1883  NumHeaderSearchEntries, TableData.size()};
1884  TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1885  Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
1886 
1887  // Free all of the strings we had to duplicate.
1888  for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1889  free(const_cast<char *>(SavedStrings[I]));
1890 }
1891 
1892 /// \brief Writes the block containing the serialized form of the
1893 /// source manager.
1894 ///
1895 /// TODO: We should probably use an on-disk hash table (stored in a
1896 /// blob), indexed based on the file name, so that we only create
1897 /// entries for files that we actually need. In the common case (no
1898 /// errors), we probably won't have to create file entries for any of
1899 /// the files in the AST.
1900 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1901  const Preprocessor &PP) {
1902  RecordData Record;
1903 
1904  // Enter the source manager block.
1905  Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
1906 
1907  // Abbreviations for the various kinds of source-location entries.
1908  unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1909  unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1910  unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1911  unsigned SLocBufferBlobCompressedAbbrv =
1912  CreateSLocBufferBlobAbbrev(Stream, true);
1913  unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1914 
1915  // Write out the source location entry table. We skip the first
1916  // entry, which is always the same dummy entry.
1917  std::vector<uint32_t> SLocEntryOffsets;
1918  RecordData PreloadSLocs;
1919  SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1920  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1921  I != N; ++I) {
1922  // Get this source location entry.
1923  const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1924  FileID FID = FileID::get(I);
1925  assert(&SourceMgr.getSLocEntry(FID) == SLoc);
1926 
1927  // Record the offset of this source-location entry.
1928  SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1929 
1930  // Figure out which record code to use.
1931  unsigned Code;
1932  if (SLoc->isFile()) {
1933  const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1934  if (Cache->OrigEntry) {
1935  Code = SM_SLOC_FILE_ENTRY;
1936  } else
1937  Code = SM_SLOC_BUFFER_ENTRY;
1938  } else
1939  Code = SM_SLOC_EXPANSION_ENTRY;
1940  Record.clear();
1941  Record.push_back(Code);
1942 
1943  // Starting offset of this entry within this module, so skip the dummy.
1944  Record.push_back(SLoc->getOffset() - 2);
1945  if (SLoc->isFile()) {
1946  const SrcMgr::FileInfo &File = SLoc->getFile();
1947  AddSourceLocation(File.getIncludeLoc(), Record);
1948  Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1949  Record.push_back(File.hasLineDirectives());
1950 
1951  const SrcMgr::ContentCache *Content = File.getContentCache();
1952  bool EmitBlob = false;
1953  if (Content->OrigEntry) {
1954  assert(Content->OrigEntry == Content->ContentsEntry &&
1955  "Writing to AST an overridden file is not supported");
1956 
1957  // The source location entry is a file. Emit input file ID.
1958  assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1959  Record.push_back(InputFileIDs[Content->OrigEntry]);
1960 
1961  Record.push_back(File.NumCreatedFIDs);
1962 
1963  FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
1964  if (FDI != FileDeclIDs.end()) {
1965  Record.push_back(FDI->second->FirstDeclIndex);
1966  Record.push_back(FDI->second->DeclIDs.size());
1967  } else {
1968  Record.push_back(0);
1969  Record.push_back(0);
1970  }
1971 
1972  Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1973 
1974  if (Content->BufferOverridden || Content->IsTransient)
1975  EmitBlob = true;
1976  } else {
1977  // The source location entry is a buffer. The blob associated
1978  // with this entry contains the contents of the buffer.
1979 
1980  // We add one to the size so that we capture the trailing NULL
1981  // that is required by llvm::MemoryBuffer::getMemBuffer (on
1982  // the reader side).
1983  const llvm::MemoryBuffer *Buffer
1984  = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1985  const char *Name = Buffer->getBufferIdentifier();
1986  Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1987  StringRef(Name, strlen(Name) + 1));
1988  EmitBlob = true;
1989 
1990  if (strcmp(Name, "<built-in>") == 0) {
1991  PreloadSLocs.push_back(SLocEntryOffsets.size());
1992  }
1993  }
1994 
1995  if (EmitBlob) {
1996  // Include the implicit terminating null character in the on-disk buffer
1997  // if we're writing it uncompressed.
1998  const llvm::MemoryBuffer *Buffer =
1999  Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2000  StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2001 
2002  // Compress the buffer if possible. We expect that almost all PCM
2003  // consumers will not want its contents.
2004  SmallString<0> CompressedBuffer;
2005  if (llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer) ==
2006  llvm::zlib::StatusOK) {
2007  RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2008  Blob.size() - 1};
2009  Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2010  CompressedBuffer);
2011  } else {
2012  RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB};
2013  Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2014  }
2015  }
2016  } else {
2017  // The source location entry is a macro expansion.
2018  const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2019  AddSourceLocation(Expansion.getSpellingLoc(), Record);
2020  AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2021  AddSourceLocation(Expansion.isMacroArgExpansion()
2022  ? SourceLocation()
2023  : Expansion.getExpansionLocEnd(),
2024  Record);
2025 
2026  // Compute the token length for this macro expansion.
2027  unsigned NextOffset = SourceMgr.getNextLocalOffset();
2028  if (I + 1 != N)
2029  NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2030  Record.push_back(NextOffset - SLoc->getOffset() - 1);
2031  Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2032  }
2033  }
2034 
2035  Stream.ExitBlock();
2036 
2037  if (SLocEntryOffsets.empty())
2038  return;
2039 
2040  // Write the source-location offsets table into the AST block. This
2041  // table is used for lazily loading source-location information.
2042  using namespace llvm;
2043 
2044  auto *Abbrev = new BitCodeAbbrev();
2045  Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2046  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2047  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2048  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2049  unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
2050  {
2051  RecordData::value_type Record[] = {
2052  SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2053  SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2054  Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2055  bytes(SLocEntryOffsets));
2056  }
2057  // Write the source location entry preloads array, telling the AST
2058  // reader which source locations entries it should load eagerly.
2059  Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2060 
2061  // Write the line table. It depends on remapping working, so it must come
2062  // after the source location offsets.
2063  if (SourceMgr.hasLineTable()) {
2064  LineTableInfo &LineTable = SourceMgr.getLineTable();
2065 
2066  Record.clear();
2067 
2068  // Emit the needed file names.
2069  llvm::DenseMap<int, int> FilenameMap;
2070  for (const auto &L : LineTable) {
2071  if (L.first.ID < 0)
2072  continue;
2073  for (auto &LE : L.second) {
2074  if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2075  FilenameMap.size())).second)
2076  AddPath(LineTable.getFilename(LE.FilenameID), Record);
2077  }
2078  }
2079  Record.push_back(0);
2080 
2081  // Emit the line entries
2082  for (const auto &L : LineTable) {
2083  // Only emit entries for local files.
2084  if (L.first.ID < 0)
2085  continue;
2086 
2087  // Emit the file ID
2088  Record.push_back(L.first.ID);
2089 
2090  // Emit the line entries
2091  Record.push_back(L.second.size());
2092  for (const auto &LE : L.second) {
2093  Record.push_back(LE.FileOffset);
2094  Record.push_back(LE.LineNo);
2095  Record.push_back(FilenameMap[LE.FilenameID]);
2096  Record.push_back((unsigned)LE.FileKind);
2097  Record.push_back(LE.IncludeOffset);
2098  }
2099  }
2100 
2101  Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2102  }
2103 }
2104 
2105 //===----------------------------------------------------------------------===//
2106 // Preprocessor Serialization
2107 //===----------------------------------------------------------------------===//
2108 
2109 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2110  const Preprocessor &PP) {
2111  if (MacroInfo *MI = MD->getMacroInfo())
2112  if (MI->isBuiltinMacro())
2113  return true;
2114 
2115  if (IsModule) {
2116  SourceLocation Loc = MD->getLocation();
2117  if (Loc.isInvalid())
2118  return true;
2119  if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2120  return true;
2121  }
2122 
2123  return false;
2124 }
2125 
2126 /// \brief Writes the block containing the serialized form of the
2127 /// preprocessor.
2128 ///
2129 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2131  if (PPRec)
2132  WritePreprocessorDetail(*PPRec);
2133 
2134  RecordData Record;
2135  RecordData ModuleMacroRecord;
2136 
2137  // If the preprocessor __COUNTER__ value has been bumped, remember it.
2138  if (PP.getCounterValue() != 0) {
2139  RecordData::value_type Record[] = {PP.getCounterValue()};
2140  Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2141  }
2142 
2143  // Enter the preprocessor block.
2144  Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2145 
2146  // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2147  // FIXME: Include a location for the use, and say which one was used.
2148  if (PP.SawDateOrTime())
2149  PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2150 
2151  // Loop over all the macro directives that are live at the end of the file,
2152  // emitting each to the PP section.
2153 
2154  // Construct the list of identifiers with macro directives that need to be
2155  // serialized.
2157  for (auto &Id : PP.getIdentifierTable())
2158  if (Id.second->hadMacroDefinition() &&
2159  (!Id.second->isFromAST() ||
2160  Id.second->hasChangedSinceDeserialization()))
2161  MacroIdentifiers.push_back(Id.second);
2162  // Sort the set of macro definitions that need to be serialized by the
2163  // name of the macro, to provide a stable ordering.
2164  std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2165  llvm::less_ptr<IdentifierInfo>());
2166 
2167  // Emit the macro directives as a list and associate the offset with the
2168  // identifier they belong to.
2169  for (const IdentifierInfo *Name : MacroIdentifiers) {
2171  auto StartOffset = Stream.GetCurrentBitNo();
2172 
2173  // Emit the macro directives in reverse source order.
2174  for (; MD; MD = MD->getPrevious()) {
2175  // Once we hit an ignored macro, we're done: the rest of the chain
2176  // will all be ignored macros.
2177  if (shouldIgnoreMacro(MD, IsModule, PP))
2178  break;
2179 
2180  AddSourceLocation(MD->getLocation(), Record);
2181  Record.push_back(MD->getKind());
2182  if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2183  Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2184  } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2185  Record.push_back(VisMD->isPublic());
2186  }
2187  }
2188 
2189  // Write out any exported module macros.
2190  bool EmittedModuleMacros = false;
2191  // We write out exported module macros for PCH as well.
2192  auto Leafs = PP.getLeafModuleMacros(Name);
2193  SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2194  llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2195  while (!Worklist.empty()) {
2196  auto *Macro = Worklist.pop_back_val();
2197 
2198  // Emit a record indicating this submodule exports this macro.
2199  ModuleMacroRecord.push_back(
2200  getSubmoduleID(Macro->getOwningModule()));
2201  ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2202  for (auto *M : Macro->overrides())
2203  ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2204 
2205  Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2206  ModuleMacroRecord.clear();
2207 
2208  // Enqueue overridden macros once we've visited all their ancestors.
2209  for (auto *M : Macro->overrides())
2210  if (++Visits[M] == M->getNumOverridingMacros())
2211  Worklist.push_back(M);
2212 
2213  EmittedModuleMacros = true;
2214  }
2215 
2216  if (Record.empty() && !EmittedModuleMacros)
2217  continue;
2218 
2219  IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2220  Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2221  Record.clear();
2222  }
2223 
2224  /// \brief Offsets of each of the macros into the bitstream, indexed by
2225  /// the local macro ID
2226  ///
2227  /// For each identifier that is associated with a macro, this map
2228  /// provides the offset into the bitstream where that macro is
2229  /// defined.
2230  std::vector<uint32_t> MacroOffsets;
2231 
2232  for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2233  const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2234  MacroInfo *MI = MacroInfosToEmit[I].MI;
2235  MacroID ID = MacroInfosToEmit[I].ID;
2236 
2237  if (ID < FirstMacroID) {
2238  assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2239  continue;
2240  }
2241 
2242  // Record the local offset of this macro.
2243  unsigned Index = ID - FirstMacroID;
2244  if (Index == MacroOffsets.size())
2245  MacroOffsets.push_back(Stream.GetCurrentBitNo());
2246  else {
2247  if (Index > MacroOffsets.size())
2248  MacroOffsets.resize(Index + 1);
2249 
2250  MacroOffsets[Index] = Stream.GetCurrentBitNo();
2251  }
2252 
2253  AddIdentifierRef(Name, Record);
2254  Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2255  AddSourceLocation(MI->getDefinitionLoc(), Record);
2256  AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2257  Record.push_back(MI->isUsed());
2258  Record.push_back(MI->isUsedForHeaderGuard());
2259  unsigned Code;
2260  if (MI->isObjectLike()) {
2261  Code = PP_MACRO_OBJECT_LIKE;
2262  } else {
2263  Code = PP_MACRO_FUNCTION_LIKE;
2264 
2265  Record.push_back(MI->isC99Varargs());
2266  Record.push_back(MI->isGNUVarargs());
2267  Record.push_back(MI->hasCommaPasting());
2268  Record.push_back(MI->getNumArgs());
2269  for (const IdentifierInfo *Arg : MI->args())
2270  AddIdentifierRef(Arg, Record);
2271  }
2272 
2273  // If we have a detailed preprocessing record, record the macro definition
2274  // ID that corresponds to this macro.
2275  if (PPRec)
2276  Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2277 
2278  Stream.EmitRecord(Code, Record);
2279  Record.clear();
2280 
2281  // Emit the tokens array.
2282  for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2283  // Note that we know that the preprocessor does not have any annotation
2284  // tokens in it because they are created by the parser, and thus can't
2285  // be in a macro definition.
2286  const Token &Tok = MI->getReplacementToken(TokNo);
2287  AddToken(Tok, Record);
2288  Stream.EmitRecord(PP_TOKEN, Record);
2289  Record.clear();
2290  }
2291  ++NumMacros;
2292  }
2293 
2294  Stream.ExitBlock();
2295 
2296  // Write the offsets table for macro IDs.
2297  using namespace llvm;
2298 
2299  auto *Abbrev = new BitCodeAbbrev();
2300  Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2301  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2302  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2303  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2304 
2305  unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2306  {
2307  RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2308  FirstMacroID - NUM_PREDEF_MACRO_IDS};
2309  Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2310  }
2311 }
2312 
2313 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2314  if (PPRec.local_begin() == PPRec.local_end())
2315  return;
2316 
2317  SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2318 
2319  // Enter the preprocessor block.
2320  Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2321 
2322  // If the preprocessor has a preprocessing record, emit it.
2323  unsigned NumPreprocessingRecords = 0;
2324  using namespace llvm;
2325 
2326  // Set up the abbreviation for
2327  unsigned InclusionAbbrev = 0;
2328  {
2329  auto *Abbrev = new BitCodeAbbrev();
2330  Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2331  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2332  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2333  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2334  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2335  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2336  InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2337  }
2338 
2339  unsigned FirstPreprocessorEntityID
2340  = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2342  unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2343  RecordData Record;
2345  EEnd = PPRec.local_end();
2346  E != EEnd;
2347  (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2348  Record.clear();
2349 
2350  PreprocessedEntityOffsets.push_back(
2351  PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
2352 
2353  if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2354  // Record this macro definition's ID.
2355  MacroDefinitions[MD] = NextPreprocessorEntityID;
2356 
2357  AddIdentifierRef(MD->getName(), Record);
2358  Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2359  continue;
2360  }
2361 
2362  if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2363  Record.push_back(ME->isBuiltinMacro());
2364  if (ME->isBuiltinMacro())
2365  AddIdentifierRef(ME->getName(), Record);
2366  else
2367  Record.push_back(MacroDefinitions[ME->getDefinition()]);
2368  Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2369  continue;
2370  }
2371 
2372  if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2373  Record.push_back(PPD_INCLUSION_DIRECTIVE);
2374  Record.push_back(ID->getFileName().size());
2375  Record.push_back(ID->wasInQuotes());
2376  Record.push_back(static_cast<unsigned>(ID->getKind()));
2377  Record.push_back(ID->importedModule());
2379  Buffer += ID->getFileName();
2380  // Check that the FileEntry is not null because it was not resolved and
2381  // we create a PCH even with compiler errors.
2382  if (ID->getFile())
2383  Buffer += ID->getFile()->getName();
2384  Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2385  continue;
2386  }
2387 
2388  llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2389  }
2390  Stream.ExitBlock();
2391 
2392  // Write the offsets table for the preprocessing record.
2393  if (NumPreprocessingRecords > 0) {
2394  assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2395 
2396  // Write the offsets table for identifier IDs.
2397  using namespace llvm;
2398 
2399  auto *Abbrev = new BitCodeAbbrev();
2400  Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2401  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2402  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2403  unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2404 
2405  RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2406  FirstPreprocessorEntityID -
2408  Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2409  bytes(PreprocessedEntityOffsets));
2410  }
2411 }
2412 
2414  if (!Mod)
2415  return 0;
2416 
2417  llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2418  if (Known != SubmoduleIDs.end())
2419  return Known->second;
2420 
2421  if (Mod->getTopLevelModule() != WritingModule)
2422  return 0;
2423 
2424  return SubmoduleIDs[Mod] = NextSubmoduleID++;
2425 }
2426 
2427 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2428  // FIXME: This can easily happen, if we have a reference to a submodule that
2429  // did not result in us loading a module file for that submodule. For
2430  // instance, a cross-top-level-module 'conflict' declaration will hit this.
2431  unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2432  assert((ID || !Mod) &&
2433  "asked for module ID for non-local, non-imported module");
2434  return ID;
2435 }
2436 
2437 /// \brief Compute the number of modules within the given tree (including the
2438 /// given module).
2439 static unsigned getNumberOfModules(Module *Mod) {
2440  unsigned ChildModules = 0;
2441  for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2442  Sub != SubEnd; ++Sub)
2443  ChildModules += getNumberOfModules(*Sub);
2444 
2445  return ChildModules + 1;
2446 }
2447 
2448 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2449  // Enter the submodule description block.
2450  Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2451 
2452  // Write the abbreviations needed for the submodules block.
2453  using namespace llvm;
2454 
2455  auto *Abbrev = new BitCodeAbbrev();
2456  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2457  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2458  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2459  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2460  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2461  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2462  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2463  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2464  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2465  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2466  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2467  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2468  unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2469 
2470  Abbrev = new BitCodeAbbrev();
2471  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2472  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2473  unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2474 
2475  Abbrev = new BitCodeAbbrev();
2476  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2477  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2478  unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2479 
2480  Abbrev = new BitCodeAbbrev();
2481  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2482  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2483  unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2484 
2485  Abbrev = new BitCodeAbbrev();
2486  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2487  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2488  unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2489 
2490  Abbrev = new BitCodeAbbrev();
2491  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2492  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2493  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2494  unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2495 
2496  Abbrev = new BitCodeAbbrev();
2497  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2498  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2499  unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2500 
2501  Abbrev = new BitCodeAbbrev();
2502  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2503  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2504  unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2505 
2506  Abbrev = new BitCodeAbbrev();
2507  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2508  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2509  unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2510 
2511  Abbrev = new BitCodeAbbrev();
2512  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2513  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2514  unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2515 
2516  Abbrev = new BitCodeAbbrev();
2517  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2518  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2519  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2520  unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2521 
2522  Abbrev = new BitCodeAbbrev();
2523  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2524  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2525  unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2526 
2527  Abbrev = new BitCodeAbbrev();
2528  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2529  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2530  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2531  unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2532 
2533  // Write the submodule metadata block.
2534  RecordData::value_type Record[] = {getNumberOfModules(WritingModule),
2535  FirstSubmoduleID -
2537  Stream.EmitRecord(SUBMODULE_METADATA, Record);
2538 
2539  // Write all of the submodules.
2540  std::queue<Module *> Q;
2541  Q.push(WritingModule);
2542  while (!Q.empty()) {
2543  Module *Mod = Q.front();
2544  Q.pop();
2545  unsigned ID = getSubmoduleID(Mod);
2546 
2547  uint64_t ParentID = 0;
2548  if (Mod->Parent) {
2549  assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2550  ParentID = SubmoduleIDs[Mod->Parent];
2551  }
2552 
2553  // Emit the definition of the block.
2554  {
2555  RecordData::value_type Record[] = {
2556  SUBMODULE_DEFINITION, ID, ParentID, Mod->IsFramework, Mod->IsExplicit,
2557  Mod->IsSystem, Mod->IsExternC, Mod->InferSubmodules,
2559  Mod->ConfigMacrosExhaustive};
2560  Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2561  }
2562 
2563  // Emit the requirements.
2564  for (const auto &R : Mod->Requirements) {
2565  RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2566  Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2567  }
2568 
2569  // Emit the umbrella header, if there is one.
2570  if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2571  RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2572  Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2573  UmbrellaHeader.NameAsWritten);
2574  } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2575  RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2576  Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2577  UmbrellaDir.NameAsWritten);
2578  }
2579 
2580  // Emit the headers.
2581  struct {
2582  unsigned RecordKind;
2583  unsigned Abbrev;
2584  Module::HeaderKind HeaderKind;
2585  } HeaderLists[] = {
2586  {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2587  {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2588  {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2589  {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2591  {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2592  };
2593  for (auto &HL : HeaderLists) {
2594  RecordData::value_type Record[] = {HL.RecordKind};
2595  for (auto &H : Mod->Headers[HL.HeaderKind])
2596  Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2597  }
2598 
2599  // Emit the top headers.
2600  {
2601  auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2602  RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2603  for (auto *H : TopHeaders)
2604  Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2605  }
2606 
2607  // Emit the imports.
2608  if (!Mod->Imports.empty()) {
2609  RecordData Record;
2610  for (auto *I : Mod->Imports)
2611  Record.push_back(getSubmoduleID(I));
2612  Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2613  }
2614 
2615  // Emit the exports.
2616  if (!Mod->Exports.empty()) {
2617  RecordData Record;
2618  for (const auto &E : Mod->Exports) {
2619  // FIXME: This may fail; we don't require that all exported modules
2620  // are local or imported.
2621  Record.push_back(getSubmoduleID(E.getPointer()));
2622  Record.push_back(E.getInt());
2623  }
2624  Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2625  }
2626 
2627  //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2628  // Might be unnecessary as use declarations are only used to build the
2629  // module itself.
2630 
2631  // Emit the link libraries.
2632  for (const auto &LL : Mod->LinkLibraries) {
2633  RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2634  LL.IsFramework};
2635  Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2636  }
2637 
2638  // Emit the conflicts.
2639  for (const auto &C : Mod->Conflicts) {
2640  // FIXME: This may fail; we don't require that all conflicting modules
2641  // are local or imported.
2642  RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2643  getSubmoduleID(C.Other)};
2644  Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2645  }
2646 
2647  // Emit the configuration macros.
2648  for (const auto &CM : Mod->ConfigMacros) {
2649  RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2650  Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2651  }
2652 
2653  // Queue up the submodules of this module.
2654  for (auto *M : Mod->submodules())
2655  Q.push(M);
2656  }
2657 
2658  Stream.ExitBlock();
2659 
2660  assert((NextSubmoduleID - FirstSubmoduleID ==
2661  getNumberOfModules(WritingModule)) &&
2662  "Wrong # of submodules; found a reference to a non-local, "
2663  "non-imported submodule?");
2664 }
2665 
2668  if (Loc.isInvalid() || !WritingModule)
2669  return 0; // No submodule
2670 
2671  // Find the module that owns this location.
2672  ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2673  Module *OwningMod
2675  if (!OwningMod)
2676  return 0;
2677 
2678  // Check whether this submodule is part of our own module.
2679  if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
2680  return 0;
2681 
2682  return getSubmoduleID(OwningMod);
2683 }
2684 
2685 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2686  bool isModule) {
2687  // Make sure set diagnostic pragmas don't affect the translation unit that
2688  // imports the module.
2689  // FIXME: Make diagnostic pragma sections work properly with modules.
2690  if (isModule)
2691  return;
2692 
2693  llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2694  DiagStateIDMap;
2695  unsigned CurrID = 0;
2696  DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
2697  RecordData Record;
2698  for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2699  I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2700  I != E; ++I) {
2701  const DiagnosticsEngine::DiagStatePoint &point = *I;
2702  if (point.Loc.isInvalid())
2703  continue;
2704 
2705  AddSourceLocation(point.Loc, Record);
2706  unsigned &DiagStateID = DiagStateIDMap[point.State];
2707  Record.push_back(DiagStateID);
2708 
2709  if (DiagStateID == 0) {
2710  DiagStateID = ++CurrID;
2711  for (const auto &I : *(point.State)) {
2712  if (I.second.isPragma()) {
2713  Record.push_back(I.first);
2714  Record.push_back((unsigned)I.second.getSeverity());
2715  }
2716  }
2717  Record.push_back(-1); // mark the end of the diag/map pairs for this
2718  // location.
2719  }
2720  }
2721 
2722  if (!Record.empty())
2723  Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2724 }
2725 
2726 //===----------------------------------------------------------------------===//
2727 // Type Serialization
2728 //===----------------------------------------------------------------------===//
2729 
2730 /// \brief Write the representation of a type to the AST stream.
2731 void ASTWriter::WriteType(QualType T) {
2732  TypeIdx &IdxRef = TypeIdxs[T];
2733  if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2734  IdxRef = TypeIdx(NextTypeID++);
2735  TypeIdx Idx = IdxRef;
2736 
2737  assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2738 
2739  RecordData Record;
2740 
2741  // Emit the type's representation.
2742  ASTTypeWriter W(*this, Record);
2743  W.Visit(T);
2744  uint64_t Offset = W.Emit();
2745 
2746  // Record the offset for this type.
2747  unsigned Index = Idx.getIndex() - FirstTypeID;
2748  if (TypeOffsets.size() == Index)
2749  TypeOffsets.push_back(Offset);
2750  else if (TypeOffsets.size() < Index) {
2751  TypeOffsets.resize(Index + 1);
2752  TypeOffsets[Index] = Offset;
2753  } else {
2754  llvm_unreachable("Types emitted in wrong order");
2755  }
2756 }
2757 
2758 //===----------------------------------------------------------------------===//
2759 // Declaration Serialization
2760 //===----------------------------------------------------------------------===//
2761 
2762 /// \brief Write the block containing all of the declaration IDs
2763 /// lexically declared within the given DeclContext.
2764 ///
2765 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2766 /// bistream, or 0 if no block was written.
2767 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2768  DeclContext *DC) {
2769  if (DC->decls_empty())
2770  return 0;
2771 
2772  uint64_t Offset = Stream.GetCurrentBitNo();
2773  SmallVector<uint32_t, 128> KindDeclPairs;
2774  for (const auto *D : DC->decls()) {
2775  KindDeclPairs.push_back(D->getKind());
2776  KindDeclPairs.push_back(GetDeclRef(D));
2777  }
2778 
2779  ++NumLexicalDeclContexts;
2780  RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
2781  Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2782  bytes(KindDeclPairs));
2783  return Offset;
2784 }
2785 
2786 void ASTWriter::WriteTypeDeclOffsets() {
2787  using namespace llvm;
2788 
2789  // Write the type offsets array
2790  auto *Abbrev = new BitCodeAbbrev();
2791  Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2792  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2793  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2794  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2795  unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2796  {
2797  RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2798  FirstTypeID - NUM_PREDEF_TYPE_IDS};
2799  Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2800  }
2801 
2802  // Write the declaration offsets array
2803  Abbrev = new BitCodeAbbrev();
2804  Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2805  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2806  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2807  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2808  unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2809  {
2810  RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2811  FirstDeclID - NUM_PREDEF_DECL_IDS};
2812  Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2813  }
2814 }
2815 
2816 void ASTWriter::WriteFileDeclIDsMap() {
2817  using namespace llvm;
2818 
2820  FileDeclIDs.begin(), FileDeclIDs.end());
2821  std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2822  llvm::less_first());
2823 
2824  // Join the vectors of DeclIDs from all files.
2825  SmallVector<DeclID, 256> FileGroupedDeclIDs;
2826  for (auto &FileDeclEntry : SortedFileDeclIDs) {
2827  DeclIDInFileInfo &Info = *FileDeclEntry.second;
2828  Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2829  for (auto &LocDeclEntry : Info.DeclIDs)
2830  FileGroupedDeclIDs.push_back(LocDeclEntry.second);
2831  }
2832 
2833  auto *Abbrev = new BitCodeAbbrev();
2834  Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2835  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2836  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2837  unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2838  RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2839  FileGroupedDeclIDs.size()};
2840  Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
2841 }
2842 
2843 void ASTWriter::WriteComments() {
2844  Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2845  ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
2846  RecordData Record;
2847  for (const auto *I : RawComments) {
2848  Record.clear();
2849  AddSourceRange(I->getSourceRange(), Record);
2850  Record.push_back(I->getKind());
2851  Record.push_back(I->isTrailingComment());
2852  Record.push_back(I->isAlmostTrailingComment());
2853  Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2854  }
2855  Stream.ExitBlock();
2856 }
2857 
2858 //===----------------------------------------------------------------------===//
2859 // Global Method Pool and Selector Serialization
2860 //===----------------------------------------------------------------------===//
2861 
2862 namespace {
2863 // Trait used for the on-disk hash table used in the method pool.
2864 class ASTMethodPoolTrait {
2865  ASTWriter &Writer;
2866 
2867 public:
2868  typedef Selector key_type;
2869  typedef key_type key_type_ref;
2870 
2871  struct data_type {
2872  SelectorID ID;
2873  ObjCMethodList Instance, Factory;
2874  };
2875  typedef const data_type& data_type_ref;
2876 
2877  typedef unsigned hash_value_type;
2878  typedef unsigned offset_type;
2879 
2880  explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2881 
2882  static hash_value_type ComputeHash(Selector Sel) {
2883  return serialization::ComputeHash(Sel);
2884  }
2885 
2886  std::pair<unsigned,unsigned>
2887  EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2888  data_type_ref Methods) {
2889  using namespace llvm::support;
2890  endian::Writer<little> LE(Out);
2891  unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2892  LE.write<uint16_t>(KeyLen);
2893  unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2894  for (const ObjCMethodList *Method = &Methods.Instance; Method;
2895  Method = Method->getNext())
2896  if (Method->getMethod())
2897  DataLen += 4;
2898  for (const ObjCMethodList *Method = &Methods.Factory; Method;
2899  Method = Method->getNext())
2900  if (Method->getMethod())
2901  DataLen += 4;
2902  LE.write<uint16_t>(DataLen);
2903  return std::make_pair(KeyLen, DataLen);
2904  }
2905 
2906  void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
2907  using namespace llvm::support;
2908  endian::Writer<little> LE(Out);
2909  uint64_t Start = Out.tell();
2910  assert((Start >> 32) == 0 && "Selector key offset too large");
2911  Writer.SetSelectorOffset(Sel, Start);
2912  unsigned N = Sel.getNumArgs();
2913  LE.write<uint16_t>(N);
2914  if (N == 0)
2915  N = 1;
2916  for (unsigned I = 0; I != N; ++I)
2917  LE.write<uint32_t>(
2918  Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2919  }
2920 
2921  void EmitData(raw_ostream& Out, key_type_ref,
2922  data_type_ref Methods, unsigned DataLen) {
2923  using namespace llvm::support;
2924  endian::Writer<little> LE(Out);
2925  uint64_t Start = Out.tell(); (void)Start;
2926  LE.write<uint32_t>(Methods.ID);
2927  unsigned NumInstanceMethods = 0;
2928  for (const ObjCMethodList *Method = &Methods.Instance; Method;
2929  Method = Method->getNext())
2930  if (Method->getMethod())
2931  ++NumInstanceMethods;
2932 
2933  unsigned NumFactoryMethods = 0;
2934  for (const ObjCMethodList *Method = &Methods.Factory; Method;
2935  Method = Method->getNext())
2936  if (Method->getMethod())
2937  ++NumFactoryMethods;
2938 
2939  unsigned InstanceBits = Methods.Instance.getBits();
2940  assert(InstanceBits < 4);
2941  unsigned InstanceHasMoreThanOneDeclBit =
2942  Methods.Instance.hasMoreThanOneDecl();
2943  unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2944  (InstanceHasMoreThanOneDeclBit << 2) |
2945  InstanceBits;
2946  unsigned FactoryBits = Methods.Factory.getBits();
2947  assert(FactoryBits < 4);
2948  unsigned FactoryHasMoreThanOneDeclBit =
2949  Methods.Factory.hasMoreThanOneDecl();
2950  unsigned FullFactoryBits = (NumFactoryMethods << 3) |
2951  (FactoryHasMoreThanOneDeclBit << 2) |
2952  FactoryBits;
2953  LE.write<uint16_t>(FullInstanceBits);
2954  LE.write<uint16_t>(FullFactoryBits);
2955  for (const ObjCMethodList *Method = &Methods.Instance; Method;
2956  Method = Method->getNext())
2957  if (Method->getMethod())
2958  LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
2959  for (const ObjCMethodList *Method = &Methods.Factory; Method;
2960  Method = Method->getNext())
2961  if (Method->getMethod())
2962  LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
2963 
2964  assert(Out.tell() - Start == DataLen && "Data length is wrong");
2965  }
2966 };
2967 } // end anonymous namespace
2968 
2969 /// \brief Write ObjC data: selectors and the method pool.
2970 ///
2971 /// The method pool contains both instance and factory methods, stored
2972 /// in an on-disk hash table indexed by the selector. The hash table also
2973 /// contains an empty entry for every other selector known to Sema.
2974 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2975  using namespace llvm;
2976 
2977  // Do we have to do anything at all?
2978  if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2979  return;
2980  unsigned NumTableEntries = 0;
2981  // Create and write out the blob that contains selectors and the method pool.
2982  {
2983  llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2984  ASTMethodPoolTrait Trait(*this);
2985 
2986  // Create the on-disk hash table representation. We walk through every
2987  // selector we've seen and look it up in the method pool.
2988  SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2989  for (auto &SelectorAndID : SelectorIDs) {
2990  Selector S = SelectorAndID.first;
2991  SelectorID ID = SelectorAndID.second;
2992  Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2993  ASTMethodPoolTrait::data_type Data = {
2994  ID,
2995  ObjCMethodList(),
2996  ObjCMethodList()
2997  };
2998  if (F != SemaRef.MethodPool.end()) {
2999  Data.Instance = F->second.first;
3000  Data.Factory = F->second.second;
3001  }
3002  // Only write this selector if it's not in an existing AST or something
3003  // changed.
3004  if (Chain && ID < FirstSelectorID) {
3005  // Selector already exists. Did it change?
3006  bool changed = false;
3007  for (ObjCMethodList *M = &Data.Instance;
3008  !changed && M && M->getMethod(); M = M->getNext()) {
3009  if (!M->getMethod()->isFromASTFile())
3010  changed = true;
3011  }
3012  for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
3013  M = M->getNext()) {
3014  if (!M->getMethod()->isFromASTFile())
3015  changed = true;
3016  }
3017  if (!changed)
3018  continue;
3019  } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3020  // A new method pool entry.
3021  ++NumTableEntries;
3022  }
3023  Generator.insert(S, Data, Trait);
3024  }
3025 
3026  // Create the on-disk hash table in a buffer.
3027  SmallString<4096> MethodPool;
3028  uint32_t BucketOffset;
3029  {
3030  using namespace llvm::support;
3031  ASTMethodPoolTrait Trait(*this);
3032  llvm::raw_svector_ostream Out(MethodPool);
3033  // Make sure that no bucket is at offset 0
3034  endian::Writer<little>(Out).write<uint32_t>(0);
3035  BucketOffset = Generator.Emit(Out, Trait);
3036  }
3037 
3038  // Create a blob abbreviation
3039  auto *Abbrev = new BitCodeAbbrev();
3040  Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3041  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3042  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3043  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3044  unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
3045 
3046  // Write the method pool
3047  {
3048  RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3049  NumTableEntries};
3050  Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3051  }
3052 
3053  // Create a blob abbreviation for the selector table offsets.
3054  Abbrev = new BitCodeAbbrev();
3055  Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3056  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3057  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3058  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3059  unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3060 
3061  // Write the selector offsets table.
3062  {
3063  RecordData::value_type Record[] = {
3064  SELECTOR_OFFSETS, SelectorOffsets.size(),
3065  FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3066  Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3067  bytes(SelectorOffsets));
3068  }
3069  }
3070 }
3071 
3072 /// \brief Write the selectors referenced in @selector expression into AST file.
3073 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3074  using namespace llvm;
3075  if (SemaRef.ReferencedSelectors.empty())
3076  return;
3077 
3078  RecordData Record;
3079  ASTRecordWriter Writer(*this, Record);
3080 
3081  // Note: this writes out all references even for a dependent AST. But it is
3082  // very tricky to fix, and given that @selector shouldn't really appear in
3083  // headers, probably not worth it. It's not a correctness issue.
3084  for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3085  Selector Sel = SelectorAndLocation.first;
3086  SourceLocation Loc = SelectorAndLocation.second;
3087  Writer.AddSelectorRef(Sel);
3088  Writer.AddSourceLocation(Loc);
3089  }
3090  Writer.Emit(REFERENCED_SELECTOR_POOL);
3091 }
3092 
3093 //===----------------------------------------------------------------------===//
3094 // Identifier Table Serialization
3095 //===----------------------------------------------------------------------===//
3096 
3097 /// Determine the declaration that should be put into the name lookup table to
3098 /// represent the given declaration in this module. This is usually D itself,
3099 /// but if D was imported and merged into a local declaration, we want the most
3100 /// recent local declaration instead. The chosen declaration will be the most
3101 /// recent declaration in any module that imports this one.
3103  NamedDecl *D) {
3104  if (!LangOpts.Modules || !D->isFromASTFile())
3105  return D;
3106 
3107  if (Decl *Redecl = D->getPreviousDecl()) {
3108  // For Redeclarable decls, a prior declaration might be local.
3109  for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3110  // If we find a local decl, we're done.
3111  if (!Redecl->isFromASTFile()) {
3112  // Exception: in very rare cases (for injected-class-names), not all
3113  // redeclarations are in the same semantic context. Skip ones in a
3114  // different context. They don't go in this lookup table at all.
3115  if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3116  D->getDeclContext()->getRedeclContext()))
3117  continue;
3118  return cast<NamedDecl>(Redecl);
3119  }
3120 
3121  // If we find a decl from a (chained-)PCH stop since we won't find a
3122  // local one.
3123  if (Redecl->getOwningModuleID() == 0)
3124  break;
3125  }
3126  } else if (Decl *First = D->getCanonicalDecl()) {
3127  // For Mergeable decls, the first decl might be local.
3128  if (!First->isFromASTFile())
3129  return cast<NamedDecl>(First);
3130  }
3131 
3132  // All declarations are imported. Our most recent declaration will also be
3133  // the most recent one in anyone who imports us.
3134  return D;
3135 }
3136 
3137 namespace {
3138 class ASTIdentifierTableTrait {
3139  ASTWriter &Writer;
3140  Preprocessor &PP;
3141  IdentifierResolver &IdResolver;
3142  bool IsModule;
3143  bool NeedDecls;
3144  ASTWriter::RecordData *InterestingIdentifierOffsets;
3145 
3146  /// \brief Determines whether this is an "interesting" identifier that needs a
3147  /// full IdentifierInfo structure written into the hash table. Notably, this
3148  /// doesn't check whether the name has macros defined; use PublicMacroIterator
3149  /// to check that.
3150  bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3151  if (MacroOffset ||
3152  II->isPoisoned() ||
3153  (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
3155  (NeedDecls && II->getFETokenInfo<void>()))
3156  return true;
3157 
3158  return false;
3159  }
3160 
3161 public:
3162  typedef IdentifierInfo* key_type;
3163  typedef key_type key_type_ref;
3164 
3165  typedef IdentID data_type;
3166  typedef data_type data_type_ref;
3167 
3168  typedef unsigned hash_value_type;
3169  typedef unsigned offset_type;
3170 
3171  ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3172  IdentifierResolver &IdResolver, bool IsModule,
3173  ASTWriter::RecordData *InterestingIdentifierOffsets)
3174  : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3175  NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3176  InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3177 
3178  bool needDecls() const { return NeedDecls; }
3179 
3180  static hash_value_type ComputeHash(const IdentifierInfo* II) {
3181  return llvm::HashString(II->getName());
3182  }
3183 
3184  bool isInterestingIdentifier(const IdentifierInfo *II) {
3185  auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3186  return isInterestingIdentifier(II, MacroOffset);
3187  }
3188  bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3189  return isInterestingIdentifier(II, 0);
3190  }
3191 
3192  std::pair<unsigned,unsigned>
3193  EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3194  unsigned KeyLen = II->getLength() + 1;
3195  unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3196  auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3197  if (isInterestingIdentifier(II, MacroOffset)) {
3198  DataLen += 2; // 2 bytes for builtin ID
3199  DataLen += 2; // 2 bytes for flags
3200  if (MacroOffset)
3201  DataLen += 4; // MacroDirectives offset.
3202 
3203  if (NeedDecls) {
3204  for (IdentifierResolver::iterator D = IdResolver.begin(II),
3205  DEnd = IdResolver.end();
3206  D != DEnd; ++D)
3207  DataLen += 4;
3208  }
3209  }
3210  using namespace llvm::support;
3211  endian::Writer<little> LE(Out);
3212 
3213  assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
3214  LE.write<uint16_t>(DataLen);
3215  // We emit the key length after the data length so that every
3216  // string is preceded by a 16-bit length. This matches the PTH
3217  // format for storing identifiers.
3218  LE.write<uint16_t>(KeyLen);
3219  return std::make_pair(KeyLen, DataLen);
3220  }
3221 
3222  void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3223  unsigned KeyLen) {
3224  // Record the location of the key data. This is used when generating
3225  // the mapping from persistent IDs to strings.
3226  Writer.SetIdentifierOffset(II, Out.tell());
3227 
3228  // Emit the offset of the key/data length information to the interesting
3229  // identifiers table if necessary.
3230  if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3231  InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3232 
3233  Out.write(II->getNameStart(), KeyLen);
3234  }
3235 
3236  void EmitData(raw_ostream& Out, IdentifierInfo* II,
3237  IdentID ID, unsigned) {
3238  using namespace llvm::support;
3239  endian::Writer<little> LE(Out);
3240 
3241  auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3242  if (!isInterestingIdentifier(II, MacroOffset)) {
3243  LE.write<uint32_t>(ID << 1);
3244  return;
3245  }
3246 
3247  LE.write<uint32_t>((ID << 1) | 0x01);
3248  uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3249  assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3250  LE.write<uint16_t>(Bits);
3251  Bits = 0;
3252  bool HadMacroDefinition = MacroOffset != 0;
3253  Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3254  Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3255  Bits = (Bits << 1) | unsigned(II->isPoisoned());
3256  Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
3257  Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3258  Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3259  LE.write<uint16_t>(Bits);
3260 
3261  if (HadMacroDefinition)
3262  LE.write<uint32_t>(MacroOffset);
3263 
3264  if (NeedDecls) {
3265  // Emit the declaration IDs in reverse order, because the
3266  // IdentifierResolver provides the declarations as they would be
3267  // visible (e.g., the function "stat" would come before the struct
3268  // "stat"), but the ASTReader adds declarations to the end of the list
3269  // (so we need to see the struct "stat" before the function "stat").
3270  // Only emit declarations that aren't from a chained PCH, though.
3271  SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3272  IdResolver.end());
3273  for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3274  DEnd = Decls.rend();
3275  D != DEnd; ++D)
3276  LE.write<uint32_t>(
3277  Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3278  }
3279  }
3280 };
3281 } // end anonymous namespace
3282 
3283 /// \brief Write the identifier table into the AST file.
3284 ///
3285 /// The identifier table consists of a blob containing string data
3286 /// (the actual identifiers themselves) and a separate "offsets" index
3287 /// that maps identifier IDs to locations within the blob.
3288 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3289  IdentifierResolver &IdResolver,
3290  bool IsModule) {
3291  using namespace llvm;
3292 
3293  RecordData InterestingIdents;
3294 
3295  // Create and write out the blob that contains the identifier
3296  // strings.
3297  {
3298  llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3299  ASTIdentifierTableTrait Trait(
3300  *this, PP, IdResolver, IsModule,
3301  (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3302 
3303  // Look for any identifiers that were named while processing the
3304  // headers, but are otherwise not needed. We add these to the hash
3305  // table to enable checking of the predefines buffer in the case
3306  // where the user adds new macro definitions when building the AST
3307  // file.
3309  for (const auto &ID : PP.getIdentifierTable())
3310  IIs.push_back(ID.second);
3311  // Sort the identifiers lexicographically before getting them references so
3312  // that their order is stable.
3313  std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3314  for (const IdentifierInfo *II : IIs)
3315  if (Trait.isInterestingNonMacroIdentifier(II))
3316  getIdentifierRef(II);
3317 
3318  // Create the on-disk hash table representation. We only store offsets
3319  // for identifiers that appear here for the first time.
3320  IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3321  for (auto IdentIDPair : IdentifierIDs) {
3322  auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3323  IdentID ID = IdentIDPair.second;
3324  assert(II && "NULL identifier in identifier table");
3325  // Write out identifiers if either the ID is local or the identifier has
3326  // changed since it was loaded.
3327  if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3328  || II->hasChangedSinceDeserialization() ||
3329  (Trait.needDecls() &&
3331  Generator.insert(II, ID, Trait);
3332  }
3333 
3334  // Create the on-disk hash table in a buffer.
3336  uint32_t BucketOffset;
3337  {
3338  using namespace llvm::support;
3339  llvm::raw_svector_ostream Out(IdentifierTable);
3340  // Make sure that no bucket is at offset 0
3341  endian::Writer<little>(Out).write<uint32_t>(0);
3342  BucketOffset = Generator.Emit(Out, Trait);
3343  }
3344 
3345  // Create a blob abbreviation
3346  auto *Abbrev = new BitCodeAbbrev();
3347  Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3348  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3349  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3350  unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
3351 
3352  // Write the identifier table
3353  RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3354  Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3355  }
3356 
3357  // Write the offsets table for identifier IDs.
3358  auto *Abbrev = new BitCodeAbbrev();
3359  Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3360  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3361  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3362  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3363  unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3364 
3365 #ifndef NDEBUG
3366  for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3367  assert(IdentifierOffsets[I] && "Missing identifier offset?");
3368 #endif
3369 
3370  RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3371  IdentifierOffsets.size(),
3372  FirstIdentID - NUM_PREDEF_IDENT_IDS};
3373  Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3374  bytes(IdentifierOffsets));
3375 
3376  // In C++, write the list of interesting identifiers (those that are
3377  // defined as macros, poisoned, or similar unusual things).
3378  if (!InterestingIdents.empty())
3379  Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3380 }
3381 
3382 //===----------------------------------------------------------------------===//
3383 // DeclContext's Name Lookup Table Serialization
3384 //===----------------------------------------------------------------------===//
3385 
3386 namespace {
3387 // Trait used for the on-disk hash table used in the method pool.
3388 class ASTDeclContextNameLookupTrait {
3389  ASTWriter &Writer;
3391 
3392 public:
3393  typedef DeclarationNameKey key_type;
3394  typedef key_type key_type_ref;
3395 
3396  /// A start and end index into DeclIDs, representing a sequence of decls.
3397  typedef std::pair<unsigned, unsigned> data_type;
3398  typedef const data_type& data_type_ref;
3399 
3400  typedef unsigned hash_value_type;
3401  typedef unsigned offset_type;
3402 
3403  explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3404 
3405  template<typename Coll>
3406  data_type getData(const Coll &Decls) {
3407  unsigned Start = DeclIDs.size();
3408  for (NamedDecl *D : Decls) {
3409  DeclIDs.push_back(
3410  Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3411  }
3412  return std::make_pair(Start, DeclIDs.size());
3413  }
3414 
3415  data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3416  unsigned Start = DeclIDs.size();
3417  for (auto ID : FromReader)
3418  DeclIDs.push_back(ID);
3419  return std::make_pair(Start, DeclIDs.size());
3420  }
3421 
3422  static bool EqualKey(key_type_ref a, key_type_ref b) {
3423  return a == b;
3424  }
3425 
3426  hash_value_type ComputeHash(DeclarationNameKey Name) {
3427  return Name.getHash();
3428  }
3429 
3430  void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3431  assert(Writer.hasChain() &&
3432  "have reference to loaded module file but no chain?");
3433 
3434  using namespace llvm::support;
3435  endian::Writer<little>(Out)
3436  .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3437  }
3438 
3439  std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3440  DeclarationNameKey Name,
3441  data_type_ref Lookup) {
3442  using namespace llvm::support;
3443  endian::Writer<little> LE(Out);
3444  unsigned KeyLen = 1;
3445  switch (Name.getKind()) {
3451  KeyLen += 4;
3452  break;
3454  KeyLen += 1;
3455  break;
3460  break;
3461  }
3462  LE.write<uint16_t>(KeyLen);
3463 
3464  // 4 bytes for each DeclID.
3465  unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3466  assert(uint16_t(DataLen) == DataLen &&
3467  "too many decls for serialized lookup result");
3468  LE.write<uint16_t>(DataLen);
3469 
3470  return std::make_pair(KeyLen, DataLen);
3471  }
3472 
3473  void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3474  using namespace llvm::support;
3475  endian::Writer<little> LE(Out);
3476  LE.write<uint8_t>(Name.getKind());
3477  switch (Name.getKind()) {
3480  LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3481  return;
3485  LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3486  return;
3488  assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3489  "Invalid operator?");
3490  LE.write<uint8_t>(Name.getOperatorKind());
3491  return;
3496  return;
3497  }
3498 
3499  llvm_unreachable("Invalid name kind?");
3500  }
3501 
3502  void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3503  unsigned DataLen) {
3504  using namespace llvm::support;
3505  endian::Writer<little> LE(Out);
3506  uint64_t Start = Out.tell(); (void)Start;
3507  for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3508  LE.write<uint32_t>(DeclIDs[I]);
3509  assert(Out.tell() - Start == DataLen && "Data length is wrong");
3510  }
3511 };
3512 } // end anonymous namespace
3513 
3514 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3515  DeclContext *DC) {
3516  return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3517 }
3518 
3519 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3520  DeclContext *DC) {
3521  for (auto *D : Result.getLookupResult())
3522  if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3523  return false;
3524 
3525  return true;
3526 }
3527 
3528 void
3529 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3530  llvm::SmallVectorImpl<char> &LookupTable) {
3531  assert(!ConstDC->HasLazyLocalLexicalLookups &&
3532  !ConstDC->HasLazyExternalLexicalLookups &&
3533  "must call buildLookups first");
3534 
3535  // FIXME: We need to build the lookups table, which is logically const.
3536  auto *DC = const_cast<DeclContext*>(ConstDC);
3537  assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3538 
3539  // Create the on-disk hash table representation.
3541  ASTDeclContextNameLookupTrait> Generator;
3542  ASTDeclContextNameLookupTrait Trait(*this);
3543 
3544  // The first step is to collect the declaration names which we need to
3545  // serialize into the name lookup table, and to collect them in a stable
3546  // order.
3548 
3549  // We also build up small sets of the constructor and conversion function
3550  // names which are visible.
3551  llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3552 
3553  for (auto &Lookup : *DC->buildLookup()) {
3554  auto &Name = Lookup.first;
3555  auto &Result = Lookup.second;
3556 
3557  // If there are no local declarations in our lookup result, we
3558  // don't need to write an entry for the name at all. If we can't
3559  // write out a lookup set without performing more deserialization,
3560  // just skip this entry.
3561  if (isLookupResultExternal(Result, DC) &&
3562  isLookupResultEntirelyExternal(Result, DC))
3563  continue;
3564 
3565  // We also skip empty results. If any of the results could be external and
3566  // the currently available results are empty, then all of the results are
3567  // external and we skip it above. So the only way we get here with an empty
3568  // results is when no results could have been external *and* we have
3569  // external results.
3570  //
3571  // FIXME: While we might want to start emitting on-disk entries for negative
3572  // lookups into a decl context as an optimization, today we *have* to skip
3573  // them because there are names with empty lookup results in decl contexts
3574  // which we can't emit in any stable ordering: we lookup constructors and
3575  // conversion functions in the enclosing namespace scope creating empty
3576  // results for them. This in almost certainly a bug in Clang's name lookup,
3577  // but that is likely to be hard or impossible to fix and so we tolerate it
3578  // here by omitting lookups with empty results.
3579  if (Lookup.second.getLookupResult().empty())
3580  continue;
3581 
3582  switch (Lookup.first.getNameKind()) {
3583  default:
3584  Names.push_back(Lookup.first);
3585  break;
3586 
3588  assert(isa<CXXRecordDecl>(DC) &&
3589  "Cannot have a constructor name outside of a class!");
3590  ConstructorNameSet.insert(Name);
3591  break;
3592 
3594  assert(isa<CXXRecordDecl>(DC) &&
3595  "Cannot have a conversion function name outside of a class!");
3596  ConversionNameSet.insert(Name);
3597  break;
3598  }
3599  }
3600 
3601  // Sort the names into a stable order.
3602  std::sort(Names.begin(), Names.end());
3603 
3604  if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3605  // We need to establish an ordering of constructor and conversion function
3606  // names, and they don't have an intrinsic ordering.
3607 
3608  // First we try the easy case by forming the current context's constructor
3609  // name and adding that name first. This is a very useful optimization to
3610  // avoid walking the lexical declarations in many cases, and it also
3611  // handles the only case where a constructor name can come from some other
3612  // lexical context -- when that name is an implicit constructor merged from
3613  // another declaration in the redecl chain. Any non-implicit constructor or
3614  // conversion function which doesn't occur in all the lexical contexts
3615  // would be an ODR violation.
3616  auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3617  Context->getCanonicalType(Context->getRecordType(D)));
3618  if (ConstructorNameSet.erase(ImplicitCtorName))
3619  Names.push_back(ImplicitCtorName);
3620 
3621  // If we still have constructors or conversion functions, we walk all the
3622  // names in the decl and add the constructors and conversion functions
3623  // which are visible in the order they lexically occur within the context.
3624  if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3625  for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3626  if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3627  auto Name = ChildND->getDeclName();
3628  switch (Name.getNameKind()) {
3629  default:
3630  continue;
3631 
3633  if (ConstructorNameSet.erase(Name))
3634  Names.push_back(Name);
3635  break;
3636 
3638  if (ConversionNameSet.erase(Name))
3639  Names.push_back(Name);
3640  break;
3641  }
3642 
3643  if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3644  break;
3645  }
3646 
3647  assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3648  "constructors by walking all the "
3649  "lexical members of the context.");
3650  assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3651  "conversion functions by walking all "
3652  "the lexical members of the context.");
3653  }
3654 
3655  // Next we need to do a lookup with each name into this decl context to fully
3656  // populate any results from external sources. We don't actually use the
3657  // results of these lookups because we only want to use the results after all
3658  // results have been loaded and the pointers into them will be stable.
3659  for (auto &Name : Names)
3660  DC->lookup(Name);
3661 
3662  // Now we need to insert the results for each name into the hash table. For
3663  // constructor names and conversion function names, we actually need to merge
3664  // all of the results for them into one list of results each and insert
3665  // those.
3666  SmallVector<NamedDecl *, 8> ConstructorDecls;
3667  SmallVector<NamedDecl *, 8> ConversionDecls;
3668 
3669  // Now loop over the names, either inserting them or appending for the two
3670  // special cases.
3671  for (auto &Name : Names) {
3672  DeclContext::lookup_result Result = DC->noload_lookup(Name);
3673 
3674  switch (Name.getNameKind()) {
3675  default:
3676  Generator.insert(Name, Trait.getData(Result), Trait);
3677  break;
3678 
3680  ConstructorDecls.append(Result.begin(), Result.end());
3681  break;
3682 
3684  ConversionDecls.append(Result.begin(), Result.end());
3685  break;
3686  }
3687  }
3688 
3689  // Handle our two special cases if we ended up having any. We arbitrarily use
3690  // the first declaration's name here because the name itself isn't part of
3691  // the key, only the kind of name is used.
3692  if (!ConstructorDecls.empty())
3693  Generator.insert(ConstructorDecls.front()->getDeclName(),
3694  Trait.getData(ConstructorDecls), Trait);
3695  if (!ConversionDecls.empty())
3696  Generator.insert(ConversionDecls.front()->getDeclName(),
3697  Trait.getData(ConversionDecls), Trait);
3698 
3699  // Create the on-disk hash table. Also emit the existing imported and
3700  // merged table if there is one.
3701  auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3702  Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
3703 }
3704 
3705 /// \brief Write the block containing all of the declaration IDs
3706 /// visible from the given DeclContext.
3707 ///
3708 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3709 /// bitstream, or 0 if no block was written.
3710 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3711  DeclContext *DC) {
3712  // If we imported a key declaration of this namespace, write the visible
3713  // lookup results as an update record for it rather than including them
3714  // on this declaration. We will only look at key declarations on reload.
3715  if (isa<NamespaceDecl>(DC) && Chain &&
3716  Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3717  // Only do this once, for the first local declaration of the namespace.
3718  for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
3719  Prev = Prev->getPreviousDecl())
3720  if (!Prev->isFromASTFile())
3721  return 0;
3722 
3723  // Note that we need to emit an update record for the primary context.
3724  UpdatedDeclContexts.insert(DC->getPrimaryContext());
3725 
3726  // Make sure all visible decls are written. They will be recorded later. We
3727  // do this using a side data structure so we can sort the names into
3728  // a deterministic order.
3731  LookupResults;
3732  if (Map) {
3733  LookupResults.reserve(Map->size());
3734  for (auto &Entry : *Map)
3735  LookupResults.push_back(
3736  std::make_pair(Entry.first, Entry.second.getLookupResult()));
3737  }
3738 
3739  std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
3740  for (auto &NameAndResult : LookupResults) {
3741  DeclarationName Name = NameAndResult.first;
3742  DeclContext::lookup_result Result = NameAndResult.second;
3745  // We have to work around a name lookup bug here where negative lookup
3746  // results for these names get cached in namespace lookup tables (these
3747  // names should never be looked up in a namespace).
3748  assert(Result.empty() && "Cannot have a constructor or conversion "
3749  "function name in a namespace!");
3750  continue;
3751  }
3752 
3753  for (NamedDecl *ND : Result)
3754  if (!ND->isFromASTFile())
3755  GetDeclRef(ND);
3756  }
3757 
3758  return 0;
3759  }
3760 
3761  if (DC->getPrimaryContext() != DC)
3762  return 0;
3763 
3764  // Skip contexts which don't support name lookup.
3765  if (!DC->isLookupContext())
3766  return 0;
3767 
3768  // If not in C++, we perform name lookup for the translation unit via the
3769  // IdentifierInfo chains, don't bother to build a visible-declarations table.
3770  if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3771  return 0;
3772 
3773  // Serialize the contents of the mapping used for lookup. Note that,
3774  // although we have two very different code paths, the serialized
3775  // representation is the same for both cases: a declaration name,
3776  // followed by a size, followed by references to the visible
3777  // declarations that have that name.
3778  uint64_t Offset = Stream.GetCurrentBitNo();
3779  StoredDeclsMap *Map = DC->buildLookup();
3780  if (!Map || Map->empty())
3781  return 0;
3782 
3783  // Create the on-disk hash table in a buffer.
3784  SmallString<4096> LookupTable;
3785  GenerateNameLookupTable(DC, LookupTable);
3786 
3787  // Write the lookup table
3788  RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
3789  Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3790  LookupTable);
3791  ++NumVisibleDeclContexts;
3792  return Offset;
3793 }
3794 
3795 /// \brief Write an UPDATE_VISIBLE block for the given context.
3796 ///
3797 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3798 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3799 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3800 /// enumeration members (in C++11).
3801 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3802  StoredDeclsMap *Map = DC->getLookupPtr();
3803  if (!Map || Map->empty())
3804  return;
3805 
3806  // Create the on-disk hash table in a buffer.
3807  SmallString<4096> LookupTable;
3808  GenerateNameLookupTable(DC, LookupTable);
3809 
3810  // If we're updating a namespace, select a key declaration as the key for the
3811  // update record; those are the only ones that will be checked on reload.
3812  if (isa<NamespaceDecl>(DC))
3813  DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3814 
3815  // Write the lookup table
3816  RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
3817  Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
3818 }
3819 
3820 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3821 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3822  RecordData::value_type Record[] = {Opts.fp_contract};
3823  Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3824 }
3825 
3826 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3827 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3828  if (!SemaRef.Context.getLangOpts().OpenCL)
3829  return;
3830 
3831  const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3832  RecordData Record;
3833 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
3834 #include "clang/Basic/OpenCLExtensions.def"
3835  Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3836 }
3837 
3838 void ASTWriter::WriteObjCCategories() {
3839  SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3840  RecordData Categories;
3841 
3842  for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3843  unsigned Size = 0;
3844  unsigned StartIndex = Categories.size();
3845 
3846  ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3847 
3848  // Allocate space for the size.
3849  Categories.push_back(0);
3850 
3851  // Add the categories.
3853  Cat = Class->known_categories_begin(),
3854  CatEnd = Class->known_categories_end();
3855  Cat != CatEnd; ++Cat, ++Size) {
3856  assert(getDeclID(*Cat) != 0 && "Bogus category");
3857  AddDeclRef(*Cat, Categories);
3858  }
3859 
3860  // Update the size.
3861  Categories[StartIndex] = Size;
3862 
3863  // Record this interface -> category map.
3864  ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3865  CategoriesMap.push_back(CatInfo);
3866  }
3867 
3868  // Sort the categories map by the definition ID, since the reader will be
3869  // performing binary searches on this information.
3870  llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3871 
3872  // Emit the categories map.
3873  using namespace llvm;
3874 
3875  auto *Abbrev = new BitCodeAbbrev();
3876  Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3877  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3878  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3879  unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3880 
3881  RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
3882  Stream.EmitRecordWithBlob(AbbrevID, Record,
3883  reinterpret_cast<char *>(CategoriesMap.data()),
3884  CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3885 
3886  // Emit the category lists.
3887  Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3888 }
3889 
3890 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3892 
3893  if (LPTMap.empty())
3894  return;
3895 
3896  RecordData Record;
3897  for (auto LPTMapEntry : LPTMap) {
3898  const FunctionDecl *FD = LPTMapEntry.first;
3899  LateParsedTemplate *LPT = LPTMapEntry.second;
3900  AddDeclRef(FD, Record);
3901  AddDeclRef(LPT->D, Record);
3902  Record.push_back(LPT->Toks.size());
3903 
3904  for (const auto &Tok : LPT->Toks) {
3905  AddToken(Tok, Record);
3906  }
3907  }
3908  Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3909 }
3910 
3911 /// \brief Write the state of 'pragma clang optimize' at the end of the module.
3912 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3913  RecordData Record;
3914  SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
3915  AddSourceLocation(PragmaLoc, Record);
3916  Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
3917 }
3918 
3919 /// \brief Write the state of 'pragma ms_struct' at the end of the module.
3920 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
3921  RecordData Record;
3922  Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
3923  Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
3924 }
3925 
3926 /// \brief Write the state of 'pragma pointers_to_members' at the end of the
3927 //module.
3928 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
3929  RecordData Record;
3930  Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
3931  AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
3932  Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
3933 }
3934 
3935 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
3936  ModuleFileExtensionWriter &Writer) {
3937  // Enter the extension block.
3938  Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
3939 
3940  // Emit the metadata record abbreviation.
3941  auto *Abv = new llvm::BitCodeAbbrev();
3942  Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
3943  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3944  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3945  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3946  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3947  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3948  unsigned Abbrev = Stream.EmitAbbrev(Abv);
3949 
3950  // Emit the metadata record.
3951  RecordData Record;
3952  auto Metadata = Writer.getExtension()->getExtensionMetadata();
3953  Record.push_back(EXTENSION_METADATA);
3954  Record.push_back(Metadata.MajorVersion);
3955  Record.push_back(Metadata.MinorVersion);
3956  Record.push_back(Metadata.BlockName.size());
3957  Record.push_back(Metadata.UserInfo.size());
3959  Buffer += Metadata.BlockName;
3960  Buffer += Metadata.UserInfo;
3961  Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
3962 
3963  // Emit the contents of the extension block.
3964  Writer.writeExtensionContents(SemaRef, Stream);
3965 
3966  // Exit the extension block.
3967  Stream.ExitBlock();
3968 }
3969 
3970 //===----------------------------------------------------------------------===//
3971 // General Serialization Routines
3972 //===----------------------------------------------------------------------===//
3973 
3974 /// \brief Emit the list of attributes to the specified record.
3976  auto &Record = *this;
3977  Record.push_back(Attrs.size());
3978  for (const auto *A : Attrs) {
3979  Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
3980  Record.AddSourceRange(A->getRange());
3981 
3982 #include "clang/Serialization/AttrPCHWrite.inc"
3983 
3984  }
3985 }
3986 
3987 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
3988  AddSourceLocation(Tok.getLocation(), Record);
3989  Record.push_back(Tok.getLength());
3990 
3991  // FIXME: When reading literal tokens, reconstruct the literal pointer
3992  // if it is needed.
3993  AddIdentifierRef(Tok.getIdentifierInfo(), Record);
3994  // FIXME: Should translate token kind to a stable encoding.
3995  Record.push_back(Tok.getKind());
3996  // FIXME: Should translate token flags to a stable encoding.
3997  Record.push_back(Tok.getFlags());
3998 }
3999 
4000 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4001  Record.push_back(Str.size());
4002  Record.insert(Record.end(), Str.begin(), Str.end());
4003 }
4004 
4006  assert(Context && "should have context when outputting path");
4007 
4008  bool Changed =
4010 
4011  // Remove a prefix to make the path relative, if relevant.
4012  const char *PathBegin = Path.data();
4013  const char *PathPtr =
4014  adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4015  if (PathPtr != PathBegin) {
4016  Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4017  Changed = true;
4018  }
4019 
4020  return Changed;
4021 }
4022 
4023 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4024  SmallString<128> FilePath(Path);
4025  PreparePathForOutput(FilePath);
4026  AddString(FilePath, Record);
4027 }
4028 
4029 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4030  StringRef Path) {
4031  SmallString<128> FilePath(Path);
4032  PreparePathForOutput(FilePath);
4033  Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4034 }
4035 
4037  RecordDataImpl &Record) {
4038  Record.push_back(Version.getMajor());
4039  if (Optional<unsigned> Minor = Version.getMinor())
4040  Record.push_back(*Minor + 1);
4041  else
4042  Record.push_back(0);
4043  if (Optional<unsigned> Subminor = Version.getSubminor())
4044  Record.push_back(*Subminor + 1);
4045  else
4046  Record.push_back(0);
4047 }
4048 
4049 /// \brief Note that the identifier II occurs at the given offset
4050 /// within the identifier table.
4051 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4052  IdentID ID = IdentifierIDs[II];
4053  // Only store offsets new to this AST file. Other identifier names are looked
4054  // up earlier in the chain and thus don't need an offset.
4055  if (ID >= FirstIdentID)
4056  IdentifierOffsets[ID - FirstIdentID] = Offset;
4057 }
4058 
4059 /// \brief Note that the selector Sel occurs at the given offset
4060 /// within the method pool/selector table.
4061 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4062  unsigned ID = SelectorIDs[Sel];
4063  assert(ID && "Unknown selector");
4064  // Don't record offsets for selectors that are also available in a different
4065  // file.
4066  if (ID < FirstSelectorID)
4067  return;
4068  SelectorOffsets[ID - FirstSelectorID] = Offset;
4069 }
4070 
4072  llvm::BitstreamWriter &Stream,
4074  bool IncludeTimestamps)
4075  : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
4076  WritingModule(nullptr), IncludeTimestamps(IncludeTimestamps),
4077  WritingAST(false), DoneWritingDeclsAndTypes(false),
4078  ASTHasCompilerErrors(false), FirstDeclID(NUM_PREDEF_DECL_IDS),
4079  NextDeclID(FirstDeclID), FirstTypeID(NUM_PREDEF_TYPE_IDS),
4080  NextTypeID(FirstTypeID), FirstIdentID(NUM_PREDEF_IDENT_IDS),
4081  NextIdentID(FirstIdentID), FirstMacroID(NUM_PREDEF_MACRO_IDS),
4082  NextMacroID(FirstMacroID), FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
4083  NextSubmoduleID(FirstSubmoduleID),
4084  FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
4085  NumStatements(0), NumMacros(0),
4086  NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
4087  TypeExtQualAbbrev(0), TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
4088  DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
4089  UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
4090  DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
4091  DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
4092  CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
4093  ExprImplicitCastAbbrev(0) {
4094  for (const auto &Ext : Extensions) {
4095  if (auto Writer = Ext->createExtensionWriter(*this))
4096  ModuleFileExtensionWriters.push_back(std::move(Writer));
4097  }
4098 }
4099 
4101  llvm::DeleteContainerSeconds(FileDeclIDs);
4102 }
4103 
4105  assert(WritingAST && "can't determine lang opts when not writing AST");
4106  return Context->getLangOpts();
4107 }
4108 
4110  return IncludeTimestamps ? E->getModificationTime() : 0;
4111 }
4112 
4113 uint64_t ASTWriter::WriteAST(Sema &SemaRef, const std::string &OutputFile,
4114  Module *WritingModule, StringRef isysroot,
4115  bool hasErrors) {
4116  WritingAST = true;
4117 
4118  ASTHasCompilerErrors = hasErrors;
4119 
4120  // Emit the file header.
4121  Stream.Emit((unsigned)'C', 8);
4122  Stream.Emit((unsigned)'P', 8);
4123  Stream.Emit((unsigned)'C', 8);
4124  Stream.Emit((unsigned)'H', 8);
4125 
4126  WriteBlockInfoBlock();
4127 
4128  Context = &SemaRef.Context;
4129  PP = &SemaRef.PP;
4130  this->WritingModule = WritingModule;
4131  ASTFileSignature Signature =
4132  WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4133  Context = nullptr;
4134  PP = nullptr;
4135  this->WritingModule = nullptr;
4136  this->BaseDirectory.clear();
4137 
4138  WritingAST = false;
4139  return Signature;
4140 }
4141 
4142 template<typename Vector>
4143 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4144  ASTWriter::RecordData &Record) {
4145  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4146  I != E; ++I) {
4147  Writer.AddDeclRef(*I, Record);
4148  }
4149 }
4150 
4151 uint64_t ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4152  const std::string &OutputFile,
4153  Module *WritingModule) {
4154  using namespace llvm;
4155 
4156  bool isModule = WritingModule != nullptr;
4157 
4158  // Make sure that the AST reader knows to finalize itself.
4159  if (Chain)
4160  Chain->finalizeForWriting();
4161 
4162  ASTContext &Context = SemaRef.Context;
4163  Preprocessor &PP = SemaRef.PP;
4164 
4165  // Set up predefined declaration IDs.
4166  auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4167  if (D) {
4168  assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4169  DeclIDs[D] = ID;
4170  }
4171  };
4172  RegisterPredefDecl(Context.getTranslationUnitDecl(),
4174  RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4175  RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4176  RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4177  RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4179  RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4180  RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4181  RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4183  RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4184  RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4185  RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4187  RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4188  RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4190  RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4192  RegisterPredefDecl(Context.CFConstantStringTagDecl,
4194  RegisterPredefDecl(Context.TypePackElementDecl,
4196 
4197  // Build a record containing all of the tentative definitions in this file, in
4198  // TentativeDefinitions order. Generally, this record will be empty for
4199  // headers.
4200  RecordData TentativeDefinitions;
4201  AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4202 
4203  // Build a record containing all of the file scoped decls in this file.
4204  RecordData UnusedFileScopedDecls;
4205  if (!isModule)
4207  UnusedFileScopedDecls);
4208 
4209  // Build a record containing all of the delegating constructors we still need
4210  // to resolve.
4211  RecordData DelegatingCtorDecls;
4212  if (!isModule)
4213  AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4214 
4215  // Write the set of weak, undeclared identifiers. We always write the
4216  // entire table, since later PCH files in a PCH chain are only interested in
4217  // the results at the end of the chain.
4218  RecordData WeakUndeclaredIdentifiers;
4219  for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4220  IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4221  WeakInfo &WI = WeakUndeclaredIdentifier.second;
4222  AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4223  AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4224  AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4225  WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4226  }
4227 
4228  // Build a record containing all of the ext_vector declarations.
4229  RecordData ExtVectorDecls;
4230  AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4231 
4232  // Build a record containing all of the VTable uses information.
4233  RecordData VTableUses;
4234  if (!SemaRef.VTableUses.empty()) {
4235  for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4236  AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4237  AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4238  VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4239  }
4240  }
4241 
4242  // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4243  RecordData UnusedLocalTypedefNameCandidates;
4244  for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4245  AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4246 
4247  // Build a record containing all of pending implicit instantiations.
4248  RecordData PendingInstantiations;
4249  for (const auto &I : SemaRef.PendingInstantiations) {
4250  AddDeclRef(I.first, PendingInstantiations);
4251  AddSourceLocation(I.second, PendingInstantiations);
4252  }
4253  assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4254  "There are local ones at end of translation unit!");
4255 
4256  // Build a record containing some declaration references.
4257  RecordData SemaDeclRefs;
4258  if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4259  AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4260  AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4261  }
4262 
4263  RecordData CUDASpecialDeclRefs;
4264  if (Context.getcudaConfigureCallDecl()) {
4265  AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4266  }
4267 
4268  // Build a record containing all of the known namespaces.
4269  RecordData KnownNamespaces;
4270  for (const auto &I : SemaRef.KnownNamespaces) {
4271  if (!I.second)
4272  AddDeclRef(I.first, KnownNamespaces);
4273  }
4274 
4275  // Build a record of all used, undefined objects that require definitions.
4276  RecordData UndefinedButUsed;
4277 
4279  SemaRef.getUndefinedButUsed(Undefined);
4280  for (const auto &I : Undefined) {
4281  AddDeclRef(I.first, UndefinedButUsed);
4282  AddSourceLocation(I.second, UndefinedButUsed);
4283  }
4284 
4285  // Build a record containing all delete-expressions that we would like to
4286  // analyze later in AST.
4287  RecordData DeleteExprsToAnalyze;
4288 
4289  for (const auto &DeleteExprsInfo :
4290  SemaRef.getMismatchingDeleteExpressions()) {
4291  AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4292  DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4293  for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4294  AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4295  DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4296  }
4297  }
4298 
4299  // Write the control block
4300  uint64_t Signature = WriteControlBlock(PP, Context, isysroot, OutputFile);
4301 
4302  // Write the remaining AST contents.
4303  Stream.EnterSubblock(AST_BLOCK_ID, 5);
4304 
4305  // This is so that older clang versions, before the introduction
4306  // of the control block, can read and reject the newer PCH format.
4307  {
4308  RecordData Record = {VERSION_MAJOR};
4309  Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4310  }
4311 
4312  // Create a lexical update block containing all of the declarations in the
4313  // translation unit that do not come from other AST files.
4314  const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4315  SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4316  for (const auto *D : TU->noload_decls()) {
4317  if (!D->isFromASTFile()) {
4318  NewGlobalKindDeclPairs.push_back(D->getKind());
4319  NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4320  }
4321  }
4322 
4323  auto *Abv = new llvm::BitCodeAbbrev();
4324  Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4325  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4326  unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
4327  {
4328  RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4329  Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4330  bytes(NewGlobalKindDeclPairs));
4331  }
4332 
4333  // And a visible updates block for the translation unit.
4334  Abv = new llvm::BitCodeAbbrev();
4335  Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4336  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4337  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4338  UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4339  WriteDeclContextVisibleUpdate(TU);
4340 
4341  // If we have any extern "C" names, write out a visible update for them.
4342  if (Context.ExternCContext)
4343  WriteDeclContextVisibleUpdate(Context.ExternCContext);
4344 
4345  // If the translation unit has an anonymous namespace, and we don't already
4346  // have an update block for it, write it as an update block.
4347  // FIXME: Why do we not do this if there's already an update block?
4348  if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4349  ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4350  if (Record.empty())
4351  Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4352  }
4353 
4354  // Add update records for all mangling numbers and static local numbers.
4355  // These aren't really update records, but this is a convenient way of
4356  // tagging this rare extra data onto the declarations.
4357  for (const auto &Number : Context.MangleNumbers)
4358  if (!Number.first->isFromASTFile())
4359  DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4360  Number.second));
4361  for (const auto &Number : Context.StaticLocalNumbers)
4362  if (!Number.first->isFromASTFile())
4363  DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4364  Number.second));
4365 
4366  // Make sure visible decls, added to DeclContexts previously loaded from
4367  // an AST file, are registered for serialization.
4368  for (const auto *I : UpdatingVisibleDecls) {
4369  GetDeclRef(I);
4370  }
4371 
4372  // Make sure all decls associated with an identifier are registered for
4373  // serialization, if we're storing decls with identifiers.
4374  if (!WritingModule || !getLangOpts().CPlusPlus) {
4376  for (const auto &ID : PP.getIdentifierTable()) {
4377  const IdentifierInfo *II = ID.second;
4378  if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4379  IIs.push_back(II);
4380  }
4381  // Sort the identifiers to visit based on their name.
4382  std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4383  for (const IdentifierInfo *II : IIs) {
4384  for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4385  DEnd = SemaRef.IdResolver.end();
4386  D != DEnd; ++D) {
4387  GetDeclRef(*D);
4388  }
4389  }
4390  }
4391 
4392  // For method pool in the module, if it contains an entry for a selector,
4393  // the entry should be complete, containing everything introduced by that
4394  // module and all modules it imports. It's possible that the entry is out of
4395  // date, so we need to pull in the new content here.
4396 
4397  // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4398  // safe, we copy all selectors out.
4399  llvm::SmallVector<Selector, 256> AllSelectors;
4400  for (auto &SelectorAndID : SelectorIDs)
4401  AllSelectors.push_back(SelectorAndID.first);
4402  for (auto &Selector : AllSelectors)
4404 
4405  // Form the record of special types.
4406  RecordData SpecialTypes;
4407  AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4408  AddTypeRef(Context.getFILEType(), SpecialTypes);
4409  AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4410  AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4411  AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4412  AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4413  AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4414  AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4415 
4416  if (Chain) {
4417  // Write the mapping information describing our module dependencies and how
4418  // each of those modules were mapped into our own offset/ID space, so that
4419  // the reader can build the appropriate mapping to its own offset/ID space.
4420  // The map consists solely of a blob with the following format:
4421  // *(module-name-len:i16 module-name:len*i8
4422  // source-location-offset:i32
4423  // identifier-id:i32
4424  // preprocessed-entity-id:i32
4425  // macro-definition-id:i32
4426  // submodule-id:i32
4427  // selector-id:i32
4428  // declaration-id:i32
4429  // c++-base-specifiers-id:i32
4430  // type-id:i32)
4431  //
4432  auto *Abbrev = new BitCodeAbbrev();
4433  Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4434  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4435  unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
4437  {
4438  llvm::raw_svector_ostream Out(Buffer);
4439  for (ModuleFile *M : Chain->ModuleMgr) {
4440  using namespace llvm::support;
4441  endian::Writer<little> LE(Out);
4442  StringRef FileName = M->FileName;
4443  LE.write<uint16_t>(FileName.size());
4444  Out.write(FileName.data(), FileName.size());
4445 
4446  // Note: if a base ID was uint max, it would not be possible to load
4447  // another module after it or have more than one entity inside it.
4449 
4450  auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4451  assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4452  if (ShouldWrite)
4453  LE.write<uint32_t>(BaseID);
4454  else
4455  LE.write<uint32_t>(None);
4456  };
4457 
4458  // These values should be unique within a chain, since they will be read
4459  // as keys into ContinuousRangeMaps.
4460  writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4461  writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4462  writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4463  writeBaseIDOrNone(M->BasePreprocessedEntityID,
4465  writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4466  writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4467  writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4468  writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
4469  }
4470  }
4471  RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4472  Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4473  Buffer.data(), Buffer.size());
4474  }
4475 
4476  RecordData DeclUpdatesOffsetsRecord;
4477 
4478  // Keep writing types, declarations, and declaration update records
4479  // until we've emitted all of them.
4480  Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4481  WriteTypeAbbrevs();
4482  WriteDeclAbbrevs();
4483  do {
4484  WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4485  while (!DeclTypesToEmit.empty()) {
4486  DeclOrType DOT = DeclTypesToEmit.front();
4487  DeclTypesToEmit.pop();
4488  if (DOT.isType())
4489  WriteType(DOT.getType());
4490  else
4491  WriteDecl(Context, DOT.getDecl());
4492  }
4493  } while (!DeclUpdates.empty());
4494  Stream.ExitBlock();
4495 
4496  DoneWritingDeclsAndTypes = true;
4497 
4498  // These things can only be done once we've written out decls and types.
4499  WriteTypeDeclOffsets();
4500  if (!DeclUpdatesOffsetsRecord.empty())
4501  Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4502  WriteFileDeclIDsMap();
4503  WriteSourceManagerBlock(Context.getSourceManager(), PP);
4504  WriteComments();
4505  WritePreprocessor(PP, isModule);
4506  WriteHeaderSearch(PP.getHeaderSearchInfo());
4507  WriteSelectors(SemaRef);
4508  WriteReferencedSelectorsPool(SemaRef);
4509  WriteLateParsedTemplates(SemaRef);
4510  WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4511  WriteFPPragmaOptions(SemaRef.getFPOptions());
4512  WriteOpenCLExtensions(SemaRef);
4513  WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
4514 
4515  // If we're emitting a module, write out the submodule information.
4516  if (WritingModule)
4517  WriteSubmodules(WritingModule);
4518 
4519  Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4520 
4521  // Write the record containing external, unnamed definitions.
4522  if (!EagerlyDeserializedDecls.empty())
4523  Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4524 
4525  // Write the record containing tentative definitions.
4526  if (!TentativeDefinitions.empty())
4527  Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4528 
4529  // Write the record containing unused file scoped decls.
4530  if (!UnusedFileScopedDecls.empty())
4531  Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4532 
4533  // Write the record containing weak undeclared identifiers.
4534  if (!WeakUndeclaredIdentifiers.empty())
4535  Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4536  WeakUndeclaredIdentifiers);
4537 
4538  // Write the record containing ext_vector type names.
4539  if (!ExtVectorDecls.empty())
4540  Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4541 
4542  // Write the record containing VTable uses information.
4543  if (!VTableUses.empty())
4544  Stream.EmitRecord(VTABLE_USES, VTableUses);
4545 
4546  // Write the record containing potentially unused local typedefs.
4547  if (!UnusedLocalTypedefNameCandidates.empty())
4548  Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4549  UnusedLocalTypedefNameCandidates);
4550 
4551  // Write the record containing pending implicit instantiations.
4552  if (!PendingInstantiations.empty())
4553  Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4554 
4555  // Write the record containing declaration references of Sema.
4556  if (!SemaDeclRefs.empty())
4557  Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4558 
4559  // Write the record containing CUDA-specific declaration references.
4560  if (!CUDASpecialDeclRefs.empty())
4561  Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4562 
4563  // Write the delegating constructors.
4564  if (!DelegatingCtorDecls.empty())
4565  Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4566 
4567  // Write the known namespaces.
4568  if (!KnownNamespaces.empty())
4569  Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4570 
4571  // Write the undefined internal functions and variables, and inline functions.
4572  if (!UndefinedButUsed.empty())
4573  Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4574 
4575  if (!DeleteExprsToAnalyze.empty())
4576  Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4577 
4578  // Write the visible updates to DeclContexts.
4579  for (auto *DC : UpdatedDeclContexts)
4580  WriteDeclContextVisibleUpdate(DC);
4581 
4582  if (!WritingModule) {
4583  // Write the submodules that were imported, if any.
4584  struct ModuleInfo {
4585  uint64_t ID;
4586  Module *M;
4587  ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4588  };
4590  for (const auto *I : Context.local_imports()) {
4591  assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4592  Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4593  I->getImportedModule()));
4594  }
4595 
4596  if (!Imports.empty()) {
4597  auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4598  return A.ID < B.ID;
4599  };
4600  auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4601  return A.ID == B.ID;
4602  };
4603 
4604  // Sort and deduplicate module IDs.
4605  std::sort(Imports.begin(), Imports.end(), Cmp);
4606  Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
4607  Imports.end());
4608 
4609  RecordData ImportedModules;
4610  for (const auto &Import : Imports) {
4611  ImportedModules.push_back(Import.ID);
4612  // FIXME: If the module has macros imported then later has declarations
4613  // imported, this location won't be the right one as a location for the
4614  // declaration imports.
4615  AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
4616  }
4617 
4618  Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4619  }
4620  }
4621 
4622  WriteObjCCategories();
4623  if(!WritingModule) {
4624  WriteOptimizePragmaOptions(SemaRef);
4625  WriteMSStructPragmaOptions(SemaRef);
4626  WriteMSPointersToMembersPragmaOptions(SemaRef);
4627  }
4628 
4629  // Some simple statistics
4630  RecordData::value_type Record[] = {
4631  NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
4632  Stream.EmitRecord(STATISTICS, Record);
4633  Stream.ExitBlock();
4634 
4635  // Write the module file extension blocks.
4636  for (const auto &ExtWriter : ModuleFileExtensionWriters)
4637  WriteModuleFileExtension(SemaRef, *ExtWriter);
4638 
4639  return Signature;
4640 }
4641 
4642 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4643  if (DeclUpdates.empty())
4644  return;
4645 
4646  DeclUpdateMap LocalUpdates;
4647  LocalUpdates.swap(DeclUpdates);
4648 
4649  for (auto &DeclUpdate : LocalUpdates) {
4650  const Decl *D = DeclUpdate.first;
4651 
4652  bool HasUpdatedBody = false;
4654  ASTRecordWriter Record(*this, RecordData);
4655  for (auto &Update : DeclUpdate.second) {
4656  DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4657 
4658  // An updated body is emitted last, so that the reader doesn't need
4659  // to skip over the lazy body to reach statements for other records.
4661  HasUpdatedBody = true;
4662  else
4663  Record.push_back(Kind);
4664 
4665  switch (Kind) {
4669  assert(Update.getDecl() && "no decl to add?");
4670  Record.push_back(GetDeclRef(Update.getDecl()));
4671  break;
4672 
4674  break;
4675 
4677  Record.AddSourceLocation(Update.getLoc());
4678  break;
4679 
4681  Record.AddStmt(const_cast<Expr *>(
4682  cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
4683  break;
4684 
4686  auto *RD = cast<CXXRecordDecl>(D);
4687  UpdatedDeclContexts.insert(RD->getPrimaryContext());
4688  Record.AddCXXDefinitionData(RD);
4689  Record.AddOffset(WriteDeclContextLexicalBlock(
4690  *Context, const_cast<CXXRecordDecl *>(RD)));
4691 
4692  // This state is sometimes updated by template instantiation, when we
4693  // switch from the specialization referring to the template declaration
4694  // to it referring to the template definition.
4695  if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4696  Record.push_back(MSInfo->getTemplateSpecializationKind());
4697  Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
4698  } else {
4699  auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4700  Record.push_back(Spec->getTemplateSpecializationKind());
4701  Record.AddSourceLocation(Spec->getPointOfInstantiation());
4702 
4703  // The instantiation might have been resolved to a partial
4704  // specialization. If so, record which one.
4705  auto From = Spec->getInstantiatedFrom();
4706  if (auto PartialSpec =
4707  From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4708  Record.push_back(true);
4709  Record.AddDeclRef(PartialSpec);
4710  Record.AddTemplateArgumentList(
4711  &Spec->getTemplateInstantiationArgs());
4712  } else {
4713  Record.push_back(false);
4714  }
4715  }
4716  Record.push_back(RD->getTagKind());
4717  Record.AddSourceLocation(RD->getLocation());
4718  Record.AddSourceLocation(RD->getLocStart());
4719  Record.AddSourceRange(RD->getBraceRange());
4720 
4721  // Instantiation may change attributes; write them all out afresh.
4722  Record.push_back(D->hasAttrs());
4723  if (D->hasAttrs())
4724  Record.AddAttributes(D->getAttrs());
4725 
4726  // FIXME: Ensure we don't get here for explicit instantiations.
4727  break;
4728  }
4729 
4731  Record.AddDeclRef(Update.getDecl());
4732  break;
4733 
4736  cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4737  Record);
4738  break;
4739 
4741  Record.push_back(GetOrCreateTypeID(Update.getType()));
4742  break;
4743 
4744  case UPD_DECL_MARKED_USED:
4745  break;
4746 
4747  case UPD_MANGLING_NUMBER:
4749  Record.push_back(Update.getNumber());
4750  break;
4751 
4753  Record.AddSourceRange(
4754  D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
4755  break;
4756 
4758  Record.AddSourceRange(
4759  D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
4760  break;
4761 
4762  case UPD_DECL_EXPORTED:
4763  Record.push_back(getSubmoduleID(Update.getModule()));
4764  break;
4765 
4767  Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
4768  break;
4769  }
4770  }
4771 
4772  if (HasUpdatedBody) {
4773  const auto *Def = cast<FunctionDecl>(D);
4774  Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
4775  Record.push_back(Def->isInlined());
4776  Record.AddSourceLocation(Def->getInnerLocStart());
4777  Record.AddFunctionDefinition(Def);
4778  }
4779 
4780  OffsetsRecord.push_back(GetDeclRef(D));
4781  OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
4782  }
4783 }
4784 
4786  uint32_t Raw = Loc.getRawEncoding();
4787  Record.push_back((Raw << 1) | (Raw >> 31));
4788 }
4789 
4791  AddSourceLocation(Range.getBegin(), Record);
4792  AddSourceLocation(Range.getEnd(), Record);
4793 }
4794 
4795 void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
4796  Record->push_back(Value.getBitWidth());
4797  const uint64_t *Words = Value.getRawData();
4798  Record->append(Words, Words + Value.getNumWords());
4799 }
4800 
4801 void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
4802  Record->push_back(Value.isUnsigned());
4803  AddAPInt(Value);
4804 }
4805 
4806 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
4807  AddAPInt(Value.bitcastToAPInt());
4808 }
4809 
4811  Record.push_back(getIdentifierRef(II));
4812 }
4813 
4815  if (!II)
4816  return 0;
4817 
4818  IdentID &ID = IdentifierIDs[II];
4819  if (ID == 0)
4820  ID = NextIdentID++;
4821  return ID;
4822 }
4823 
4825  // Don't emit builtin macros like __LINE__ to the AST file unless they
4826  // have been redefined by the header (in which case they are not
4827  // isBuiltinMacro).
4828  if (!MI || MI->isBuiltinMacro())
4829  return 0;
4830 
4831  MacroID &ID = MacroIDs[MI];
4832  if (ID == 0) {
4833  ID = NextMacroID++;
4834  MacroInfoToEmitData Info = { Name, MI, ID };
4835  MacroInfosToEmit.push_back(Info);
4836  }
4837  return ID;
4838 }
4839 
4841  if (!MI || MI->isBuiltinMacro())
4842  return 0;
4843 
4844  assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4845  return MacroIDs[MI];
4846 }
4847 
4849  return IdentMacroDirectivesOffsetMap.lookup(Name);
4850 }
4851 
4853  Record->push_back(Writer->getSelectorRef(SelRef));
4854 }
4855 
4857  if (Sel.getAsOpaquePtr() == nullptr) {
4858  return 0;
4859  }
4860 
4861  SelectorID SID = SelectorIDs[Sel];
4862  if (SID == 0 && Chain) {
4863  // This might trigger a ReadSelector callback, which will set the ID for
4864  // this selector.
4865  Chain->LoadSelector(Sel);
4866  SID = SelectorIDs[Sel];
4867  }
4868  if (SID == 0) {
4869  SID = NextSelectorID++;
4870  SelectorIDs[Sel] = SID;
4871  }
4872  return SID;
4873 }
4874 
4876  AddDeclRef(Temp->getDestructor());
4877 }
4878 
4881  switch (Kind) {
4883  AddStmt(Arg.getAsExpr());
4884  break;
4886  AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
4887  break;
4889  AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
4891  break;
4893  AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
4896  break;
4902  // FIXME: Is this right?
4903  break;
4904  }
4905 }
4906 
4908  AddTemplateArgument(Arg.getArgument());
4909 
4911  bool InfoHasSameExpr
4912  = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4913  Record->push_back(InfoHasSameExpr);
4914  if (InfoHasSameExpr)
4915  return; // Avoid storing the same expr twice.
4916  }
4917  AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
4918 }
4919 
4921  if (!TInfo) {
4922  AddTypeRef(QualType());
4923  return;
4924  }
4925 
4926  AddTypeLoc(TInfo->getTypeLoc());
4927 }
4928 
4930  AddTypeRef(TL.getType());
4931 
4932  TypeLocWriter TLW(*this);
4933  for (; !TL.isNull(); TL = TL.getNextTypeLoc())
4934  TLW.Visit(TL);
4935 }
4936 
4938  Record.push_back(GetOrCreateTypeID(T));
4939 }
4940 
4942  assert(Context);
4943  return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4944  if (T.isNull())
4945  return TypeIdx();
4946  assert(!T.getLocalFastQualifiers());
4947 
4948  TypeIdx &Idx = TypeIdxs[T];
4949  if (Idx.getIndex() == 0) {
4950  if (DoneWritingDeclsAndTypes) {
4951  assert(0 && "New type seen after serializing all the types to emit!");
4952  return TypeIdx();
4953  }
4954 
4955  // We haven't seen this type before. Assign it a new ID and put it
4956  // into the queue of types to emit.
4957  Idx = TypeIdx(NextTypeID++);
4958  DeclTypesToEmit.push(T);
4959  }
4960  return Idx;
4961  });
4962 }
4963 
4965  assert(Context);
4966  return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4967  if (T.isNull())
4968  return TypeIdx();
4969  assert(!T.getLocalFastQualifiers());
4970 
4971  TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4972  assert(I != TypeIdxs.end() && "Type not emitted!");
4973  return I->second;
4974  });
4975 }
4976 
4977 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
4978  Record.push_back(GetDeclRef(D));
4979 }
4980 
4982  assert(WritingAST && "Cannot request a declaration ID before AST writing");
4983 
4984  if (!D) {
4985  return 0;
4986  }
4987 
4988  // If D comes from an AST file, its declaration ID is already known and
4989  // fixed.
4990  if (D->isFromASTFile())
4991  return D->getGlobalID();
4992 
4993  assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
4994  DeclID &ID = DeclIDs[D];
4995  if (ID == 0) {
4996  if (DoneWritingDeclsAndTypes) {
4997  assert(0 && "New decl seen after serializing all the decls to emit!");
4998  return 0;
4999  }
5000 
5001  // We haven't seen this declaration before. Give it a new ID and
5002  // enqueue it in the list of declarations to emit.
5003  ID = NextDeclID++;
5004  DeclTypesToEmit.push(const_cast<Decl *>(D));
5005  }
5006 
5007  return ID;
5008 }
5009 
5011  if (!D)
5012  return 0;
5013 
5014  // If D comes from an AST file, its declaration ID is already known and
5015  // fixed.
5016  if (D->isFromASTFile())
5017  return D->getGlobalID();
5018 
5019  assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5020  return DeclIDs[D];
5021 }
5022 
5023 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5024  assert(ID);
5025  assert(D);
5026 
5027  SourceLocation Loc = D->getLocation();
5028  if (Loc.isInvalid())
5029  return;
5030 
5031  // We only keep track of the file-level declarations of each file.
5032  if (!D->getLexicalDeclContext()->isFileContext())
5033  return;
5034  // FIXME: ParmVarDecls that are part of a function type of a parameter of
5035  // a function/objc method, should not have TU as lexical context.
5036  if (isa<ParmVarDecl>(D))
5037  return;
5038 
5039  SourceManager &SM = Context->getSourceManager();
5040  SourceLocation FileLoc = SM.getFileLoc(Loc);
5041  assert(SM.isLocalSourceLocation(FileLoc));
5042  FileID FID;
5043  unsigned Offset;
5044  std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5045  if (FID.isInvalid())
5046  return;
5047  assert(SM.getSLocEntry(FID).isFile());
5048 
5049  DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5050  if (!Info)
5051  Info = new DeclIDInFileInfo();
5052 
5053  std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5054  LocDeclIDsTy &Decls = Info->DeclIDs;
5055 
5056  if (Decls.empty() || Decls.back().first <= Offset) {
5057  Decls.push_back(LocDecl);
5058  return;
5059  }
5060 
5062  std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
5063 
5064  Decls.insert(I, LocDecl);
5065 }
5066 
5068  // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
5069  Record->push_back(Name.getNameKind());
5070  switch (Name.getNameKind()) {
5073  break;
5074 
5078  AddSelectorRef(Name.getObjCSelector());
5079  break;
5080 
5084  AddTypeRef(Name.getCXXNameType());
5085  break;
5086 
5088  Record->push_back(Name.getCXXOverloadedOperator());
5089  break;
5090 
5093  break;
5094 
5096  // No extra data to emit
5097  break;
5098  }
5099 }
5100 
5102  assert(needsAnonymousDeclarationNumber(D) &&
5103  "expected an anonymous declaration");
5104 
5105  // Number the anonymous declarations within this context, if we've not
5106  // already done so.
5107  auto It = AnonymousDeclarationNumbers.find(D);
5108  if (It == AnonymousDeclarationNumbers.end()) {
5109  auto *DC = D->getLexicalDeclContext();
5110  numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5111  AnonymousDeclarationNumbers[ND] = Number;
5112  });
5113 
5114  It = AnonymousDeclarationNumbers.find(D);
5115  assert(It != AnonymousDeclarationNumbers.end() &&
5116  "declaration not found within its lexical context");
5117  }
5118 
5119  return It->second;
5120 }
5121 
5123  DeclarationName Name) {
5124  switch (Name.getNameKind()) {
5128  AddTypeSourceInfo(DNLoc.NamedType.TInfo);
5129  break;
5130 
5136  break;
5137 
5141  break;
5142 
5148  break;
5149  }
5150 }
5151 
5153  const DeclarationNameInfo &NameInfo) {
5154  AddDeclarationName(NameInfo.getName());
5155  AddSourceLocation(NameInfo.getLoc());
5156  AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5157 }
5158 
5160  AddNestedNameSpecifierLoc(Info.QualifierLoc);
5161  Record->push_back(Info.NumTemplParamLists);
5162  for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
5163  AddTemplateParameterList(Info.TemplParamLists[i]);
5164 }
5165 
5167  // Nested name specifiers usually aren't too long. I think that 8 would
5168  // typically accommodate the vast majority.
5170 
5171  // Push each of the NNS's onto a stack for serialization in reverse order.
5172  while (NNS) {
5173  NestedNames.push_back(NNS);
5174  NNS = NNS->getPrefix();
5175  }
5176 
5177  Record->push_back(NestedNames.size());
5178  while(!NestedNames.empty()) {
5179  NNS = NestedNames.pop_back_val();
5181  Record->push_back(Kind);
5182  switch (Kind) {
5185  break;
5186 
5188  AddDeclRef(NNS->getAsNamespace());
5189  break;
5190 
5193  break;
5194 
5197  AddTypeRef(QualType(NNS->getAsType(), 0));
5198  Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5199  break;
5200 
5202  // Don't need to write an associated value.
5203  break;
5204 
5206  AddDeclRef(NNS->getAsRecordDecl());
5207  break;
5208  }
5209  }
5210 }
5211 
5213  // Nested name specifiers usually aren't too long. I think that 8 would
5214  // typically accommodate the vast majority.
5216 
5217  // Push each of the nested-name-specifiers's onto a stack for
5218  // serialization in reverse order.
5219  while (NNS) {
5220  NestedNames.push_back(NNS);
5221  NNS = NNS.getPrefix();
5222  }
5223 
5224  Record->push_back(NestedNames.size());
5225  while(!NestedNames.empty()) {
5226  NNS = NestedNames.pop_back_val();
5228  = NNS.getNestedNameSpecifier()->getKind();
5229  Record->push_back(Kind);
5230  switch (Kind) {
5234  break;
5235 
5239  break;
5240 
5244  break;
5245 
5248  Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5249  AddTypeLoc(NNS.getTypeLoc());
5251  break;
5252 
5255  break;
5256 
5260  break;
5261  }
5262  }
5263 }
5264 
5266  TemplateName::NameKind Kind = Name.getKind();
5267  Record->push_back(Kind);
5268  switch (Kind) {
5270  AddDeclRef(Name.getAsTemplateDecl());
5271  break;
5272 
5275  Record->push_back(OvT->size());
5276  for (const auto &I : *OvT)
5277  AddDeclRef(I);
5278  break;
5279  }
5280 
5283  AddNestedNameSpecifier(QualT->getQualifier());
5284  Record->push_back(QualT->hasTemplateKeyword());
5285  AddDeclRef(QualT->getTemplateDecl());
5286  break;
5287  }
5288 
5291  AddNestedNameSpecifier(DepT->getQualifier());
5292  Record->push_back(DepT->isIdentifier());
5293  if (DepT->isIdentifier())
5295  else
5296  Record->push_back(DepT->getOperator());
5297  break;
5298  }
5299 
5303  AddDeclRef(subst->getParameter());
5304  AddTemplateName(subst->getReplacement());
5305  break;
5306  }
5307 
5311  AddDeclRef(SubstPack->getParameterPack());
5312  AddTemplateArgument(SubstPack->getArgumentPack());
5313  break;
5314  }
5315  }
5316 }
5317 
5319  Record->push_back(Arg.getKind());
5320  switch (Arg.getKind()) {
5322  break;
5324  AddTypeRef(Arg.getAsType());
5325  break;
5327  AddDeclRef(Arg.getAsDecl());
5329  break;
5331  AddTypeRef(Arg.getNullPtrType());
5332  break;
5334  AddAPSInt(Arg.getAsIntegral());
5335  AddTypeRef(Arg.getIntegralType());
5336  break;
5338  AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5339  break;
5341  AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5342  if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5343  Record->push_back(*NumExpansions + 1);
5344  else
5345  Record->push_back(0);
5346  break;
5348  AddStmt(Arg.getAsExpr());
5349  break;
5351  Record->push_back(Arg.pack_size());
5352  for (const auto &P : Arg.pack_elements())
5353  AddTemplateArgument(P);
5354  break;
5355  }
5356 }
5357 
5359  const TemplateParameterList *TemplateParams) {
5360  assert(TemplateParams && "No TemplateParams!");
5361  AddSourceLocation(TemplateParams->getTemplateLoc());
5362  AddSourceLocation(TemplateParams->getLAngleLoc());
5363  AddSourceLocation(TemplateParams->getRAngleLoc());
5364  Record->push_back(TemplateParams->size());
5365  for (const auto &P : *TemplateParams)
5366  AddDeclRef(P);
5367 }
5368 
5369 /// \brief Emit a template argument list.
5371  const TemplateArgumentList *TemplateArgs) {
5372  assert(TemplateArgs && "No TemplateArgs!");
5373  Record->push_back(TemplateArgs->size());
5374  for (int i=0, e = TemplateArgs->size(); i != e; ++i)
5375  AddTemplateArgument(TemplateArgs->get(i));
5376 }
5377 
5379  const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5380  assert(ASTTemplArgList && "No ASTTemplArgList!");
5381  AddSourceLocation(ASTTemplArgList->LAngleLoc);
5382  AddSourceLocation(ASTTemplArgList->RAngleLoc);
5383  Record->push_back(ASTTemplArgList->NumTemplateArgs);
5384  const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5385  for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5386  AddTemplateArgumentLoc(TemplArgs[i]);
5387 }
5388 
5390  Record->push_back(Set.size());
5392  I = Set.begin(), E = Set.end(); I != E; ++I) {
5393  AddDeclRef(I.getDecl());
5394  Record->push_back(I.getAccess());
5395  }
5396 }
5397 
5398 // FIXME: Move this out of the main ASTRecordWriter interface.
5400  Record->push_back(Base.isVirtual());
5401  Record->push_back(Base.isBaseOfClass());
5402  Record->push_back(Base.getAccessSpecifierAsWritten());
5403  Record->push_back(Base.getInheritConstructors());
5404  AddTypeSourceInfo(Base.getTypeSourceInfo());
5407  : SourceLocation());
5408 }
5409 
5412  ASTWriter::RecordData Record;
5413  ASTRecordWriter Writer(W, Record);
5414  Writer.push_back(Bases.size());
5415 
5416  for (auto &Base : Bases)
5417  Writer.AddCXXBaseSpecifier(Base);
5418 
5420 }
5421 
5422 // FIXME: Move this out of the main ASTRecordWriter interface.
5424  AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5425 }
5426 
5427 static uint64_t
5429  ArrayRef<CXXCtorInitializer *> CtorInits) {
5430  ASTWriter::RecordData Record;
5431  ASTRecordWriter Writer(W, Record);
5432  Writer.push_back(CtorInits.size());
5433 
5434  for (auto *Init : CtorInits) {
5435  if (Init->isBaseInitializer()) {
5437  Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5438  Writer.push_back(Init->isBaseVirtual());
5439  } else if (Init->isDelegatingInitializer()) {
5441  Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5442  } else if (Init->isMemberInitializer()){
5444  Writer.AddDeclRef(Init->getMember());
5445  } else {
5447  Writer.AddDeclRef(Init->getIndirectMember());
5448  }
5449 
5450  Writer.AddSourceLocation(Init->getMemberLocation());
5451  Writer.AddStmt(Init->getInit());
5452  Writer.AddSourceLocation(Init->getLParenLoc());
5453  Writer.AddSourceLocation(Init->getRParenLoc());
5454  Writer.push_back(Init->isWritten());
5455  if (Init->isWritten()) {
5456  Writer.push_back(Init->getSourceOrder());
5457  } else {
5458  Writer.push_back(Init->getNumArrayIndices());
5459  for (auto *VD : Init->getArrayIndices())
5460  Writer.AddDeclRef(VD);
5461  }
5462  }
5463 
5465 }
5466 
5467 // FIXME: Move this out of the main ASTRecordWriter interface.
5469  ArrayRef<CXXCtorInitializer *> CtorInits) {
5470  AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
5471 }
5472 
5474  auto &Data = D->data();
5475  Record->push_back(Data.IsLambda);
5476  Record->push_back(Data.UserDeclaredConstructor);
5477  Record->push_back(Data.UserDeclaredSpecialMembers);
5478  Record->push_back(Data.Aggregate);
5479  Record->push_back(Data.PlainOldData);
5480  Record->push_back(Data.Empty);
5481  Record->push_back(Data.Polymorphic);
5482  Record->push_back(Data.Abstract);
5483  Record->push_back(Data.IsStandardLayout);
5484  Record->push_back(Data.HasNoNonEmptyBases);
5485  Record->push_back(Data.HasPrivateFields);
5486  Record->push_back(Data.HasProtectedFields);
5487  Record->push_back(Data.HasPublicFields);
5488  Record->push_back(Data.HasMutableFields);
5489  Record->push_back(Data.HasVariantMembers);
5490  Record->push_back(Data.HasOnlyCMembers);
5491  Record->push_back(Data.HasInClassInitializer);
5492  Record->push_back(Data.HasUninitializedReferenceMember);
5493  Record->push_back(Data.HasUninitializedFields);
5494  Record->push_back(Data.HasInheritedConstructor);
5495  Record->push_back(Data.HasInheritedAssignment);
5496  Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
5497  Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
5498  Record->push_back(Data.NeedOverloadResolutionForDestructor);
5499  Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
5500  Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
5501  Record->push_back(Data.DefaultedDestructorIsDeleted);
5502  Record->push_back(Data.HasTrivialSpecialMembers);
5503  Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
5504  Record->push_back(Data.HasIrrelevantDestructor);
5505  Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
5506  Record->push_back(Data.HasDefaultedDefaultConstructor);
5507  Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5508  Record->push_back(Data.HasConstexprDefaultConstructor);
5509  Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
5510  Record->push_back(Data.ComputedVisibleConversions);
5511  Record->push_back(Data.UserProvidedDefaultConstructor);
5512  Record->push_back(Data.DeclaredSpecialMembers);
5513  Record->push_back(Data.ImplicitCopyConstructorHasConstParam);
5514  Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
5515  Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5516  Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5517  // IsLambda bit is already saved.
5518 
5519  Record->push_back(Data.NumBases);
5520  if (Data.NumBases > 0)
5521  AddCXXBaseSpecifiers(Data.bases());
5522 
5523  // FIXME: Make VBases lazily computed when needed to avoid storing them.
5524  Record->push_back(Data.NumVBases);
5525  if (Data.NumVBases > 0)
5526  AddCXXBaseSpecifiers(Data.vbases());
5527 
5528  AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5529  AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
5530  // Data.Definition is the owning decl, no need to write it.
5531  AddDeclRef(D->getFirstFriend());
5532 
5533  // Add lambda-specific data.
5534  if (Data.IsLambda) {
5535  auto &Lambda = D->getLambdaData();
5536  Record->push_back(Lambda.Dependent);
5537  Record->push_back(Lambda.IsGenericLambda);
5538  Record->push_back(Lambda.CaptureDefault);
5539  Record->push_back(Lambda.NumCaptures);
5540  Record->push_back(Lambda.NumExplicitCaptures);
5541  Record->push_back(Lambda.ManglingNumber);
5542  AddDeclRef(Lambda.ContextDecl);
5543  AddTypeSourceInfo(Lambda.MethodTyInfo);
5544  for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5545  const LambdaCapture &Capture = Lambda.Captures[I];
5546  AddSourceLocation(Capture.getLocation());
5547  Record->push_back(Capture.isImplicit());
5548  Record->push_back(Capture.getCaptureKind());
5549  switch (Capture.getCaptureKind()) {
5550  case LCK_StarThis:
5551  case LCK_This:
5552  case LCK_VLAType:
5553  break;
5554  case LCK_ByCopy:
5555  case LCK_ByRef:
5556  VarDecl *Var =
5557  Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5558  AddDeclRef(Var);
5559  AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5560  : SourceLocation());
5561  break;
5562  }
5563  }
5564  }
5565 }
5566 
5567 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5568  assert(Reader && "Cannot remove chain");
5569  assert((!Chain || Chain == Reader) && "Cannot replace chain");
5570  assert(FirstDeclID == NextDeclID &&
5571  FirstTypeID == NextTypeID &&
5572  FirstIdentID == NextIdentID &&
5573  FirstMacroID == NextMacroID &&
5574  FirstSubmoduleID == NextSubmoduleID &&
5575  FirstSelectorID == NextSelectorID &&
5576  "Setting chain after writing has started.");
5577 
5578  Chain = Reader;
5579 
5580  // Note, this will get called multiple times, once one the reader starts up
5581  // and again each time it's done reading a PCH or module.
5582  FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5583  FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5584  FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5585  FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5586  FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5587  FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5588  NextDeclID = FirstDeclID;
5589  NextTypeID = FirstTypeID;
5590  NextIdentID = FirstIdentID;
5591  NextMacroID = FirstMacroID;
5592  NextSelectorID = FirstSelectorID;
5593  NextSubmoduleID = FirstSubmoduleID;
5594 }
5595 
5596 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5597  // Always keep the highest ID. See \p TypeRead() for more information.
5598  IdentID &StoredID = IdentifierIDs[II];
5599  if (ID > StoredID)
5600  StoredID = ID;
5601 }
5602 
5603 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5604  // Always keep the highest ID. See \p TypeRead() for more information.
5605  MacroID &StoredID = MacroIDs[MI];
5606  if (ID > StoredID)
5607  StoredID = ID;
5608 }
5609 
5610 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5611  // Always take the highest-numbered type index. This copes with an interesting
5612  // case for chained AST writing where we schedule writing the type and then,
5613  // later, deserialize the type from another AST. In this case, we want to
5614  // keep the higher-numbered entry so that we can properly write it out to
5615  // the AST file.
5616  TypeIdx &StoredIdx = TypeIdxs[T];
5617  if (Idx.getIndex() >= StoredIdx.getIndex())
5618  StoredIdx = Idx;
5619 }
5620 
5621 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5622  // Always keep the highest ID. See \p TypeRead() for more information.
5623  SelectorID &StoredID = SelectorIDs[S];
5624  if (ID > StoredID)
5625  StoredID = ID;
5626 }
5627 
5628 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5629  MacroDefinitionRecord *MD) {
5630  assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5631  MacroDefinitions[MD] = ID;
5632 }
5633 
5634 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5635  assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5636  SubmoduleIDs[Mod] = ID;
5637 }
5638 
5639 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5640  if (Chain && Chain->isProcessingUpdateRecords()) return;
5641  assert(D->isCompleteDefinition());
5642  assert(!WritingAST && "Already writing the AST!");
5643  if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5644  // We are interested when a PCH decl is modified.
5645  if (RD->isFromASTFile()) {
5646  // A forward reference was mutated into a definition. Rewrite it.
5647  // FIXME: This happens during template instantiation, should we
5648  // have created a new definition decl instead ?
5649  assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5650  "completed a tag from another module but not by instantiation?");
5651  DeclUpdates[RD].push_back(
5653  }
5654  }
5655 }
5656 
5657 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5658  if (D->isFromASTFile())
5659  return true;
5660 
5661  // The predefined __va_list_tag struct is imported if we imported any decls.
5662  // FIXME: This is a gross hack.
5663  return D == D->getASTContext().getVaListTagDecl();
5664 }
5665 
5666 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5667  if (Chain && Chain->isProcessingUpdateRecords()) return;
5668  assert(DC->isLookupContext() &&
5669  "Should not add lookup results to non-lookup contexts!");
5670 
5671  // TU is handled elsewhere.
5672  if (isa<TranslationUnitDecl>(DC))
5673  return;
5674 
5675  // Namespaces are handled elsewhere, except for template instantiations of
5676  // FunctionTemplateDecls in namespaces. We are interested in cases where the
5677  // local instantiations are added to an imported context. Only happens when
5678  // adding ADL lookup candidates, for example templated friends.
5679  if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5680  !isa<FunctionTemplateDecl>(D))
5681  return;
5682 
5683  // We're only interested in cases where a local declaration is added to an
5684  // imported context.
5685  if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5686  return;
5687 
5688  assert(DC == DC->getPrimaryContext() && "added to non-primary context");
5689  assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5690  assert(!WritingAST && "Already writing the AST!");
5691  if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5692  // We're adding a visible declaration to a predefined decl context. Ensure
5693  // that we write out all of its lookup results so we don't get a nasty
5694  // surprise when we try to emit its lookup table.
5695  for (auto *Child : DC->decls())
5696  UpdatingVisibleDecls.push_back(Child);
5697  }
5698  UpdatingVisibleDecls.push_back(D);
5699 }
5700 
5701 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5702  if (Chain && Chain->isProcessingUpdateRecords()) return;
5703  assert(D->isImplicit());
5704 
5705  // We're only interested in cases where a local declaration is added to an
5706  // imported context.
5707  if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5708  return;
5709 
5710  if (!isa<CXXMethodDecl>(D))
5711  return;
5712 
5713  // A decl coming from PCH was modified.
5714  assert(RD->isCompleteDefinition());
5715  assert(!WritingAST && "Already writing the AST!");
5716  DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5717 }
5718 
5719 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5720  if (Chain && Chain->isProcessingUpdateRecords()) return;
5721  assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5722  if (!Chain) return;
5723  Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5724  // If we don't already know the exception specification for this redecl
5725  // chain, add an update record for it.
5726  if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5727  ->getType()
5728  ->castAs<FunctionProtoType>()
5729  ->getExceptionSpecType()))
5730  DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5731  });
5732 }
5733 
5734 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5735  if (Chain && Chain->isProcessingUpdateRecords()) return;
5736  assert(!WritingAST && "Already writing the AST!");
5737  if (!Chain) return;
5738  Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5739  DeclUpdates[D].push_back(
5740  DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5741  });
5742 }
5743 
5744 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5745  const FunctionDecl *Delete) {
5746  if (Chain && Chain->isProcessingUpdateRecords()) return;
5747  assert(!WritingAST && "Already writing the AST!");
5748  assert(Delete && "Not given an operator delete");
5749  if (!Chain) return;
5750  Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
5751  DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5752  });
5753 }
5754 
5755 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5756  if (Chain && Chain->isProcessingUpdateRecords()) return;
5757  assert(!WritingAST && "Already writing the AST!");
5758  if (!D->isFromASTFile())
5759  return; // Declaration not imported from PCH.
5760 
5761  // Implicit function decl from a PCH was defined.
5762  DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5763 }
5764 
5765 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5766  if (Chain && Chain->isProcessingUpdateRecords()) return;
5767  assert(!WritingAST && "Already writing the AST!");
5768  if (!D->isFromASTFile())
5769  return;
5770 
5771  DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5772 }
5773 
5774 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
5775  if (Chain && Chain->isProcessingUpdateRecords()) return;
5776  assert(!WritingAST && "Already writing the AST!");
5777  if (!D->isFromASTFile())
5778  return;
5779 
5780  // Since the actual instantiation is delayed, this really means that we need
5781  // to update the instantiation location.
5782  DeclUpdates[D].push_back(
5785 }
5786 
5787 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
5788  if (Chain && Chain->isProcessingUpdateRecords()) return;
5789  assert(!WritingAST && "Already writing the AST!");
5790  if (!D->isFromASTFile())
5791  return;
5792 
5793  DeclUpdates[D].push_back(
5794  DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5795 }
5796 
5797 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5798  const ObjCInterfaceDecl *IFD) {
5799  if (Chain && Chain->isProcessingUpdateRecords()) return;
5800  assert(!WritingAST && "Already writing the AST!");
5801  if (!IFD->isFromASTFile())
5802  return; // Declaration not imported from PCH.
5803 
5804  assert(IFD->getDefinition() && "Category on a class without a definition?");
5805  ObjCClassesWithCategories.insert(
5806  const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5807 }
5808 
5809 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5810  if (Chain && Chain->isProcessingUpdateRecords()) return;
5811  assert(!WritingAST && "Already writing the AST!");
5812 
5813  // If there is *any* declaration of the entity that's not from an AST file,
5814  // we can skip writing the update record. We make sure that isUsed() triggers
5815  // completion of the redeclaration chain of the entity.
5816  for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
5817  if (IsLocalDecl(Prev))
5818  return;
5819 
5820  DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
5821 }
5822 
5823 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5824  if (Chain && Chain->isProcessingUpdateRecords()) return;
5825  assert(!WritingAST && "Already writing the AST!");
5826  if (!D->isFromASTFile())
5827  return;
5828 
5829  DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5830 }
5831 
5832 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
5833  const Attr *Attr) {
5834  if (Chain && Chain->isProcessingUpdateRecords()) return;
5835  assert(!WritingAST && "Already writing the AST!");
5836  if (!D->isFromASTFile())
5837  return;
5838 
5839  DeclUpdates[D].push_back(
5840  DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
5841 }
5842 
5843 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
5844  if (Chain && Chain->isProcessingUpdateRecords()) return;
5845  assert(!WritingAST && "Already writing the AST!");
5846  assert(D->isHidden() && "expected a hidden declaration");
5847  DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
5848 }
5849 
5850 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5851  const RecordDecl *Record) {
5852  if (Chain && Chain->isProcessingUpdateRecords()) return;
5853  assert(!WritingAST && "Already writing the AST!");
5854  if (!Record->isFromASTFile())
5855  return;
5856  DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5857 }
bool hasLineDirectives() const
Return true if this FileID has #line directives in it.
A PredefinedExpr record.
Definition: ASTBitCodes.h:1231
unsigned getNumElements() const
Definition: Type.h:2781
TypeSourceInfo * getUnderlyingTInfo() const
Definition: TypeLoc.h:1646
SourceManager & getSourceManager() const
Definition: Preprocessor.h:694
bool isPoisoned() const
Return true if this token has been poisoned.
SourceLocation getOptimizeOffPragmaLocation() const
Get the location for the currently active "\#pragma clang optimize off". If this location is invalid...
Definition: Sema.h:7864
A FriendTemplateDecl record.
Definition: ASTBitCodes.h:1117
Defines the clang::ASTContext interface.
A CompoundLiteralExpr record.
Definition: ASTBitCodes.h:1271
A NonTypeTemplateParmDecl record.
Definition: ASTBitCodes.h:1135
QualType getExceptionType(unsigned i) const
Definition: Type.h:3332
Represents a type that was referred to using an elaborated type keyword, e.g., struct S...
Definition: Type.h:4430
SourceLocation getEnd() const
QualType getUnderlyingType() const
Definition: Type.h:3599
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used...
Definition: Sema.h:526
Record code for the preprocessor options table.
Definition: ASTBitCodes.h:322
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:5278
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.h:4948
unsigned getAnonymousDeclarationNumber(const NamedDecl *D)
Definition: ASTWriter.cpp:5101
uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name)
Definition: ASTWriter.cpp:4848
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1561
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:488
bool isVariadic() const
Definition: Type.h:3366
std::string Name
The name of this module.
Definition: Basic/Module.h:50
void VisitArrayType(const ArrayType *T)
Definition: ASTWriter.cpp:179
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
ExtVectorDeclsType ExtVectorDecls
ExtVectorDecls - This is a list all the extended vector types.
Definition: Sema.h:476
IdentifierInfo * getIdentifier() const
Definition: ASTBitCodes.h:1588
iterator begin() const
Definition: DeclBase.h:1103
Source range/offset of a preprocessed entity.
Definition: ASTBitCodes.h:166
Header getUmbrellaHeader() const
Retrieve the header that serves as the umbrella header for this module.
Definition: Basic/Module.h:401
SourceLocation getElaboratedKeywordLoc() const
Definition: TypeLoc.h:1840
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:3431
unsigned getDepth() const
Definition: Type.h:3945
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:292
no exception specification
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:572
Smart pointer class that efficiently represents Objective-C method names.
Record code for map of Objective-C class definition IDs to the ObjC categories in a module that are a...
Definition: ASTBitCodes.h:530
This is a discriminated union of FileInfo and ExpansionInfo.
An IndirectGotoStmt record.
Definition: ASTBitCodes.h:1215
llvm::iterator_range< pack_iterator > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:329
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2179
bool hasFETokenInfoChangedSinceDeserialization() const
Determine whether the frontend token information for this identifier has changed since it was loaded ...
Represents the dependent type named by a dependently-scoped typename using declaration, e.g.
Definition: Type.h:3473
A (possibly-)qualified type.
Definition: Type.h:598
static void EmitBlockID(unsigned ID, const char *Name, llvm::BitstreamWriter &Stream, ASTWriter::RecordDataImpl &Record)
Definition: ASTWriter.cpp:751
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:208
A PointerType record.
Definition: ASTBitCodes.h:824
#define BLOCK(X)
An AddrLabelExpr record.
Definition: ASTBitCodes.h:1287
bool isBaseOfClass() const
Determine whether this base class is a base of a class declared with the 'class' keyword (vs...
Definition: DeclCXX.h:212
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:626
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:1559
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:282
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:117
SourceLocation getNameLoc() const
Definition: TypeLoc.h:1804
void AddToken(const Token &Tok, RecordDataImpl &Record)
Emit a token.
Definition: ASTWriter.cpp:3987
unsigned local_sloc_entry_size() const
Get the number of local SLocEntries we have.
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:554
ArrayRef< const IdentifierInfo * > args() const
Definition: MacroInfo.h:180
FunctionDecl * getExceptionSpecDecl() const
If this function type has an exception specification which hasn't been determined yet (either because...
Definition: Type.h:3346
OpenCL supported extensions and optional core features.
Definition: OpenCLOptions.h:24
A CXXStaticCastExpr record.
Definition: ASTBitCodes.h:1377
Defines the clang::FileManager interface and associated types.
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:526
An AttributedStmt record.
Definition: ASTBitCodes.h:1201
DeclarationName getCXXConstructorName(CanQualType Ty)
getCXXConstructorName - Returns the name of a C++ constructor for the given Type. ...
A CXXReinterpretCastExpr record.
Definition: ASTBitCodes.h:1381
QualType getBaseType() const
Definition: Type.h:3653
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:4858
An OMPThreadPrivateDecl record.
Definition: ASTBitCodes.h:1160
An ObjCBoolLiteralExpr record.
Definition: ASTBitCodes.h:1353
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition: Sema.cpp:474
submodule_iterator submodule_begin()
Definition: Basic/Module.h:474
ArrayRef< RawComment * > getComments() const
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
Definition: ASTReader.cpp:897
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:810
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:1453
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2879
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "...
Definition: Basic/Module.h:178
IdentifierInfo * getCXXLiteralIdentifier() const
getCXXLiteralIdentifier - If this name is the name of a literal operator, retrieve the identifier ass...
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:484
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Basic/Module.h:368
void AddUnresolvedSet(const ASTUnresolvedSet &Set)
Emit a UnresolvedSet structure.
Definition: ASTWriter.cpp:5389
void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS)
Emit a nested name specifier with source-location information.
Definition: ASTWriter.cpp:5212
C Language Family Type Representation.
Defines the SourceManager interface.
uint32_t IdentID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:123
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in...
static bool isImportedDeclContext(ASTReader *Chain, const Decl *D)
Definition: ASTWriter.cpp:5657
const LangOptions & getLangOpts() const
Definition: ASTWriter.cpp:4104
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:4496
An OMPDeclareReductionDecl record.
Definition: ASTBitCodes.h:1172
The template argument is an expression, and we've not resolved it to one of the other forms yet...
Definition: TemplateBase.h:69
CXXRecordDecl * getDecl() const
Definition: Type.cpp:3065
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:617
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
An ImplicitValueInitExpr record.
Definition: ASTBitCodes.h:1281
unsigned getNextLocalOffset() const
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
Definition: ASTBitCodes.h:145
An ImplicitCastExpr record.
Definition: ASTBitCodes.h:1267
Defines the FileSystemStatCache interface.
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
A VarTemplatePartialSpecializationDecl record.
Definition: ASTBitCodes.h:1129
bool isObjectLike() const
Definition: MacroInfo.h:197
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed...
Definition: Sema.h:7041
unsigned IsFramework
Whether this is a framework module.
Definition: Basic/Module.h:166
bool hasCommaPasting() const
Definition: MacroInfo.h:214
Kind getKind() const
Definition: MacroInfo.h:334
Defines the C++ template declaration subclasses.
StringRef P
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:604
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:4084
static NamedDecl * getDeclForLocalLookup(const LangOptions &LangOpts, NamedDecl *D)
Determine the declaration that should be put into the name lookup table to represent the given declar...
Definition: ASTWriter.cpp:3102
An LValueReferenceType record.
Definition: ASTBitCodes.h:828
static unsigned getNumberOfModules(Module *Mod)
Compute the number of modules within the given tree (including the given module). ...
Definition: ASTWriter.cpp:2439
Defines the clang::MacroInfo and clang::MacroDirective classes.
A CXXOperatorCallExpr record.
Definition: ASTBitCodes.h:1367
Optional< unsigned > getMinor() const
Retrieve the minor version number, if provided.
Definition: VersionTuple.h:77
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:664
A record that stores the set of declarations that are lexically stored within a given DeclContext...
Definition: ASTBitCodes.h:1070
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type...
Definition: Type.h:3416
QualType getPointeeType() const
Definition: Type.h:2420
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn't a simple identifier.
Specifies an umbrella directory.
Definition: ASTBitCodes.h:661
A CXXTemporaryObjectExpr record.
Definition: ASTBitCodes.h:1375
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier.
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:7081
uint32_t DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:63
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1260
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded...
const ExpansionInfo & getExpansion() const
unsigned getLength() const
Efficiently return the length of this identifier info.
A SubstTemplateTypeParmType record.
Definition: ASTBitCodes.h:866
QualType getRecordType(const RecordDecl *Decl) const
std::unique_ptr< llvm::MemoryBuffer > Buffer
Class that performs name lookup into a DeclContext stored in an AST file.
DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgument > Args, QualType Canon)
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2456
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
Definition: TemplateName.h:133
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:51
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:471
A ObjCPropertyDecl record.
Definition: ASTBitCodes.h:1043
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
StoredDeclsMap * getLookupPtr() const
Retrieve the internal representation of the lookup structure.
Definition: DeclBase.h:1749
Wrapper for source info for typedefs.
Definition: TypeLoc.h:620
bool hasBaseTypeAsWritten() const
Definition: TypeLoc.h:933
serialization::DeclID GetDeclRef(const Decl *D)
Force a declaration to be emitted and get its ID.
Definition: ASTWriter.cpp:4981
A container of type source information.
Definition: Decl.h:62
unsigned getIndex() const
Definition: Type.h:3946
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:509
Record code for the module build directory.
Definition: ASTBitCodes.h:295
Floating point control options.
Definition: LangOptions.h:161
void * getAsOpaquePtr() const
void AddTypeRef(QualType T, RecordDataImpl &Record)
Emit a reference to a type.
Definition: ASTWriter.cpp:4937
An ElaboratedType record.
Definition: ASTBitCodes.h:864
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:305
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
An UnresolvedUsingType record.
Definition: ASTBitCodes.h:868
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
unsigned fp_contract
Definition: LangOptions.h:163
static void AddStmtsExprs(llvm::BitstreamWriter &Stream, ASTWriter::RecordDataImpl &Record)
Definition: ASTWriter.cpp:777
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:216
unsigned getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it...
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1095
bool hasAttrEnumOperand() const
Definition: TypeLoc.h:738
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:26
SourceRange getAttrOperandParensRange() const
The location of the parentheses around the operand, if there is an operand.
Definition: TypeLoc.h:797
bool isSpelledAsLValue() const
Definition: Type.h:2336
An IncompleteArrayType record.
Definition: ASTBitCodes.h:836
The internal '__type_pack_element' template.
Definition: ASTBitCodes.h:988
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:201
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:683
uint64_t Emit(unsigned Code, unsigned Abbrev=0)
Emit the record to the stream, followed by its substatements, and return its offset.
Definition: ASTWriter.h:754
const llvm::APInt & getSize() const
Definition: Type.h:2527
A ClassTemplateDecl record.
Definition: ASTBitCodes.h:1119
SourceLocation getIncludeLoc() const
A PragmaDetectMismatchDecl record.
Definition: ASTBitCodes.h:1170
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
An UnresolvedUsingTypenameDecl record.
Definition: ASTBitCodes.h:1096
unsigned getCounterValue() const
An identifier, stored as an IdentifierInfo*.
The internal '__builtin_va_list' typedef.
Definition: ASTBitCodes.h:967
static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W, ArrayRef< CXXBaseSpecifier > Bases)
Definition: ASTWriter.cpp:5410
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:32
serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name)
Get the unique number used to refer to the given macro.
Definition: ASTWriter.cpp:4824
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:768
bool decls_empty() const
Definition: DeclBase.cpp:1212
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1163
An OMPCapturedExprDecl record.
Definition: ASTBitCodes.h:1166
Options for controlling the target.
Definition: TargetOptions.h:25
Wrapper of type source information for a type with non-trivial direct qualifiers. ...
Definition: TypeLoc.h:247
bool hasAttrExprOperand() const
Definition: TypeLoc.h:733
A UsingShadowDecl record.
Definition: ASTBitCodes.h:1088
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Definition: MacroInfo.h:120
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:46
AutoTypeKeyword getKeyword() const
Definition: Type.h:4102
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
const unsigned int NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition: ASTBitCodes.h:995
static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a file.
Definition: ASTWriter.cpp:1641
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:1537
The value of the next COUNTER to dispense.
Definition: ASTBitCodes.h:433
const DeclContext * getDefinitiveDeclContext(const DeclContext *DC)
Retrieve the "definitive" declaration that provides all of the visible entries for the given declarat...
Definition: ASTCommon.cpp:179
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:3949
A TemplateTemplateParmDecl record that stores an expanded template template parameter pack...
Definition: ASTBitCodes.h:1153
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:655
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:572
A namespace, stored as a NamespaceDecl*.
QualType getOriginalType() const
Definition: Type.h:2243
iterator local_end()
End iterator for local, non-loaded, preprocessed entities.
unsigned isCompilingModuleHeader
Whether this header is part of the module that we are building.
Definition: HeaderSearch.h:60
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:590
Record code for header search information.
Definition: ASTBitCodes.h:503
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:49
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:593
Used to hold and unique data used to represent #line information.
llvm::MapVector< Selector, SourceLocation > ReferencedSelectors
Method selectors used in a @selector expression.
Definition: Sema.h:1004
A CXXConstructExpr record.
Definition: ASTBitCodes.h:1371
Record code for the target options table.
Definition: ASTBitCodes.h:310
serialization::IdentID getIdentifierRef(const IdentifierInfo *II)
Get the unique number used to refer to the given identifier.
Definition: ASTWriter.cpp:4814
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:69
bool hasAttrOperand() const
Definition: TypeLoc.h:743
A TemplateTemplateParmDecl record.
Definition: ASTBitCodes.h:1137
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:404
TemplateTemplateParmDecl * getParameter() const
Definition: TemplateName.h:327
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1377
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:3983
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1063
Defines the clang::Expr interface and subclasses for C++ expressions.
FPOptions & getFPOptions()
Definition: Sema.h:1064
A ObjCInterfaceDecl record.
Definition: ASTBitCodes.h:1027
QualType getRawCFConstantStringType() const
Get the structure type used to representation CFStrings, or NULL if it hasn't yet been built...
Definition: ASTContext.h:1387
QualType getUnderlyingType() const
Definition: Type.h:3652
SourceLocation getAmpAmpLoc() const
Definition: TypeLoc.h:1238
void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record)
Emit a reference to an identifier.
Definition: ASTWriter.cpp:4810
The collection of all-type qualifiers we support.
Definition: Type.h:117
A ShuffleVectorExpr record.
Definition: ASTBitCodes.h:1295
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:313
PipeType - OpenCL20.
Definition: Type.h:5190
iterator begin(DeclarationName Name)
begin - Returns an iterator for decls with the name 'Name'.
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:474
void AddTypeSourceInfo(TypeSourceInfo *TInfo)
Emits a reference to a declarator info.
Definition: ASTWriter.cpp:4920
known_categories_iterator known_categories_begin() const
Retrieve an iterator to the beginning of the known-categories list.
Definition: DeclObjC.h:1600
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
A CXXConstructorDecl record for an inherited constructor.
Definition: ASTBitCodes.h:1106
unsigned getNumParams() const
Definition: Type.h:3271
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3253
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:39
SourceRange getLocalSourceRange() const
Retrieve the source range covering just the last part of this nested-name-specifier, not including the prefix.
const IdentifierInfo * getIdentifier() const
Retrieve the type named by the typename specifier as an identifier.
Definition: Type.h:4523
DeclarationName getName() const
getName - Returns the embedded declaration name.
const StringRef FilePath
One of these records is kept for each identifier that is lexed.
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:2497
A macro directive exported by a module.
Definition: ASTBitCodes.h:630
An ObjCAtThrowStmt record.
Definition: ASTBitCodes.h:1349
time_t getTimestampForOutput(const FileEntry *E) const
Get a timestamp for output into the AST file.
Definition: ASTWriter.cpp:4109
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:659
The block containing comments.
Definition: ASTBitCodes.h:234
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template.
void AddTypeRef(QualType T)
Emit a reference to a type.
Definition: ASTWriter.h:829
A DesignatedInitExpr record.
Definition: ASTBitCodes.h:1277
StringRef getModuleCachePath() const
Retrieve the path to the module cache.
Definition: HeaderSearch.h:322
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4549
bool isNull() const
Definition: TypeLoc.h:95
Represents a class type in Objective C.
Definition: Type.h:4727
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
Iteration over the preprocessed entities.
Expr * getSizeExpr() const
Definition: Type.h:2623
IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:92
A C++ nested-name-specifier augmented with source location information.
Record the location of a macro definition.
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:412
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1067
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:471
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:57
Specifies a header that has been explicitly excluded from this submodule.
Definition: ASTBitCodes.h:672
static SourceLocation getFromRawEncoding(unsigned Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition: Basic/Module.h:148
TypeSourceInfo * getTypeArgTInfo(unsigned i) const
Definition: TypeLoc.h:886
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1267
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis for a capture that is a pack expansion.
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
Definition: Decl.h:2871
SourceLocation getTypeArgsRAngleLoc() const
Definition: TypeLoc.h:875
The unsigned 128-bit integer type.
Definition: ASTBitCodes.h:961
Record code for the module map file that was used to build this AST file.
Definition: ASTBitCodes.h:289
NameKind getKind() const
An ExtVectorType record.
Definition: ASTBitCodes.h:842
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:577
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:2964
llvm::MapVector< const FunctionDecl *, LateParsedTemplate * > LateParsedTemplateMapT
Definition: Sema.h:553
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1306
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1679
unsigned size() const
bool isTranslationUnit() const
Definition: DeclBase.h:1283
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:231
NestedNameSpecifier * getQualifier() const
Retrieve the qualification on this type.
Definition: Type.h:4516
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:28
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:690
CachedTokens Toks
Definition: Sema.h:9644
Represents the result of substituting a set of types for a template type parameter pack...
Definition: Type.h:4038
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a macro expansion.
Definition: ASTWriter.cpp:1690
unsigned getNumProtocols() const
Definition: TypeLoc.h:910
Wrapper for source info for unresolved typename using decls.
Definition: TypeLoc.h:642
bool makeAbsolutePath(SmallVectorImpl< char > &Path) const
Makes Path absolute taking into account FileSystemOptions and the working directory option...
SourceLocation getBuiltinLoc() const
Definition: TypeLoc.h:522
unsigned size() const
Definition: DeclTemplate.h:92
An AttributedType record.
Definition: ASTBitCodes.h:888
unsigned getAsOpaqueValue() const
Definition: Type.h:232
An object-like macro definition.
Definition: ASTBitCodes.h:614
~ASTWriter() override
Definition: ASTWriter.cpp:4100
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
unsigned getRegParm() const
Definition: Type.h:2948
void AddTemplateParameterList(const TemplateParameterList *TemplateParams)
Emit a template parameter list.
Definition: ASTWriter.cpp:5358
qual_range quals() const
Definition: Type.h:4836
Describes one token.
Definition: ASTBitCodes.h:623
An AdjustedType record.
Definition: ASTBitCodes.h:900
Describes a module or submodule.
Definition: Basic/Module.h:47
QualType getUnderlyingType() const
Definition: Type.h:3578
Expr * getUnderlyingExpr() const
Definition: Type.h:3598
A IndirectFieldDecl record.
Definition: ASTBitCodes.h:1147
FileManager & getFileManager() const
Definition: Preprocessor.h:693
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:448
iterator end()
end - Returns an iterator that has 'finished'.
void VisitTagType(const TagType *T)
Definition: ASTWriter.cpp:321
serialization::MacroID getMacroID(MacroInfo *MI)
Determine the ID of an already-emitted macro.
Definition: ASTWriter.cpp:4840
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:667
TemplateParameterList ** TemplParamLists
TemplParamLists - A new-allocated array of size NumTemplParamLists, containing pointers to the "outer...
Definition: Decl.h:627
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
TemplateArgument getArgumentPack() const
Definition: Type.cpp:3083
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2383
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:160
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:132
SmallVector< uint64_t, 64 > RecordData
Definition: ASTWriter.h:87
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e...
Definition: Basic/Module.h:195
A qualified template name, where the qualification is kept to describe the source code as written...
Definition: TemplateName.h:195
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:588
const LangOptions & getLangOpts() const
Definition: ASTContext.h:604
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:631
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
< Capturing the *this object by copy
Definition: Lambda.h:37
An AccessSpecDecl record.
Definition: ASTBitCodes.h:1112
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:1462
uint32_t Offset
Definition: CacheTokens.cpp:44
Describes a blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:598
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:4782
Record code for the language options table.
Definition: ASTBitCodes.h:307
QualType getReturnType() const
Definition: Type.h:3009
Wrapper for source info for functions.
Definition: TypeLoc.h:1255
Specifies a conflict with another module.
Definition: ASTBitCodes.h:678
The signed 128-bit integer type.
Definition: ASTBitCodes.h:958
StoredDeclsMap * buildLookup()
Ensure the lookup structure is fully-built and return it.
Definition: DeclBase.cpp:1345
bool isUsedForHeaderGuard() const
Determine whether this macro was used for a header guard.
Definition: MacroInfo.h:272
SourceLocation getEllipsisLoc() const
For a pack expansion, determine the location of the ellipsis.
Definition: DeclCXX.h:226
A UnaryTransformType record.
Definition: ASTBitCodes.h:894
UnresolvedUsingTypenameDecl * getDecl() const
Definition: Type.h:3483
A reference to a previously [de]serialized Stmt record.
Definition: ASTBitCodes.h:1189
NestedNameSpecifierLoc getQualifierLoc() const
Definition: TypeLoc.h:1792
A UsingDirecitveDecl record.
Definition: ASTBitCodes.h:1092
An ObjCObjectType record.
Definition: ASTBitCodes.h:872
A ConstantArrayType record.
Definition: ASTBitCodes.h:834
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:704
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:135
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:3525
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:569
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition: Sema.h:1000
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:695
void AddSourceRange(SourceRange Range, RecordDataImpl &Record)
Emit a source range.
Definition: ASTWriter.cpp:4790
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:686
Expr * getNoexceptExpr() const
Definition: Type.h:3336
TypeSourceInfo * getClassTInfo() const
Definition: TypeLoc.h:1177
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:478
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:697
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:585
The internal '__make_integer_seq' template.
Definition: ASTBitCodes.h:979
ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Definition: ASTWriter.cpp:96
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
void AddCXXCtorInitializers(ArrayRef< CXXCtorInitializer * > CtorInits)
Emit a CXXCtorInitializer array.
Definition: ASTWriter.cpp:5468
bool needsExtraLocalData() const
Definition: TypeLoc.h:538
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:497
Module * Parent
The parent of this module.
Definition: Basic/Module.h:57
An ExtQualType record.
Definition: ASTBitCodes.h:820
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:506
void AddTypeLoc(TypeLoc TL)
Emits a type with source-location information.
Definition: ASTWriter.cpp:4929
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:720
TemplateDecl * getTemplateDecl() const
The template declaration to which this qualified name refers.
Definition: TemplateName.h:390
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1601
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:981
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:516
void AddAttributes(ArrayRef< const Attr * > Attrs)
Emit a list of attributes.
Definition: ASTWriter.cpp:3975
CXXRecordDecl * getCanonicalDecl() override
Definition: DeclCXX.h:654
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location...
TypeID MakeTypeID(ASTContext &Context, QualType T, IdxForTypeTy IdxForType)
Definition: ASTCommon.h:48
Record code for an array of all of the (sub)modules that were imported by the AST file...
Definition: ASTBitCodes.h:537
submodule_iterator submodule_end()
Definition: Basic/Module.h:476
serialization::DeclID BaseDeclID
Base declaration ID for declarations local to this module.
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:1525
NestedNameSpecifier * getQualifier() const
Retrieve the qualification on this type.
Definition: Type.h:4457
TypeClass getTypeClass() const
Definition: Type.h:1533
VarDecl * getCapturedVar() const
Retrieve the declaration of the local variable being captured.
A marker record that indicates that we are at the end of an expression.
Definition: ASTBitCodes.h:1185
A ClassTemplateSpecializationDecl record.
Definition: ASTBitCodes.h:1121
tok::TokenKind getKind() const
Definition: Token.h:89
A BlockPointerType record.
Definition: ASTBitCodes.h:826
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:468
Preprocessor & PP
Definition: Sema.h:298
A MemberPointerType record.
Definition: ASTBitCodes.h:832
Represents an ObjC class declaration.
Definition: DeclObjC.h:1091
ObjCMethodDecl * getMethod() const
SourceLocation getTypeofLoc() const
Definition: TypeLoc.h:1587
detail::InMemoryDirectory::const_iterator I
SourceLocation getTypeArgsLAngleLoc() const
Definition: TypeLoc.h:868
unsigned getNumParams() const
Definition: TypeLoc.h:1301
serialization::TypeID getTypeID(QualType T) const
Determine the type ID of an already-emitted type.
Definition: ASTWriter.cpp:4964
The preprocessor keeps track of this information for each file that is #included. ...
Definition: HeaderSearch.h:39
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
QualType getCanonicalTypeInternal() const
Definition: Type.h:2001
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:437
bool isInvalid() const
serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc)
Infer the submodule ID that contains an entity at the given source location.
Definition: ASTWriter.cpp:2667
bool hasModeAttr() const
Definition: TypeLoc.h:595
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:2718
const TemplateTypeParmType * getReplacedParameter() const
Gets the template parameter that was substituted for.
Definition: Type.h:4059
A SubstTemplateTypeParmPackType record.
Definition: ASTBitCodes.h:890
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:818
DiagnosticsEngine & getDiagnostics() const
Iterator that walks over the list of categories, filtering out those that do not meet specific criter...
Definition: DeclObjC.h:1503
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
unsigned getObjCOrBuiltinID() const
bool MSStructPragmaOn
Definition: Sema.h:321
Encapsulates the information needed to find the file referenced by a #include or #include_next, (sub-)framework lookup, etc.
Definition: HeaderSearch.h:137
IdentifierInfo * getAlias() const
Definition: Weak.h:34
SourceLocation getKWLoc() const
Definition: TypeLoc.h:2047
Represents a K&R-style 'int foo()' function, which has no information available about its arguments...
Definition: Type.h:3039
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers)...
Definition: Basic/Module.h:173
The block containing information about the source manager.
Definition: ASTBitCodes.h:217
bool isCPlusPlusOperatorKeyword() const
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments.
Definition: TemplateBase.h:591
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:145
A VariableArrayType record.
Definition: ASTBitCodes.h:838
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:5173
Optional< unsigned > getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce...
QualType getInjectedSpecializationType() const
Definition: Type.h:4326
ExtInfo getExtInfo() const
Definition: Type.h:3018
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:263
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
Definition: ASTBitCodes.h:206
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
unsigned NumTemplParamLists
NumTemplParamLists - The number of "outer" template parameter lists.
Definition: Decl.h:620
QualType getParamType(unsigned i) const
Definition: Type.h:3272
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3073
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3304
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:518
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:652
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Retrieves list of suspicious delete-expressions that will be checked at the end of translation unit...
Definition: Sema.cpp:1519
void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, DeclarationName Name)
Definition: ASTWriter.cpp:5122
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
void AddCXXTemporary(const CXXTemporary *Temp)
Emit a CXXTemporary.
Definition: ASTWriter.cpp:4875
SourceLocation getAttrEnumOperandLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:784
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition: Basic/Module.h:221
StringRef Filename
Definition: Format.cpp:1194
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:198
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:462
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1363
ASTContext * Context
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:2285
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
A StaticAssertDecl record.
Definition: ASTBitCodes.h:1141
Captures information about a #pragma weak directive.
Definition: Weak.h:25
void AddPath(StringRef Path, RecordDataImpl &Record)
Add a path to the given record.
Definition: ASTWriter.cpp:4023
A VarTemplateSpecializationDecl record.
Definition: ASTBitCodes.h:1127
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:554
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
static const char * adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir)
Adjusts the given filename to only write out the portion of the filename that is not part of the syst...
Definition: ASTWriter.cpp:1178
An ObjCTypeParamDecl record.
Definition: ASTBitCodes.h:1164
Exposes information about the current target.
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1143
unsigned IgnoreSysRoot
IgnoreSysRoot - This is false if an absolute path should be treated relative to the sysroot...
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:2659
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
SourceLocation getElaboratedKeywordLoc() const
Definition: TypeLoc.h:1727
bool isImplicit() const
Determine whether this was an implicit capture (not written between the square brackets introducing t...
An ObjCObjectPointerType record.
Definition: ASTBitCodes.h:860
An TemplateSpecializationType record.
Definition: ASTBitCodes.h:876
Type source information for an attributed type.
Definition: TypeLoc.h:724
An ObjCInterfaceType record.
Definition: ASTBitCodes.h:858
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1370
QualType getPointeeType() const
Definition: Type.h:2300
Describes a zlib-compressed blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:601
Expr - This represents one expression.
Definition: Expr.h:105
HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized. ...
Definition: HeaderSearch.h:258
A ObjCCategoryImplDecl record.
Definition: ASTBitCodes.h:1037
StringRef getName() const
Return the actual identifier string.
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:458
static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
Definition: ASTReader.cpp:755
bool isLookupContext() const
Test whether the context supports looking up names.
Definition: DeclBase.h:1275
The directory that the PCH was originally created in.
Definition: ASTBitCodes.h:274
unsigned getNumArgs() const
A ObjCPropertyImplDecl record.
Definition: ASTBitCodes.h:1045
TypeSpecifierWidth getWrittenWidthSpec() const
Definition: TypeLoc.h:572
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
void AddCXXDefinitionData(const CXXRecordDecl *D)
Definition: ASTWriter.cpp:5473
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:588
Implements an efficient mapping from strings to IdentifierInfo nodes.
bool hasLineTable() const
Determine if the source manager has a line table.
Defines implementation details of the clang::SourceManager class.
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:54
FileManager & getFileManager() const
unsigned getNumArgs() const
Definition: MacroInfo.h:179
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition: Basic/Module.h:202
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:455
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2414
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:716
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:886
A CXXConstructorDecl record.
Definition: ASTBitCodes.h:1104
Defines version macros and version-related utility functions for Clang.
Expr * getUnderlyingExpr() const
Definition: Type.h:3532
Defines the clang::Preprocessor interface.
ArgKind
The kind of template argument we're storing.
Definition: TemplateBase.h:43
const SrcMgr::SLocEntry & getLocalSLocEntry(unsigned Index, bool *Invalid=nullptr) const
Get a local SLocEntry. This is exposed for indexing.
The block containing the detailed preprocessing record.
Definition: ASTBitCodes.h:228
AccessSpecifier getAccessSpecifierAsWritten() const
Retrieves the access specifier as written in the source code (which may mean that no access specifier...
Definition: DeclCXX.h:247
QualType getNamedType() const
Retrieve the type named by the qualified-id.
Definition: Type.h:4460
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:216
bool getNoReturn() const
Definition: Type.h:2945
llvm::MapVector< IdentifierInfo *, WeakInfo > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition: Sema.h:689
serialization::TypeID GetOrCreateTypeID(QualType T)
Force a type to be emitted and get its ID.
Definition: ASTWriter.cpp:4941
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:2003
SourceLocation getLocation() const
Retrieve the source location of the capture.
A structure for storing the information associated with a substituted template template parameter...
Definition: TemplateName.h:314
lookup_result noload_lookup(DeclarationName Name)
Find the declarations with the given name that are visible within this context; don't attempt to retr...
Definition: DeclBase.cpp:1469
unsigned LocalNumMacros
The number of macros in this AST file.
A CXXStdInitializerListExpr record.
Definition: ASTBitCodes.h:1389
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1145
ArrayRef< const FileEntry * > getTopHeaders(FileManager &FileMgr)
The top-level headers associated with this module.
A VarTemplateDecl record.
Definition: ASTBitCodes.h:1125
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
Record code for the original file that was used to generate the AST file, including both its file ID ...
Definition: ASTBitCodes.h:271
An ArraySubscriptExpr record.
Definition: ASTBitCodes.h:1255
Represents a C++ template name within the type system.
Definition: TemplateName.h:176
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used...
Definition: Basic/Module.h:275
Represents the type decltype(expr) (C++11).
Definition: Type.h:3590
Information about a module that has been loaded by the ASTReader.
A namespace alias, stored as a NamespaceAliasDecl*.
void AddString(StringRef Str, RecordDataImpl &Record)
Add a string to the given record.
Definition: ASTWriter.cpp:4000
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:123
A CXXDestructorDecl record.
Definition: ASTBitCodes.h:1108
unsigned getLocalOrImportedSubmoduleID(Module *Mod)
Retrieve or create a submodule ID for this module, or return 0 if the submodule is neither local (a s...
Definition: ASTWriter.cpp:2413
bool isSubModuleOf(const Module *Other) const
Determine whether this module is a submodule of the given other module.
Kind getAttrKind() const
Definition: Type.h:3827
A FunctionProtoType record.
Definition: ASTBitCodes.h:846
A NonTypeTemplateParmDecl record that stores an expanded non-type template parameter pack...
Definition: ASTBitCodes.h:1150
SourceLocation getTemplateNameLoc() const
Definition: TypeLoc.h:1483
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:107
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:1501
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:590
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition: Sema.h:5371
Wrapper for source info for enum types.
Definition: TypeLoc.h:680
A unary type transform, which is a type constructed from another.
Definition: Type.h:3631
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1774
A block containing a module file extension.
Definition: ASTBitCodes.h:255
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition: MacroInfo.h:231
bool hasTrailingReturn() const
Definition: Type.h:3376
std::string FileName
The file name of the module file.
A NamespaceAliasDecl record.
Definition: ASTBitCodes.h:1084
QualType getCXXNameType() const
getCXXNameType - If this name is one of the C++ names (of a constructor, destructor, or conversion function), return the type associated with that name.
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:485
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion, return the pattern as a template name.
Definition: TemplateBase.h:269
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:580
void AddDeclRef(const Decl *D)
Emit a reference to a declaration.
Definition: ASTWriter.h:851
const unsigned VERSION_MINOR
AST file minor version number supported by this version of Clang.
Definition: ASTBitCodes.h:49
SourceLocation getModuleImportLoc(Module *M) const
void AddQualifierInfo(const QualifierInfo &Info)
Definition: ASTWriter.cpp:5159
A DesignatedInitUpdateExpr record.
Definition: ASTBitCodes.h:1279
void AddStmt(Stmt *S)
Add the given statement or expression to the queue of statements to emit.
Definition: ASTWriter.h:784
unsigned header_file_size() const
Definition: HeaderSearch.h:595
void AddSelectorRef(Selector S)
Emit a Selector (which is a smart pointer reference).
Definition: ASTWriter.cpp:4852
Represents a GCC generic vector type.
Definition: Type.h:2756
struct CXXOpName CXXOperatorName
a DecltypeType record.
Definition: ASTBitCodes.h:862
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2366
CXXRecordDecl * getStdBadAlloc() const
An ImplicitParamDecl record.
Definition: ASTBitCodes.h:1053
DirectoryName getUmbrellaDir() const
Retrieve the directory for which this module serves as the umbrella.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
QualType getElementType() const
Definition: Type.h:2780
unsigned SLocEntryBaseOffset
The base offset in the source manager's view of this module.
An EnumConstantDecl record.
Definition: ASTBitCodes.h:1021
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:375
Record code for undefined but used functions and variables that need a definition in this TU...
Definition: ASTBitCodes.h:563
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:165
A DependentNameType record.
Definition: ASTBitCodes.h:878
do v
Definition: arm_acle.h:78
Abstract base class that writes a module file extension block into a module file. ...
const SourceManager & SM
Definition: Format.cpp:1184
An ImportDecl recording a module import.
Definition: ASTBitCodes.h:1158
A ObjCCategoryDecl record.
Definition: ASTBitCodes.h:1035
QualType getReplacementType() const
Gets the type that was substituted for the template parameter.
Definition: Type.h:4004
bool isC99Varargs() const
Definition: MacroInfo.h:202
LambdaCaptureKind getCaptureKind() const
Determine the kind of capture.
Definition: ExprCXX.cpp:842
An ObjCForCollectionStmt record.
Definition: ASTBitCodes.h:1339
void Visit(QualType T)
Definition: ASTWriter.cpp:103
Record code for the identifier table.
Definition: ASTBitCodes.h:394
const HeaderFileInfo * getExistingFileInfo(const FileEntry *FE, bool WantExternal=true) const
Return the HeaderFileInfo structure for the specified FileEntry, if it has ever been filled in...
Decl * VaListTagDecl
Definition: ASTContext.h:927
A ObjCCompatibleAliasDecl record.
Definition: ASTBitCodes.h:1041
SourceLocation getProtocolRAngleLoc() const
Definition: TypeLoc.h:903
SmallVector< ExportDecl, 2 > Exports
The set of export declarations.
Definition: Basic/Module.h:230
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:416
SourceRange getBracketsRange() const
Definition: Type.h:2684
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition: Sema.h:534
A MS-style AsmStmt record.
Definition: ASTBitCodes.h:1229
void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record)
Emit a source location.
Definition: ASTWriter.cpp:4785
unsigned getLocalFastQualifiers() const
Definition: Type.h:628
void push_back(uint64_t N)
Minimal vector-like interface.
Definition: ASTWriter.h:741
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition: ASTBitCodes.h:126
const TemplateTypeParmType * getReplacedParameter() const
Gets the template parameter that was substituted for.
Definition: Type.h:3998
SpecifierKind
The kind of specifier that completes this nested name specifier.
SourceLocation getKWLoc() const
Definition: TypeLoc.h:1676
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:411
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1910
A template template parameter pack that has been substituted for a template template argument pack...
Definition: TemplateName.h:205
Wrapper for source info for arrays.
Definition: TypeLoc.h:1358
Record code for the set of source location entries that need to be preloaded by the AST reader...
Definition: ASTBitCodes.h:445
QualifierInfo - A struct with extended info about a syntactic name qualifier, to be used for the case...
Definition: Decl.h:613
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1479
Information about a FileID, basically just the logical file that it represents and include stack info...
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:512
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:215
DeclContext::lookup_result getLookupResult()
getLookupResult - Return an array of all the decls that this list represents.
unsigned isModuleHeader
Whether this header is part of a module.
Definition: HeaderSearch.h:57
Encapsulates changes to the "macros namespace" (the location where the macro name became active...
Definition: MacroInfo.h:307
SourceLocation getTemplateKeywordLoc() const
Definition: TypeLoc.h:1448
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1028
An UnresolvedUsingValueDecl record.
Definition: ASTBitCodes.h:1094
#define false
Definition: stdbool.h:33
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
StringRef FileName
Definition: Format.cpp:1313
Kind
bool hasRevertedBuiltin() const
True if setNotBuiltin() was called.
bool hasChangedSinceDeserialization() const
Determine whether this identifier has changed since it was loaded from an AST file.
serialization::IdentID BaseIdentifierID
Base identifier ID for identifiers local to this module.
const char * getName() const
Definition: FileManager.h:85
static uint64_t EmitCXXCtorInitializers(ASTWriter &W, ArrayRef< CXXCtorInitializer * > CtorInits)
Definition: ASTWriter.cpp:5428
Encodes a location in the source.
Sugar for parentheses used when specifying types.
Definition: Type.h:2148
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3733
void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg)
Emits a template argument location info.
Definition: ASTWriter.cpp:4879
const TemplateArgument * iterator
Definition: Type.h:4233
QualType getElementType() const
Definition: Type.h:2131
FileSystemOptions & getFileSystemOpts()
Returns the current file system options.
Definition: FileManager.h:223
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1078
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:674
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:3382
Record code for file ID of the file or buffer that was used to generate the AST file.
Definition: ASTBitCodes.h:278
Represents a C++ temporary.
Definition: ExprCXX.h:1088
Represents typeof(type), a GCC extension.
Definition: Type.h:3566
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:4936
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:657
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:119
A ComplexType record.
Definition: ASTBitCodes.h:822
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:500
OverloadedOperatorKind getCXXOverloadedOperator() const
getCXXOverloadedOperator - If this name is the name of an overloadable operator in C++ (e...
Options for controlling the compiler diagnostics engine.
A list of "interesting" identifiers.
Definition: ASTBitCodes.h:559
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1274
The block of configuration options, used to check that a module is being used in a configuration comp...
Definition: ASTBitCodes.h:252
void AddDeclarationName(DeclarationName Name)
Emit a declaration name.
Definition: ASTWriter.cpp:5067
const std::string ID
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2727
unsigned getOffset() const
bool isPackExpansion() const
Determine whether this base specifier is a pack expansion.
Definition: DeclCXX.h:215
virtual void writeExtensionContents(Sema &SemaRef, llvm::BitstreamWriter &Stream)=0
Write the contents of the extension block into the given bitstream.
This is so that older clang versions, before the introduction of the control block, can read and reject the newer PCH format.
Definition: ASTBitCodes.h:380
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:697
VectorKind getVectorKind() const
Definition: Type.h:2789
TagDecl * getCanonicalDecl() override
Definition: Decl.cpp:3533
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:53
Metadata describing this particular extension.
Definition: ASTBitCodes.h:328
static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule, const Preprocessor &PP)
Definition: ASTWriter.cpp:2109
FileManager & getFileMgr() const
Definition: HeaderSearch.h:260
SmallVector< Header, 2 > Headers[5]
The headers that are part of this module.
Definition: Basic/Module.h:126
A CXXFunctionalCastExpr record.
Definition: ASTBitCodes.h:1385
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:367
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:420
SourceLocation getNameLoc() const
Definition: TypeLoc.h:493
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:649
SourceLocation getDefinitionEndLoc() const
Return the location of the last token in the macro.
Definition: MacroInfo.h:126
void AddTemplateArgument(const TemplateArgument &Arg)
Emit a template argument.
Definition: ASTWriter.cpp:5318
An ObjCEncodeExpr record.
Definition: ASTBitCodes.h:1318
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
A TypeOfExprType record.
Definition: ASTBitCodes.h:850
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:90
Record code for late parsed template functions.
Definition: ASTBitCodes.h:566
Defines the clang::TargetOptions class.
A TemplateTypeParmDecl record.
Definition: ASTBitCodes.h:1133
frontend::IncludeDirGroup Group
unsigned LocalNumDecls
The number of declarations in this AST file.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2171
unsigned getMajor() const
Retrieve the major version number.
Definition: VersionTuple.h:74
The internal 'instancetype' typedef.
Definition: ASTBitCodes.h:964
unsigned getNumTypeArgs() const
Definition: TypeLoc.h:882
FunctionDecl * getExceptionSpecTemplate() const
If this function type has an uninstantiated exception specification, this is the function whose excep...
Definition: Type.h:3356
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:2010
void AddNestedNameSpecifier(NestedNameSpecifier *NNS)
Emit a nested name specifier.
Definition: ASTWriter.cpp:5166
Describes the categories of an Objective-C class.
Definition: ASTBitCodes.h:1543
static ASTFileSignature getSignature()
Definition: ASTWriter.cpp:1214
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:129
const FileInfo & getFile() const
The AST block, which acts as a container around the full AST block.
Definition: ASTBitCodes.h:213
TypedefNameDecl * getDecl() const
Definition: Type.h:3516
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:359
TypeSpecifierType getWrittenTypeSpec() const
Definition: TypeLoc.cpp:289
unsigned getNumProtocols() const
Return the number of qualifying protocols in this interface type, or 0 if there are none...
Definition: Type.h:4844
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
const unsigned int DECL_UPDATES
Record of updates for a declaration that was modified after being deserialized.
Definition: ASTBitCodes.h:999
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
SourceLocation getBegin() const
void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record)
Add a version tuple to the given record.
Definition: ASTWriter.cpp:4036
void updateOutOfDateSelector(Selector Sel)
ModuleFileExtension * getExtension() const
Retrieve the module file extension with which this writer is associated.
void AddSourceLocation(SourceLocation Loc)
Emit a source location.
Definition: ASTWriter.h:793
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1407
const Token & getReplacementToken(unsigned Tok) const
Definition: MacroInfo.h:233
void AddDeclRef(const Decl *D, RecordDataImpl &Record)
Emit a reference to a declaration.
Definition: ASTWriter.cpp:4977
An InjectedClassNameType record.
Definition: ASTBitCodes.h:870
FileID getMainFileID() const
Returns the FileID of the main source file.
bool getInheritConstructors() const
Determine whether this base class's constructors get inherited.
Definition: DeclCXX.h:218
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:417
FunctionDecl * getcudaConfigureCallDecl()
Definition: ASTContext.h:1101
A NamespaceDecl record.
Definition: ASTBitCodes.h:1082
SourceLocation getKWLoc() const
Definition: TypeLoc.h:1996
An array of decls optimized for the common case of only containing one entry.
void AddAPFloat(const llvm::APFloat &Value)
Emit a floating-point value.
Definition: ASTWriter.cpp:4806
bool PreparePathForOutput(SmallVectorImpl< char > &Path)
Convert a path from this build process into one that is appropriate for emission in the module file...
Definition: ASTWriter.cpp:4005
UTTKind getUTTKind() const
Definition: Type.h:3655
unsigned LocalNumSubmodules
The number of submodules in this module.
unsigned ComputeHash(Selector Sel)
Definition: ASTCommon.cpp:167
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:687
Record code for referenced selector pool.
Definition: ASTBitCodes.h:463
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:245
bool isLocalSourceLocation(SourceLocation Loc) const
Returns true if Loc did not come from a PCH/Module.
SourceLocation getNameLoc() const
Definition: TypeLoc.h:990
Represents a pointer type decayed from an array or function type.
Definition: Type.h:2263
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
Definition: Preprocessor.h:777
void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo)
Definition: ASTWriter.cpp:5152
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:4294
QualType getPointeeType() const
Definition: Type.h:2193
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:413
A ObjCProtocolDecl record.
Definition: ASTBitCodes.h:1029
Represents a pack expansion of types.
Definition: Type.h:4641
SmallVectorImpl< uint64_t > RecordDataImpl
Definition: ASTWriter.h:88
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:4828
DeclarationNameLoc - Additional source/type location info for a declaration name. ...
static void addExceptionSpec(const FunctionProtoType *T, ASTRecordWriter &Record)
Definition: ASTWriter.cpp:235
Expr * getSizeExpr() const
Definition: Type.h:2679
unsigned getFlags() const
Return the internal represtation of the flags.
Definition: Token.h:251
SourceLocation getLocation() const
Definition: Weak.h:35
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2609
void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset)
Note that the identifier II occurs at the given offset within the identifier table.
Definition: ASTWriter.cpp:4051
unsigned LocalNumSelectors
The number of selectors new to this file.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
Represents a template argument.
Definition: TemplateBase.h:40
Record code for the list of other AST files imported by this AST file.
Definition: ASTBitCodes.h:266
A CXXConversionDecl record.
Definition: ASTBitCodes.h:1110
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:639
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons...
Definition: Type.h:2227
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:238
Represents a template name that was expressed as a qualified name.
Definition: TemplateName.h:355
The internal '__NSConstantString' typedef.
Definition: ASTBitCodes.h:982
Record code for the module name.
Definition: ASTBitCodes.h:285
Selector getObjCSelector() const
getObjCSelector - Get the Objective-C selector stored in this declaration name.
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:643
An InitListExpr record.
Definition: ASTBitCodes.h:1275
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition: Sema.h:331
The internal '__builtin_ms_va_list' typedef.
Definition: ASTBitCodes.h:973
bool hasTemplateKeyword() const
Whether the template name was prefixed by the "template" keyword.
Definition: TemplateName.h:382
not evaluated yet, for special member function
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1135
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:533
A CXXBoolLiteralExpr record.
Definition: ASTBitCodes.h:1391
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:547
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:676
virtual ModuleFileExtensionMetadata getExtensionMetadata() const =0
Retrieves the metadata for this module file extension.
Module * inferModuleFromLocation(FullSourceLoc Loc)
Infers the (sub)module based on the given source location and source manager.
Definition: ModuleMap.cpp:916
SourceLocation getEllipsisLoc() const
Definition: TypeLoc.h:1956
bool hasLocalNonFastQualifiers() const
Determine whether this particular QualType instance has any "non-fast" qualifiers, e.g., those that are stored in an ExtQualType instance.
Definition: Type.h:712
An ExtVectorElementExpr record.
Definition: ASTBitCodes.h:1273
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:63
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:451
void AddCXXBaseSpecifiers(ArrayRef< CXXBaseSpecifier > Bases)
Emit a set of C++ base specifiers.
Definition: ASTWriter.cpp:5423
llvm::iterator_range< submodule_iterator > submodules()
Definition: Basic/Module.h:479
A FunctionNoProtoType record.
Definition: ASTBitCodes.h:844
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:312
bool getProducesResult() const
Definition: Type.h:2946
QualType getEquivalentType() const
Definition: Type.h:3832
A ClassTemplatePartialSpecializationDecl record.
Definition: ASTBitCodes.h:1123
#define RECORD(X)
SourceLocation getStarLoc() const
Definition: TypeLoc.h:1202
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1454
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
SourceLocation getTemplateKeywordLoc() const
Definition: TypeLoc.h:1871
bool isGNUVarargs() const
Definition: MacroInfo.h:203
bool isParameterPack() const
Definition: Type.h:3947
const ContentCache * getContentCache() const
DeclarationName - The name of a declaration.
A ClassScopeFunctionSpecializationDecl record a class scope function specialization.
Definition: ASTBitCodes.h:1156
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:429
const MacroInfo * getMacroInfo() const
Definition: MacroInfo.h:403
static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a buffer.
Definition: ASTWriter.cpp:1660
CallingConv getCC() const
Definition: Type.h:2954
SourceLocation getCaretLoc() const
Definition: TypeLoc.h:1150
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:680
Expr * getSizeExpr() const
Definition: TypeLoc.h:1381
A LinkageSpecDecl record.
Definition: ASTBitCodes.h:1098
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:636
A CXXDynamicCastExpr record.
Definition: ASTBitCodes.h:1379
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:582
An EnumType record.
Definition: ASTBitCodes.h:856
detail::InMemoryDirectory::const_iterator E
SourceLocation getElaboratedKeywordLoc() const
Definition: TypeLoc.h:1785
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2401
QualType getModifiedType() const
Definition: Type.h:3831
PreprocessingRecord * getPreprocessingRecord() const
Retrieve the preprocessing record, or NULL if there is no preprocessing record.
Definition: Preprocessor.h:989
IdentifierResolver IdResolver
Definition: Sema.h:708
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1966
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
SourceLocation getExpansionLocStart() const
An RValueReferenceType record.
Definition: ASTBitCodes.h:830
A type that was preceded by the 'template' keyword, stored as a Type*.
unsigned char getOpaqueValue() const
Definition: Type.h:3128
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension...
unsigned Map[Count]
The type of a lookup table which maps from language-specific address spaces to target-specific ones...
Definition: AddressSpaces.h:45
An AtomicType record.
Definition: ASTBitCodes.h:896
An ObjCAtFinallyStmt record.
Definition: ASTBitCodes.h:1343
bool IsLocalDecl(const Decl *D)
Is this a local declaration (that is, one that will be written to our AST file)? This is the case for...
Definition: ASTWriter.h:571
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5006
Represents a pointer to an Objective C object.
Definition: Type.h:4991
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:34
Pointer to a block type.
Definition: Type.h:2286
Capturing variable-length array type.
Definition: Lambda.h:39
A PragmaCommentDecl record.
Definition: ASTBitCodes.h:1168
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:831
time_t getModificationTime() const
Definition: FileManager.h:92
struct CXXLitOpName CXXLiteralOperatorName
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3707
TypeSpecifierSign getWrittenSignSpec() const
Definition: TypeLoc.h:558
Complex values, per C99 6.2.5p11.
Definition: Type.h:2119
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:427
std::vector< Conflict > Conflicts
The list of conflicts.
Definition: Basic/Module.h:304
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:426
unsigned getTypeQuals() const
Definition: Type.h:3378
bool getUsed()
Definition: Weak.h:37
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:540
A DependentSizedArrayType record.
Definition: ASTBitCodes.h:882
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:522
An ObjCAtSynchronizedStmt record.
Definition: ASTBitCodes.h:1347
A key used when looking up entities by DeclarationName.
Definition: ASTBitCodes.h:1573
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
An UnresolvedSet-like class which uses the ASTContext's allocator.
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:472
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:294
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
Definition: ASTBitCodes.h:139
Offsets into the input-files block where input files reside.
Definition: ASTBitCodes.h:282
A CXXMemberCallExpr record.
Definition: ASTBitCodes.h:1369
ExtVectorType - Extended vector type.
Definition: Type.h:2816
QualType getInnerType() const
Definition: Type.h:2162
void AddAPSInt(const llvm::APSInt &Value)
Emit a signed integral value.
Definition: ASTWriter.cpp:4801
const DeclarationNameLoc & getInfo() const
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
Definition: MacroInfo.h:212
The block containing the submodule structure.
Definition: ASTBitCodes.h:231
Wrapper for source info for record types.
Definition: TypeLoc.h:672
TypeSourceInfo * getTypeSourceInfo() const
Retrieves the type and source location of the base class.
Definition: DeclCXX.h:259
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1815
The template argument is a type.
Definition: TemplateBase.h:48
Wraps an ObjCPointerType with source location information.
Definition: TypeLoc.h:1198
import_range local_imports() const
Definition: ASTContext.h:857
Optional< unsigned > getSubminor() const
Retrieve the subminor version number, if provided.
Definition: VersionTuple.h:84
serialization::SelectorID getSelectorRef(Selector Sel)
Get the unique number used to refer to the given selector.
Definition: ASTWriter.cpp:4856
The template argument is actually a parameter pack.
Definition: TemplateBase.h:72
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Capturing the *this object by reference.
Definition: Lambda.h:35
void EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record, StringRef Path)
Emit the current record with the given path as a blob.
Definition: ASTWriter.cpp:4029
Represents a base class of a C++ class.
Definition: DeclCXX.h:159
SourceLocation getProtocolLAngleLoc() const
Definition: TypeLoc.h:896
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
SourceManager & getSourceManager()
Definition: ASTContext.h:561
Keeps track of options that affect how file operations are performed.
NestedNameSpecifierLoc getQualifierLoc() const
Definition: TypeLoc.h:1847
The type-property cache.
Definition: Type.cpp:3242
A TypedefType record.
Definition: ASTBitCodes.h:848
A template argument list.
Definition: DeclTemplate.h:173
TemplateArgumentLocInfo getLocInfo() const
Definition: TemplateBase.h:474
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
const Type * getClass() const
Definition: Type.h:2434
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:256
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:614
PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
Definition: Preprocessor.h:685
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:3761
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:157
SourceLocation getProtocolLoc(unsigned i) const
Definition: TypeLoc.h:914
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:335
known_categories_iterator known_categories_end() const
Retrieve an iterator to the end of the known-categories list.
Definition: DeclObjC.h:1605
bool isPackExpansion() const
Determine whether this capture is a pack expansion, which captures a function parameter pack...
A GCC-style AsmStmt record.
Definition: ASTBitCodes.h:1227
void SetSelectorOffset(Selector Sel, uint32_t Offset)
Note that the selector Sel occurs at the given offset within the method pool/selector table...
Definition: ASTWriter.cpp:4061
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition: Basic/Module.h:187
Represents a C++ struct/union/class.
Definition: DeclCXX.h:263
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:142
An TemplateTypeParmType record.
Definition: ASTBitCodes.h:874
Decl * D
The template function declaration to be late parsed.
Definition: Sema.h:9646
The template argument is a template name that was provided for a template template parameter...
Definition: TemplateBase.h:60
Represents a C array with an unspecified size.
Definition: Type.h:2562
Record code for the filesystem options table.
Definition: ASTBitCodes.h:316
SourceLocation getTemplateNameLoc() const
Definition: TypeLoc.h:1878
An object for streaming information to a record.
Definition: ASTWriter.h:693
static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, ASTWriter::RecordData &Record)
Definition: ASTWriter.cpp:4143
An ObjCAtCatchStmt record.
Definition: ASTBitCodes.h:1341
static bool cleanPathForOutput(FileManager &FileMgr, SmallVectorImpl< char > &Path)
Prepares a path for being written to an AST file by converting it to an absolute path and removing ne...
Definition: ASTWriter.cpp:1161
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
Definition: ASTCommon.cpp:323
A ObjCImplementationDecl record.
Definition: ASTBitCodes.h:1039
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition: Sema.h:325
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
ArraySizeModifier getSizeModifier() const
Definition: Type.h:2491
ElaboratedTypeKeyword getKeyword() const
Definition: Type.h:4391
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:93
Capturing by reference.
Definition: Lambda.h:38
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1281
Location information for a TemplateArgument.
Definition: TemplateBase.h:368
A ObjCAtDefsFieldDecl record.
Definition: ASTBitCodes.h:1033
Record code for the offsets of each type.
Definition: ASTBitCodes.h:355
The block containing the definitions of all of the types and decls used within the AST file...
Definition: ASTBitCodes.h:225
The internal '__va_list_tag' struct, if any.
Definition: ASTBitCodes.h:970
This class is used for builtin types like 'int'.
Definition: Type.h:2039
Writes an AST file containing the contents of a translation unit.
Definition: ASTWriter.h:84
SourceLocation getLBracketLoc() const
Definition: Type.h:2629
serialization::DeclID getDeclID(const Decl *D)
Determine the declaration ID of an already-emitted declaration.
Definition: ASTWriter.cpp:5010
QualType getAdjustedType() const
Definition: Type.h:2244
const unsigned int LOCAL_REDECLARATIONS
Record code for a list of local redeclarations of a declaration.
Definition: ASTBitCodes.h:1003
void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base)
Emit a C++ base specifier.
Definition: ASTWriter.cpp:5399
A TypeAliasDecl record.
Definition: ASTBitCodes.h:1015
void AddASTTemplateArgumentListInfo(const ASTTemplateArgumentListInfo *ASTTemplArgList)
Emits an AST template argument list info.
Definition: ASTWriter.cpp:5378
void AddAPInt(const llvm::APInt &Value)
Emit an integral value.
Definition: ASTWriter.cpp:4795
LineTableInfo & getLineTable()
Retrieve the stored line table.
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:250
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:378
uint64_t WriteAST(Sema &SemaRef, const std::string &OutputFile, Module *WritingModule, StringRef isysroot, bool hasErrors=false)
Write a precompiled header for the given semantic analysis.
Definition: ASTWriter.cpp:4113
Defines the clang::TargetInfo interface.
MacroDefinitionRecord * findMacroDefinition(const MacroInfo *MI)
Retrieve the macro definition that corresponds to the given MacroInfo.
A SourceLocation and its associated SourceManager.
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:4668
Defines the clang::VersionTuple class, which represents a version in the form major[.minor[.subminor]].
ArrayRef< ModuleMacro * > getLeafModuleMacros(const IdentifierInfo *II) const
Get the list of leaf (non-overridden) module macros for a name.
Definition: Preprocessor.h:898
a linked list of methods with the same selector name but different signatures.
Specifies a required feature.
Definition: ASTBitCodes.h:669
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
QualType getPointeeTypeAsWritten() const
Definition: Type.h:2339
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition: Basic/Module.h:279
bool getHasRegParm() const
Definition: Type.h:2947
TypeSourceInfo * getAsTypeSourceInfo() const
Definition: TemplateBase.h:403
uint32_t getIndex() const
Definition: ASTBitCodes.h:89
TagDecl * getDecl() const
Definition: Type.cpp:2960
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1682
SourceLocation getRBracketLoc() const
Definition: Type.h:2630
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:489
unsigned ModuleMapFileHomeIsCwd
Set the 'home directory' of a module map file to the current working directory (or the home directory...
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:80
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace nested inside this namespace, if any.
Definition: Decl.h:548
void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs)
Emit a template argument list.
Definition: ASTWriter.cpp:5370
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:1513
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:133
static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream, bool Compressed)
Create an abbreviation for the SLocEntry that refers to a buffer's blob.
Definition: ASTWriter.cpp:1675
unsigned getLength() const
Definition: Token.h:126
QualType getElementType() const
Definition: Type.h:5203
QualType getElementType() const
Definition: Type.h:2490
SourceLocation getStarLoc() const
Definition: TypeLoc.h:1137
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:991
A FunctionTemplateDecl record.
Definition: ASTBitCodes.h:1131
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition: Sema.h:5377
A TypeAliasTemplateDecl record.
Definition: ASTBitCodes.h:1139
Contains a late templated function.
Definition: Sema.h:9643
OverloadedOperatorKind getOperatorKind() const
Definition: ASTBitCodes.h:1599
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:475
The block containing information about the preprocessor.
Definition: ASTBitCodes.h:221
void AddTemplateName(TemplateName Name)
Emit a template name.
Definition: ASTWriter.cpp:5265
A DecayedType record.
Definition: ASTBitCodes.h:898
SourceLocation getAmpLoc() const
Definition: TypeLoc.h:1225
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:1455
void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg)
Emits a template argument location.
Definition: ASTWriter.cpp:4907
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:80
Wrapper for source info for builtin types.
Definition: TypeLoc.h:517
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
void VisitFunctionType(const FunctionType *T)
Definition: ASTWriter.cpp:216
A set of overloaded template declarations.
Definition: TemplateName.h:192
Wrapper for template type parameters.
Definition: TypeLoc.h:688
Record code for the headers search options table.
Definition: ASTBitCodes.h:319
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:299
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
AST file metadata, including the AST file version number and information about the compiler used to b...
Definition: ASTBitCodes.h:262
static void EmitRecordID(unsigned ID, const char *Name, llvm::BitstreamWriter &Stream, ASTWriter::RecordDataImpl &Record)
Definition: ASTWriter.cpp:767
The block of input files, which were used as inputs to create this AST file.
Definition: ASTBitCodes.h:245
ObjCMethodList * getNext() const
unsigned IsExplicit
Whether this is an explicit submodule.
Definition: Basic/Module.h:169
NestedNameSpecifierLoc getQualifierLoc() const
Definition: TypeLoc.h:1734
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2607
void numberAnonymousDeclsWithin(const DeclContext *DC, Fn Visit)
Visit each declaration within DC that needs an anonymous declaration number and call Visit with the d...
Definition: ASTCommon.h:94
unsigned LocalNumTypes
The number of types in this AST file.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition: DeclCXX.h:203
The internal '__NSConstantString' tag type.
Definition: ASTBitCodes.h:985
A function-like macro definition.
Definition: ASTBitCodes.h:619
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:665
The Objective-C 'Protocol' type.
Definition: ASTBitCodes.h:955
The global specifier '::'. There is no stored value.
T * getFETokenInfo() const
getFETokenInfo/setFETokenInfo - The language front-end is allowed to associate arbitrary metadata wit...
NamespaceDecl * getStdNamespace() const
The control block, which contains all of the information that needs to be validated prior to committi...
Definition: ASTBitCodes.h:239
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:470
Wrapper for source info for pointers.
Definition: TypeLoc.h:1134
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1147
TemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon, QualType Aliased)
Optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:4672
This class handles loading and caching of source files into memory.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2512
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1099
PredefinedDeclIDs
Predefined declaration IDs.
Definition: ASTBitCodes.h:938
iterator - Iterate over the decls of a specified declaration name.
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:467
TypeSourceInfo * getUnderlyingTInfo() const
Definition: TypeLoc.h:1685
A class which abstracts out some details necessary for making a call.
Definition: Type.h:2904
A GenericSelectionExpr record.
Definition: ASTBitCodes.h:1301
A type index; the type ID with the qualifier bits removed.
Definition: ASTBitCodes.h:83
Attr - This represents one attribute.
Definition: Attr.h:45
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Definition: MacroInfo.h:342
bool SawDateOrTime() const
Returns true if the preprocessor has seen a use of DATE or TIME in the file so far.
A PackExpansionType record.
Definition: ASTBitCodes.h:886
ASTWriter(llvm::BitstreamWriter &Stream, ArrayRef< llvm::IntrusiveRefCntPtr< ModuleFileExtension >> Extensions, bool IncludeTimestamps=true)
Create a new precompiled header writer that outputs to the given bitstream.
Definition: ASTWriter.cpp:4071
A single template declaration.
Definition: TemplateName.h:190
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
Definition: ASTBitCodes.h:163
SourceLocation getLocation() const
Definition: MacroInfo.h:336
SourceLocation getStarLoc() const
Definition: TypeLoc.h:1167
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition: Basic/Module.h:191
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:583
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:97
void GetUniqueIDMapping(SmallVectorImpl< const FileEntry * > &UIDToFiles) const
Produce an array mapping from the unique IDs assigned to each file to the corresponding FileEntry poi...
A DependentTemplateSpecializationType record.
Definition: ASTBitCodes.h:880
bool isUsed() const
Return false if this macro is defined in the main file and has not yet been used. ...
Definition: MacroInfo.h:219
SourceLocation getSpellingLoc() const
bool capturesVariable() const
Determine whether this capture handles a variable.
Definition: LambdaCapture.h:89
bool isHidden() const
Determine whether this declaration is hidden from name lookup.
Definition: Decl.h:305
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1594
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:420
unsigned getNumExceptions() const
Definition: Type.h:3331
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1025
iterator local_begin()
Begin iterator for local, non-loaded, preprocessed entities.
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:176
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:131
QualType getDeducedType() const
Get the type deduced for this auto type, or null if it's either not been deduced or was deduced to a ...
Definition: Type.h:4111