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