1 //===--- ASTWriter.cpp - AST File Writer ----------------------------------===//
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
14 #include "clang/Serialization/ASTWriter.h"
15 #include "clang/Serialization/ASTSerializationListener.h"
16 #include "ASTCommon.h"
17 #include "clang/Sema/Sema.h"
18 #include "clang/Sema/IdentifierResolver.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclContextInternals.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/Type.h"
27 #include "clang/AST/TypeLocVisitor.h"
28 #include "clang/Serialization/ASTReader.h"
29 #include "clang/Lex/MacroInfo.h"
30 #include "clang/Lex/PreprocessingRecord.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/HeaderSearch.h"
33 #include "clang/Basic/FileManager.h"
34 #include "clang/Basic/FileSystemStatCache.h"
35 #include "clang/Basic/OnDiskHashTable.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/SourceManagerInternals.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Basic/Version.h"
40 #include "clang/Basic/VersionTuple.h"
41 #include "llvm/ADT/APFloat.h"
42 #include "llvm/ADT/APInt.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/Bitcode/BitstreamWriter.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include <algorithm>
49 #include <cstdio>
50 #include <string.h>
51 #include <utility>
52 using namespace clang;
53 using namespace clang::serialization;
54
55 template <typename T, typename Allocator>
data(const std::vector<T,Allocator> & v)56 static llvm::StringRef data(const std::vector<T, Allocator> &v) {
57 if (v.empty()) return llvm::StringRef();
58 return llvm::StringRef(reinterpret_cast<const char*>(&v[0]),
59 sizeof(T) * v.size());
60 }
61
62 template <typename T>
data(const llvm::SmallVectorImpl<T> & v)63 static llvm::StringRef data(const llvm::SmallVectorImpl<T> &v) {
64 return llvm::StringRef(reinterpret_cast<const char*>(v.data()),
65 sizeof(T) * v.size());
66 }
67
68 //===----------------------------------------------------------------------===//
69 // Type serialization
70 //===----------------------------------------------------------------------===//
71
72 namespace {
73 class ASTTypeWriter {
74 ASTWriter &Writer;
75 ASTWriter::RecordDataImpl &Record;
76
77 public:
78 /// \brief Type code that corresponds to the record generated.
79 TypeCode Code;
80
ASTTypeWriter(ASTWriter & Writer,ASTWriter::RecordDataImpl & Record)81 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
82 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
83
84 void VisitArrayType(const ArrayType *T);
85 void VisitFunctionType(const FunctionType *T);
86 void VisitTagType(const TagType *T);
87
88 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
89 #define ABSTRACT_TYPE(Class, Base)
90 #include "clang/AST/TypeNodes.def"
91 };
92 }
93
VisitBuiltinType(const BuiltinType * T)94 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
95 assert(false && "Built-in types are never serialized");
96 }
97
VisitComplexType(const ComplexType * T)98 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
99 Writer.AddTypeRef(T->getElementType(), Record);
100 Code = TYPE_COMPLEX;
101 }
102
VisitPointerType(const PointerType * T)103 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
104 Writer.AddTypeRef(T->getPointeeType(), Record);
105 Code = TYPE_POINTER;
106 }
107
VisitBlockPointerType(const BlockPointerType * T)108 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
109 Writer.AddTypeRef(T->getPointeeType(), Record);
110 Code = TYPE_BLOCK_POINTER;
111 }
112
VisitLValueReferenceType(const LValueReferenceType * T)113 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
114 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
115 Record.push_back(T->isSpelledAsLValue());
116 Code = TYPE_LVALUE_REFERENCE;
117 }
118
VisitRValueReferenceType(const RValueReferenceType * T)119 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
120 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
121 Code = TYPE_RVALUE_REFERENCE;
122 }
123
VisitMemberPointerType(const MemberPointerType * T)124 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
125 Writer.AddTypeRef(T->getPointeeType(), Record);
126 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
127 Code = TYPE_MEMBER_POINTER;
128 }
129
VisitArrayType(const ArrayType * T)130 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
131 Writer.AddTypeRef(T->getElementType(), Record);
132 Record.push_back(T->getSizeModifier()); // FIXME: stable values
133 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
134 }
135
VisitConstantArrayType(const ConstantArrayType * T)136 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
137 VisitArrayType(T);
138 Writer.AddAPInt(T->getSize(), Record);
139 Code = TYPE_CONSTANT_ARRAY;
140 }
141
VisitIncompleteArrayType(const IncompleteArrayType * T)142 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
143 VisitArrayType(T);
144 Code = TYPE_INCOMPLETE_ARRAY;
145 }
146
VisitVariableArrayType(const VariableArrayType * T)147 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
148 VisitArrayType(T);
149 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
150 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
151 Writer.AddStmt(T->getSizeExpr());
152 Code = TYPE_VARIABLE_ARRAY;
153 }
154
VisitVectorType(const VectorType * T)155 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
156 Writer.AddTypeRef(T->getElementType(), Record);
157 Record.push_back(T->getNumElements());
158 Record.push_back(T->getVectorKind());
159 Code = TYPE_VECTOR;
160 }
161
VisitExtVectorType(const ExtVectorType * T)162 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
163 VisitVectorType(T);
164 Code = TYPE_EXT_VECTOR;
165 }
166
VisitFunctionType(const FunctionType * T)167 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
168 Writer.AddTypeRef(T->getResultType(), Record);
169 FunctionType::ExtInfo C = T->getExtInfo();
170 Record.push_back(C.getNoReturn());
171 Record.push_back(C.getHasRegParm());
172 Record.push_back(C.getRegParm());
173 // FIXME: need to stabilize encoding of calling convention...
174 Record.push_back(C.getCC());
175 Record.push_back(C.getProducesResult());
176 }
177
VisitFunctionNoProtoType(const FunctionNoProtoType * T)178 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
179 VisitFunctionType(T);
180 Code = TYPE_FUNCTION_NO_PROTO;
181 }
182
VisitFunctionProtoType(const FunctionProtoType * T)183 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
184 VisitFunctionType(T);
185 Record.push_back(T->getNumArgs());
186 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
187 Writer.AddTypeRef(T->getArgType(I), Record);
188 Record.push_back(T->isVariadic());
189 Record.push_back(T->getTypeQuals());
190 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
191 Record.push_back(T->getExceptionSpecType());
192 if (T->getExceptionSpecType() == EST_Dynamic) {
193 Record.push_back(T->getNumExceptions());
194 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
195 Writer.AddTypeRef(T->getExceptionType(I), Record);
196 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
197 Writer.AddStmt(T->getNoexceptExpr());
198 }
199 Code = TYPE_FUNCTION_PROTO;
200 }
201
VisitUnresolvedUsingType(const UnresolvedUsingType * T)202 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
203 Writer.AddDeclRef(T->getDecl(), Record);
204 Code = TYPE_UNRESOLVED_USING;
205 }
206
VisitTypedefType(const TypedefType * T)207 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
208 Writer.AddDeclRef(T->getDecl(), Record);
209 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
210 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
211 Code = TYPE_TYPEDEF;
212 }
213
VisitTypeOfExprType(const TypeOfExprType * T)214 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
215 Writer.AddStmt(T->getUnderlyingExpr());
216 Code = TYPE_TYPEOF_EXPR;
217 }
218
VisitTypeOfType(const TypeOfType * T)219 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
220 Writer.AddTypeRef(T->getUnderlyingType(), Record);
221 Code = TYPE_TYPEOF;
222 }
223
VisitDecltypeType(const DecltypeType * T)224 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
225 Writer.AddStmt(T->getUnderlyingExpr());
226 Code = TYPE_DECLTYPE;
227 }
228
VisitUnaryTransformType(const UnaryTransformType * T)229 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
230 Writer.AddTypeRef(T->getBaseType(), Record);
231 Writer.AddTypeRef(T->getUnderlyingType(), Record);
232 Record.push_back(T->getUTTKind());
233 Code = TYPE_UNARY_TRANSFORM;
234 }
235
VisitAutoType(const AutoType * T)236 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
237 Writer.AddTypeRef(T->getDeducedType(), Record);
238 Code = TYPE_AUTO;
239 }
240
VisitTagType(const TagType * T)241 void ASTTypeWriter::VisitTagType(const TagType *T) {
242 Record.push_back(T->isDependentType());
243 Writer.AddDeclRef(T->getDecl(), Record);
244 assert(!T->isBeingDefined() &&
245 "Cannot serialize in the middle of a type definition");
246 }
247
VisitRecordType(const RecordType * T)248 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
249 VisitTagType(T);
250 Code = TYPE_RECORD;
251 }
252
VisitEnumType(const EnumType * T)253 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
254 VisitTagType(T);
255 Code = TYPE_ENUM;
256 }
257
VisitAttributedType(const AttributedType * T)258 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
259 Writer.AddTypeRef(T->getModifiedType(), Record);
260 Writer.AddTypeRef(T->getEquivalentType(), Record);
261 Record.push_back(T->getAttrKind());
262 Code = TYPE_ATTRIBUTED;
263 }
264
265 void
VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType * T)266 ASTTypeWriter::VisitSubstTemplateTypeParmType(
267 const SubstTemplateTypeParmType *T) {
268 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
269 Writer.AddTypeRef(T->getReplacementType(), Record);
270 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
271 }
272
273 void
VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType * T)274 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
275 const SubstTemplateTypeParmPackType *T) {
276 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
277 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
278 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
279 }
280
281 void
VisitTemplateSpecializationType(const TemplateSpecializationType * T)282 ASTTypeWriter::VisitTemplateSpecializationType(
283 const TemplateSpecializationType *T) {
284 Record.push_back(T->isDependentType());
285 Writer.AddTemplateName(T->getTemplateName(), Record);
286 Record.push_back(T->getNumArgs());
287 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
288 ArgI != ArgE; ++ArgI)
289 Writer.AddTemplateArgument(*ArgI, Record);
290 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
291 T->isCanonicalUnqualified() ? QualType()
292 : T->getCanonicalTypeInternal(),
293 Record);
294 Code = TYPE_TEMPLATE_SPECIALIZATION;
295 }
296
297 void
VisitDependentSizedArrayType(const DependentSizedArrayType * T)298 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
299 VisitArrayType(T);
300 Writer.AddStmt(T->getSizeExpr());
301 Writer.AddSourceRange(T->getBracketsRange(), Record);
302 Code = TYPE_DEPENDENT_SIZED_ARRAY;
303 }
304
305 void
VisitDependentSizedExtVectorType(const DependentSizedExtVectorType * T)306 ASTTypeWriter::VisitDependentSizedExtVectorType(
307 const DependentSizedExtVectorType *T) {
308 // FIXME: Serialize this type (C++ only)
309 assert(false && "Cannot serialize dependent sized extended vector types");
310 }
311
312 void
VisitTemplateTypeParmType(const TemplateTypeParmType * T)313 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
314 Record.push_back(T->getDepth());
315 Record.push_back(T->getIndex());
316 Record.push_back(T->isParameterPack());
317 Writer.AddDeclRef(T->getDecl(), Record);
318 Code = TYPE_TEMPLATE_TYPE_PARM;
319 }
320
321 void
VisitDependentNameType(const DependentNameType * T)322 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
323 Record.push_back(T->getKeyword());
324 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
325 Writer.AddIdentifierRef(T->getIdentifier(), Record);
326 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
327 : T->getCanonicalTypeInternal(),
328 Record);
329 Code = TYPE_DEPENDENT_NAME;
330 }
331
332 void
VisitDependentTemplateSpecializationType(const DependentTemplateSpecializationType * T)333 ASTTypeWriter::VisitDependentTemplateSpecializationType(
334 const DependentTemplateSpecializationType *T) {
335 Record.push_back(T->getKeyword());
336 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
337 Writer.AddIdentifierRef(T->getIdentifier(), Record);
338 Record.push_back(T->getNumArgs());
339 for (DependentTemplateSpecializationType::iterator
340 I = T->begin(), E = T->end(); I != E; ++I)
341 Writer.AddTemplateArgument(*I, Record);
342 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
343 }
344
VisitPackExpansionType(const PackExpansionType * T)345 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
346 Writer.AddTypeRef(T->getPattern(), Record);
347 if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions())
348 Record.push_back(*NumExpansions + 1);
349 else
350 Record.push_back(0);
351 Code = TYPE_PACK_EXPANSION;
352 }
353
VisitParenType(const ParenType * T)354 void ASTTypeWriter::VisitParenType(const ParenType *T) {
355 Writer.AddTypeRef(T->getInnerType(), Record);
356 Code = TYPE_PAREN;
357 }
358
VisitElaboratedType(const ElaboratedType * T)359 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
360 Record.push_back(T->getKeyword());
361 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
362 Writer.AddTypeRef(T->getNamedType(), Record);
363 Code = TYPE_ELABORATED;
364 }
365
VisitInjectedClassNameType(const InjectedClassNameType * T)366 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
367 Writer.AddDeclRef(T->getDecl(), Record);
368 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
369 Code = TYPE_INJECTED_CLASS_NAME;
370 }
371
VisitObjCInterfaceType(const ObjCInterfaceType * T)372 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
373 Writer.AddDeclRef(T->getDecl(), Record);
374 Code = TYPE_OBJC_INTERFACE;
375 }
376
VisitObjCObjectType(const ObjCObjectType * T)377 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
378 Writer.AddTypeRef(T->getBaseType(), Record);
379 Record.push_back(T->getNumProtocols());
380 for (ObjCObjectType::qual_iterator I = T->qual_begin(),
381 E = T->qual_end(); I != E; ++I)
382 Writer.AddDeclRef(*I, Record);
383 Code = TYPE_OBJC_OBJECT;
384 }
385
386 void
VisitObjCObjectPointerType(const ObjCObjectPointerType * T)387 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
388 Writer.AddTypeRef(T->getPointeeType(), Record);
389 Code = TYPE_OBJC_OBJECT_POINTER;
390 }
391
392 namespace {
393
394 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
395 ASTWriter &Writer;
396 ASTWriter::RecordDataImpl &Record;
397
398 public:
TypeLocWriter(ASTWriter & Writer,ASTWriter::RecordDataImpl & Record)399 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
400 : Writer(Writer), Record(Record) { }
401
402 #define ABSTRACT_TYPELOC(CLASS, PARENT)
403 #define TYPELOC(CLASS, PARENT) \
404 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
405 #include "clang/AST/TypeLocNodes.def"
406
407 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
408 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
409 };
410
411 }
412
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)413 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
414 // nothing to do
415 }
VisitBuiltinTypeLoc(BuiltinTypeLoc TL)416 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
417 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
418 if (TL.needsExtraLocalData()) {
419 Record.push_back(TL.getWrittenTypeSpec());
420 Record.push_back(TL.getWrittenSignSpec());
421 Record.push_back(TL.getWrittenWidthSpec());
422 Record.push_back(TL.hasModeAttr());
423 }
424 }
VisitComplexTypeLoc(ComplexTypeLoc TL)425 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
426 Writer.AddSourceLocation(TL.getNameLoc(), Record);
427 }
VisitPointerTypeLoc(PointerTypeLoc TL)428 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
429 Writer.AddSourceLocation(TL.getStarLoc(), Record);
430 }
VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL)431 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
432 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
433 }
VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL)434 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
435 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
436 }
VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL)437 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
438 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
439 }
VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL)440 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
441 Writer.AddSourceLocation(TL.getStarLoc(), Record);
442 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
443 }
VisitArrayTypeLoc(ArrayTypeLoc TL)444 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
445 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
446 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
447 Record.push_back(TL.getSizeExpr() ? 1 : 0);
448 if (TL.getSizeExpr())
449 Writer.AddStmt(TL.getSizeExpr());
450 }
VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL)451 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
452 VisitArrayTypeLoc(TL);
453 }
VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL)454 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
455 VisitArrayTypeLoc(TL);
456 }
VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL)457 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
458 VisitArrayTypeLoc(TL);
459 }
VisitDependentSizedArrayTypeLoc(DependentSizedArrayTypeLoc TL)460 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
461 DependentSizedArrayTypeLoc TL) {
462 VisitArrayTypeLoc(TL);
463 }
VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL)464 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
465 DependentSizedExtVectorTypeLoc TL) {
466 Writer.AddSourceLocation(TL.getNameLoc(), Record);
467 }
VisitVectorTypeLoc(VectorTypeLoc TL)468 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
469 Writer.AddSourceLocation(TL.getNameLoc(), Record);
470 }
VisitExtVectorTypeLoc(ExtVectorTypeLoc TL)471 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
472 Writer.AddSourceLocation(TL.getNameLoc(), Record);
473 }
VisitFunctionTypeLoc(FunctionTypeLoc TL)474 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
475 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
476 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
477 Record.push_back(TL.getTrailingReturn());
478 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
479 Writer.AddDeclRef(TL.getArg(i), Record);
480 }
VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL)481 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
482 VisitFunctionTypeLoc(TL);
483 }
VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL)484 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
485 VisitFunctionTypeLoc(TL);
486 }
VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL)487 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
488 Writer.AddSourceLocation(TL.getNameLoc(), Record);
489 }
VisitTypedefTypeLoc(TypedefTypeLoc TL)490 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
491 Writer.AddSourceLocation(TL.getNameLoc(), Record);
492 }
VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL)493 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
494 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
495 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
496 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
497 }
VisitTypeOfTypeLoc(TypeOfTypeLoc TL)498 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
499 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
500 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
501 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
502 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
503 }
VisitDecltypeTypeLoc(DecltypeTypeLoc TL)504 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
505 Writer.AddSourceLocation(TL.getNameLoc(), Record);
506 }
VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL)507 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
508 Writer.AddSourceLocation(TL.getKWLoc(), Record);
509 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
510 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
511 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
512 }
VisitAutoTypeLoc(AutoTypeLoc TL)513 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
514 Writer.AddSourceLocation(TL.getNameLoc(), Record);
515 }
VisitRecordTypeLoc(RecordTypeLoc TL)516 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
517 Writer.AddSourceLocation(TL.getNameLoc(), Record);
518 }
VisitEnumTypeLoc(EnumTypeLoc TL)519 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
520 Writer.AddSourceLocation(TL.getNameLoc(), Record);
521 }
VisitAttributedTypeLoc(AttributedTypeLoc TL)522 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
523 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
524 if (TL.hasAttrOperand()) {
525 SourceRange range = TL.getAttrOperandParensRange();
526 Writer.AddSourceLocation(range.getBegin(), Record);
527 Writer.AddSourceLocation(range.getEnd(), Record);
528 }
529 if (TL.hasAttrExprOperand()) {
530 Expr *operand = TL.getAttrExprOperand();
531 Record.push_back(operand ? 1 : 0);
532 if (operand) Writer.AddStmt(operand);
533 } else if (TL.hasAttrEnumOperand()) {
534 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
535 }
536 }
VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL)537 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
538 Writer.AddSourceLocation(TL.getNameLoc(), Record);
539 }
VisitSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL)540 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
541 SubstTemplateTypeParmTypeLoc TL) {
542 Writer.AddSourceLocation(TL.getNameLoc(), Record);
543 }
VisitSubstTemplateTypeParmPackTypeLoc(SubstTemplateTypeParmPackTypeLoc TL)544 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
545 SubstTemplateTypeParmPackTypeLoc TL) {
546 Writer.AddSourceLocation(TL.getNameLoc(), Record);
547 }
VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL)548 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
549 TemplateSpecializationTypeLoc TL) {
550 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
551 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
552 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
553 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
554 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
555 TL.getArgLoc(i).getLocInfo(), Record);
556 }
VisitParenTypeLoc(ParenTypeLoc TL)557 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
558 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
559 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
560 }
VisitElaboratedTypeLoc(ElaboratedTypeLoc TL)561 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
562 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
563 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
564 }
VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL)565 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
566 Writer.AddSourceLocation(TL.getNameLoc(), Record);
567 }
VisitDependentNameTypeLoc(DependentNameTypeLoc TL)568 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
569 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
570 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
571 Writer.AddSourceLocation(TL.getNameLoc(), Record);
572 }
VisitDependentTemplateSpecializationTypeLoc(DependentTemplateSpecializationTypeLoc TL)573 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
574 DependentTemplateSpecializationTypeLoc TL) {
575 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
576 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
577 Writer.AddSourceLocation(TL.getNameLoc(), Record);
578 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
579 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
580 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
581 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
582 TL.getArgLoc(I).getLocInfo(), Record);
583 }
VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL)584 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
585 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
586 }
VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL)587 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
588 Writer.AddSourceLocation(TL.getNameLoc(), Record);
589 }
VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL)590 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
591 Record.push_back(TL.hasBaseTypeAsWritten());
592 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
593 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
594 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
595 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
596 }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)597 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
598 Writer.AddSourceLocation(TL.getStarLoc(), Record);
599 }
600
601 //===----------------------------------------------------------------------===//
602 // ASTWriter Implementation
603 //===----------------------------------------------------------------------===//
604
EmitBlockID(unsigned ID,const char * Name,llvm::BitstreamWriter & Stream,ASTWriter::RecordDataImpl & Record)605 static void EmitBlockID(unsigned ID, const char *Name,
606 llvm::BitstreamWriter &Stream,
607 ASTWriter::RecordDataImpl &Record) {
608 Record.clear();
609 Record.push_back(ID);
610 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
611
612 // Emit the block name if present.
613 if (Name == 0 || Name[0] == 0) return;
614 Record.clear();
615 while (*Name)
616 Record.push_back(*Name++);
617 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
618 }
619
EmitRecordID(unsigned ID,const char * Name,llvm::BitstreamWriter & Stream,ASTWriter::RecordDataImpl & Record)620 static void EmitRecordID(unsigned ID, const char *Name,
621 llvm::BitstreamWriter &Stream,
622 ASTWriter::RecordDataImpl &Record) {
623 Record.clear();
624 Record.push_back(ID);
625 while (*Name)
626 Record.push_back(*Name++);
627 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
628 }
629
AddStmtsExprs(llvm::BitstreamWriter & Stream,ASTWriter::RecordDataImpl & Record)630 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
631 ASTWriter::RecordDataImpl &Record) {
632 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
633 RECORD(STMT_STOP);
634 RECORD(STMT_NULL_PTR);
635 RECORD(STMT_NULL);
636 RECORD(STMT_COMPOUND);
637 RECORD(STMT_CASE);
638 RECORD(STMT_DEFAULT);
639 RECORD(STMT_LABEL);
640 RECORD(STMT_IF);
641 RECORD(STMT_SWITCH);
642 RECORD(STMT_WHILE);
643 RECORD(STMT_DO);
644 RECORD(STMT_FOR);
645 RECORD(STMT_GOTO);
646 RECORD(STMT_INDIRECT_GOTO);
647 RECORD(STMT_CONTINUE);
648 RECORD(STMT_BREAK);
649 RECORD(STMT_RETURN);
650 RECORD(STMT_DECL);
651 RECORD(STMT_ASM);
652 RECORD(EXPR_PREDEFINED);
653 RECORD(EXPR_DECL_REF);
654 RECORD(EXPR_INTEGER_LITERAL);
655 RECORD(EXPR_FLOATING_LITERAL);
656 RECORD(EXPR_IMAGINARY_LITERAL);
657 RECORD(EXPR_STRING_LITERAL);
658 RECORD(EXPR_CHARACTER_LITERAL);
659 RECORD(EXPR_PAREN);
660 RECORD(EXPR_UNARY_OPERATOR);
661 RECORD(EXPR_SIZEOF_ALIGN_OF);
662 RECORD(EXPR_ARRAY_SUBSCRIPT);
663 RECORD(EXPR_CALL);
664 RECORD(EXPR_MEMBER);
665 RECORD(EXPR_BINARY_OPERATOR);
666 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
667 RECORD(EXPR_CONDITIONAL_OPERATOR);
668 RECORD(EXPR_IMPLICIT_CAST);
669 RECORD(EXPR_CSTYLE_CAST);
670 RECORD(EXPR_COMPOUND_LITERAL);
671 RECORD(EXPR_EXT_VECTOR_ELEMENT);
672 RECORD(EXPR_INIT_LIST);
673 RECORD(EXPR_DESIGNATED_INIT);
674 RECORD(EXPR_IMPLICIT_VALUE_INIT);
675 RECORD(EXPR_VA_ARG);
676 RECORD(EXPR_ADDR_LABEL);
677 RECORD(EXPR_STMT);
678 RECORD(EXPR_CHOOSE);
679 RECORD(EXPR_GNU_NULL);
680 RECORD(EXPR_SHUFFLE_VECTOR);
681 RECORD(EXPR_BLOCK);
682 RECORD(EXPR_BLOCK_DECL_REF);
683 RECORD(EXPR_GENERIC_SELECTION);
684 RECORD(EXPR_OBJC_STRING_LITERAL);
685 RECORD(EXPR_OBJC_ENCODE);
686 RECORD(EXPR_OBJC_SELECTOR_EXPR);
687 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
688 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
689 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
690 RECORD(EXPR_OBJC_KVC_REF_EXPR);
691 RECORD(EXPR_OBJC_MESSAGE_EXPR);
692 RECORD(STMT_OBJC_FOR_COLLECTION);
693 RECORD(STMT_OBJC_CATCH);
694 RECORD(STMT_OBJC_FINALLY);
695 RECORD(STMT_OBJC_AT_TRY);
696 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
697 RECORD(STMT_OBJC_AT_THROW);
698 RECORD(EXPR_CXX_OPERATOR_CALL);
699 RECORD(EXPR_CXX_CONSTRUCT);
700 RECORD(EXPR_CXX_STATIC_CAST);
701 RECORD(EXPR_CXX_DYNAMIC_CAST);
702 RECORD(EXPR_CXX_REINTERPRET_CAST);
703 RECORD(EXPR_CXX_CONST_CAST);
704 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
705 RECORD(EXPR_CXX_BOOL_LITERAL);
706 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
707 RECORD(EXPR_CXX_TYPEID_EXPR);
708 RECORD(EXPR_CXX_TYPEID_TYPE);
709 RECORD(EXPR_CXX_UUIDOF_EXPR);
710 RECORD(EXPR_CXX_UUIDOF_TYPE);
711 RECORD(EXPR_CXX_THIS);
712 RECORD(EXPR_CXX_THROW);
713 RECORD(EXPR_CXX_DEFAULT_ARG);
714 RECORD(EXPR_CXX_BIND_TEMPORARY);
715 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
716 RECORD(EXPR_CXX_NEW);
717 RECORD(EXPR_CXX_DELETE);
718 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
719 RECORD(EXPR_EXPR_WITH_CLEANUPS);
720 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
721 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
722 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
723 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
724 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
725 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
726 RECORD(EXPR_CXX_NOEXCEPT);
727 RECORD(EXPR_OPAQUE_VALUE);
728 RECORD(EXPR_BINARY_TYPE_TRAIT);
729 RECORD(EXPR_PACK_EXPANSION);
730 RECORD(EXPR_SIZEOF_PACK);
731 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
732 RECORD(EXPR_CUDA_KERNEL_CALL);
733 #undef RECORD
734 }
735
WriteBlockInfoBlock()736 void ASTWriter::WriteBlockInfoBlock() {
737 RecordData Record;
738 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
739
740 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
741 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
742
743 // AST Top-Level Block.
744 BLOCK(AST_BLOCK);
745 RECORD(ORIGINAL_FILE_NAME);
746 RECORD(ORIGINAL_FILE_ID);
747 RECORD(TYPE_OFFSET);
748 RECORD(DECL_OFFSET);
749 RECORD(LANGUAGE_OPTIONS);
750 RECORD(METADATA);
751 RECORD(IDENTIFIER_OFFSET);
752 RECORD(IDENTIFIER_TABLE);
753 RECORD(EXTERNAL_DEFINITIONS);
754 RECORD(SPECIAL_TYPES);
755 RECORD(STATISTICS);
756 RECORD(TENTATIVE_DEFINITIONS);
757 RECORD(UNUSED_FILESCOPED_DECLS);
758 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
759 RECORD(SELECTOR_OFFSETS);
760 RECORD(METHOD_POOL);
761 RECORD(PP_COUNTER_VALUE);
762 RECORD(SOURCE_LOCATION_OFFSETS);
763 RECORD(SOURCE_LOCATION_PRELOADS);
764 RECORD(STAT_CACHE);
765 RECORD(EXT_VECTOR_DECLS);
766 RECORD(VERSION_CONTROL_BRANCH_REVISION);
767 RECORD(MACRO_DEFINITION_OFFSETS);
768 RECORD(CHAINED_METADATA);
769 RECORD(REFERENCED_SELECTOR_POOL);
770 RECORD(TU_UPDATE_LEXICAL);
771 RECORD(REDECLS_UPDATE_LATEST);
772 RECORD(SEMA_DECL_REFS);
773 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
774 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
775 RECORD(DECL_REPLACEMENTS);
776 RECORD(UPDATE_VISIBLE);
777 RECORD(DECL_UPDATE_OFFSETS);
778 RECORD(DECL_UPDATES);
779 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
780 RECORD(DIAG_PRAGMA_MAPPINGS);
781 RECORD(CUDA_SPECIAL_DECL_REFS);
782 RECORD(HEADER_SEARCH_TABLE);
783 RECORD(FP_PRAGMA_OPTIONS);
784 RECORD(OPENCL_EXTENSIONS);
785 RECORD(DELEGATING_CTORS);
786 RECORD(FILE_SOURCE_LOCATION_OFFSETS);
787 RECORD(KNOWN_NAMESPACES);
788
789 // SourceManager Block.
790 BLOCK(SOURCE_MANAGER_BLOCK);
791 RECORD(SM_SLOC_FILE_ENTRY);
792 RECORD(SM_SLOC_BUFFER_ENTRY);
793 RECORD(SM_SLOC_BUFFER_BLOB);
794 RECORD(SM_SLOC_EXPANSION_ENTRY);
795
796 // Preprocessor Block.
797 BLOCK(PREPROCESSOR_BLOCK);
798 RECORD(PP_MACRO_OBJECT_LIKE);
799 RECORD(PP_MACRO_FUNCTION_LIKE);
800 RECORD(PP_TOKEN);
801
802 // Decls and Types block.
803 BLOCK(DECLTYPES_BLOCK);
804 RECORD(TYPE_EXT_QUAL);
805 RECORD(TYPE_COMPLEX);
806 RECORD(TYPE_POINTER);
807 RECORD(TYPE_BLOCK_POINTER);
808 RECORD(TYPE_LVALUE_REFERENCE);
809 RECORD(TYPE_RVALUE_REFERENCE);
810 RECORD(TYPE_MEMBER_POINTER);
811 RECORD(TYPE_CONSTANT_ARRAY);
812 RECORD(TYPE_INCOMPLETE_ARRAY);
813 RECORD(TYPE_VARIABLE_ARRAY);
814 RECORD(TYPE_VECTOR);
815 RECORD(TYPE_EXT_VECTOR);
816 RECORD(TYPE_FUNCTION_PROTO);
817 RECORD(TYPE_FUNCTION_NO_PROTO);
818 RECORD(TYPE_TYPEDEF);
819 RECORD(TYPE_TYPEOF_EXPR);
820 RECORD(TYPE_TYPEOF);
821 RECORD(TYPE_RECORD);
822 RECORD(TYPE_ENUM);
823 RECORD(TYPE_OBJC_INTERFACE);
824 RECORD(TYPE_OBJC_OBJECT);
825 RECORD(TYPE_OBJC_OBJECT_POINTER);
826 RECORD(TYPE_DECLTYPE);
827 RECORD(TYPE_ELABORATED);
828 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
829 RECORD(TYPE_UNRESOLVED_USING);
830 RECORD(TYPE_INJECTED_CLASS_NAME);
831 RECORD(TYPE_OBJC_OBJECT);
832 RECORD(TYPE_TEMPLATE_TYPE_PARM);
833 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
834 RECORD(TYPE_DEPENDENT_NAME);
835 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
836 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
837 RECORD(TYPE_PAREN);
838 RECORD(TYPE_PACK_EXPANSION);
839 RECORD(TYPE_ATTRIBUTED);
840 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
841 RECORD(DECL_TRANSLATION_UNIT);
842 RECORD(DECL_TYPEDEF);
843 RECORD(DECL_ENUM);
844 RECORD(DECL_RECORD);
845 RECORD(DECL_ENUM_CONSTANT);
846 RECORD(DECL_FUNCTION);
847 RECORD(DECL_OBJC_METHOD);
848 RECORD(DECL_OBJC_INTERFACE);
849 RECORD(DECL_OBJC_PROTOCOL);
850 RECORD(DECL_OBJC_IVAR);
851 RECORD(DECL_OBJC_AT_DEFS_FIELD);
852 RECORD(DECL_OBJC_CLASS);
853 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
854 RECORD(DECL_OBJC_CATEGORY);
855 RECORD(DECL_OBJC_CATEGORY_IMPL);
856 RECORD(DECL_OBJC_IMPLEMENTATION);
857 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
858 RECORD(DECL_OBJC_PROPERTY);
859 RECORD(DECL_OBJC_PROPERTY_IMPL);
860 RECORD(DECL_FIELD);
861 RECORD(DECL_VAR);
862 RECORD(DECL_IMPLICIT_PARAM);
863 RECORD(DECL_PARM_VAR);
864 RECORD(DECL_FILE_SCOPE_ASM);
865 RECORD(DECL_BLOCK);
866 RECORD(DECL_CONTEXT_LEXICAL);
867 RECORD(DECL_CONTEXT_VISIBLE);
868 RECORD(DECL_NAMESPACE);
869 RECORD(DECL_NAMESPACE_ALIAS);
870 RECORD(DECL_USING);
871 RECORD(DECL_USING_SHADOW);
872 RECORD(DECL_USING_DIRECTIVE);
873 RECORD(DECL_UNRESOLVED_USING_VALUE);
874 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
875 RECORD(DECL_LINKAGE_SPEC);
876 RECORD(DECL_CXX_RECORD);
877 RECORD(DECL_CXX_METHOD);
878 RECORD(DECL_CXX_CONSTRUCTOR);
879 RECORD(DECL_CXX_DESTRUCTOR);
880 RECORD(DECL_CXX_CONVERSION);
881 RECORD(DECL_ACCESS_SPEC);
882 RECORD(DECL_FRIEND);
883 RECORD(DECL_FRIEND_TEMPLATE);
884 RECORD(DECL_CLASS_TEMPLATE);
885 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
886 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
887 RECORD(DECL_FUNCTION_TEMPLATE);
888 RECORD(DECL_TEMPLATE_TYPE_PARM);
889 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
890 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
891 RECORD(DECL_STATIC_ASSERT);
892 RECORD(DECL_CXX_BASE_SPECIFIERS);
893 RECORD(DECL_INDIRECTFIELD);
894 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
895
896 // Statements and Exprs can occur in the Decls and Types block.
897 AddStmtsExprs(Stream, Record);
898
899 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
900 RECORD(PPD_MACRO_EXPANSION);
901 RECORD(PPD_MACRO_DEFINITION);
902 RECORD(PPD_INCLUSION_DIRECTIVE);
903
904 #undef RECORD
905 #undef BLOCK
906 Stream.ExitBlock();
907 }
908
909 /// \brief Adjusts the given filename to only write out the portion of the
910 /// filename that is not part of the system root directory.
911 ///
912 /// \param Filename the file name to adjust.
913 ///
914 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
915 /// the returned filename will be adjusted by this system root.
916 ///
917 /// \returns either the original filename (if it needs no adjustment) or the
918 /// adjusted filename (which points into the @p Filename parameter).
919 static const char *
adjustFilenameForRelocatablePCH(const char * Filename,const char * isysroot)920 adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
921 assert(Filename && "No file name to adjust?");
922
923 if (!isysroot)
924 return Filename;
925
926 // Verify that the filename and the system root have the same prefix.
927 unsigned Pos = 0;
928 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
929 if (Filename[Pos] != isysroot[Pos])
930 return Filename; // Prefixes don't match.
931
932 // We hit the end of the filename before we hit the end of the system root.
933 if (!Filename[Pos])
934 return Filename;
935
936 // If the file name has a '/' at the current position, skip over the '/'.
937 // We distinguish sysroot-based includes from absolute includes by the
938 // absence of '/' at the beginning of sysroot-based includes.
939 if (Filename[Pos] == '/')
940 ++Pos;
941
942 return Filename + Pos;
943 }
944
945 /// \brief Write the AST metadata (e.g., i686-apple-darwin9).
WriteMetadata(ASTContext & Context,const char * isysroot,const std::string & OutputFile)946 void ASTWriter::WriteMetadata(ASTContext &Context, const char *isysroot,
947 const std::string &OutputFile) {
948 using namespace llvm;
949
950 // Metadata
951 const TargetInfo &Target = Context.Target;
952 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
953 MetaAbbrev->Add(BitCodeAbbrevOp(
954 Chain ? CHAINED_METADATA : METADATA));
955 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major
956 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor
957 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
958 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
959 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
960 // Target triple or chained PCH name
961 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
962 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
963
964 RecordData Record;
965 Record.push_back(Chain ? CHAINED_METADATA : METADATA);
966 Record.push_back(VERSION_MAJOR);
967 Record.push_back(VERSION_MINOR);
968 Record.push_back(CLANG_VERSION_MAJOR);
969 Record.push_back(CLANG_VERSION_MINOR);
970 Record.push_back(isysroot != 0);
971 // FIXME: This writes the absolute path for chained headers.
972 const std::string &BlobStr = Chain ? Chain->getFileName() : Target.getTriple().getTriple();
973 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, BlobStr);
974
975 // Original file name and file ID
976 SourceManager &SM = Context.getSourceManager();
977 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
978 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
979 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME));
980 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
981 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
982
983 llvm::SmallString<128> MainFilePath(MainFile->getName());
984
985 llvm::sys::fs::make_absolute(MainFilePath);
986
987 const char *MainFileNameStr = MainFilePath.c_str();
988 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
989 isysroot);
990 RecordData Record;
991 Record.push_back(ORIGINAL_FILE_NAME);
992 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
993
994 Record.clear();
995 Record.push_back(SM.getMainFileID().getOpaqueValue());
996 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
997 }
998
999 // Original PCH directory
1000 if (!OutputFile.empty() && OutputFile != "-") {
1001 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1002 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1003 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1004 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1005
1006 llvm::SmallString<128> OutputPath(OutputFile);
1007
1008 llvm::sys::fs::make_absolute(OutputPath);
1009 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1010
1011 RecordData Record;
1012 Record.push_back(ORIGINAL_PCH_DIR);
1013 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1014 }
1015
1016 // Repository branch/version information.
1017 BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
1018 RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION));
1019 RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1020 unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
1021 Record.clear();
1022 Record.push_back(VERSION_CONTROL_BRANCH_REVISION);
1023 Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
1024 getClangFullRepositoryVersion());
1025 }
1026
1027 /// \brief Write the LangOptions structure.
WriteLanguageOptions(const LangOptions & LangOpts)1028 void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
1029 RecordData Record;
1030 Record.push_back(LangOpts.Trigraphs);
1031 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
1032 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
1033 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
1034 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
1035 Record.push_back(LangOpts.GNUKeywords); // Allow GNU-extension keywords
1036 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
1037 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
1038 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
1039 Record.push_back(LangOpts.C99); // C99 Support
1040 Record.push_back(LangOpts.C1X); // C1X Support
1041 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
1042 // LangOpts.MSCVersion is ignored because all it does it set a macro, which is
1043 // already saved elsewhere.
1044 Record.push_back(LangOpts.CPlusPlus); // C++ Support
1045 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
1046 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
1047
1048 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
1049 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
1050 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C
1051 // modern abi enabled.
1052 Record.push_back(LangOpts.ObjCNonFragileABI2); // Objective-C enhanced
1053 // modern abi enabled.
1054 Record.push_back(LangOpts.AppleKext); // Apple's kernel extensions ABI
1055 Record.push_back(LangOpts.ObjCDefaultSynthProperties); // Objective-C auto-synthesized
1056 // properties enabled.
1057 Record.push_back(LangOpts.ObjCInferRelatedResultType);
1058 Record.push_back(LangOpts.NoConstantCFStrings); // non cfstring generation enabled..
1059
1060 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
1061 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
1062 Record.push_back(LangOpts.LaxVectorConversions);
1063 Record.push_back(LangOpts.AltiVec);
1064 Record.push_back(LangOpts.Exceptions); // Support exception handling.
1065 Record.push_back(LangOpts.ObjCExceptions);
1066 Record.push_back(LangOpts.CXXExceptions);
1067 Record.push_back(LangOpts.SjLjExceptions);
1068
1069 Record.push_back(LangOpts.MSBitfields); // MS-compatible structure layout
1070 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
1071 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
1072 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
1073
1074 // Whether static initializers are protected by locks.
1075 Record.push_back(LangOpts.ThreadsafeStatics);
1076 Record.push_back(LangOpts.POSIXThreads);
1077 Record.push_back(LangOpts.Blocks); // block extension to C
1078 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
1079 // they are unused.
1080 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
1081 // (modulo the platform support).
1082
1083 Record.push_back(LangOpts.getSignedOverflowBehavior());
1084 Record.push_back(LangOpts.HeinousExtensions);
1085
1086 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
1087 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
1088 // defined.
1089 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
1090 // opposed to __DYNAMIC__).
1091 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
1092
1093 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
1094 // used (instead of C99 semantics).
1095 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
1096 Record.push_back(LangOpts.Deprecated); // Should __DEPRECATED be defined.
1097 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
1098 // be enabled.
1099 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
1100 // unsigned type
1101 Record.push_back(LangOpts.ShortWChar); // force wchar_t to be unsigned short
1102 Record.push_back(LangOpts.ShortEnums); // Should the enum type be equivalent
1103 // to the smallest integer type with
1104 // enough room.
1105 Record.push_back(LangOpts.getGCMode());
1106 Record.push_back(LangOpts.getVisibilityMode());
1107 Record.push_back(LangOpts.getStackProtectorMode());
1108 Record.push_back(LangOpts.InstantiationDepth);
1109 Record.push_back(LangOpts.OpenCL);
1110 Record.push_back(LangOpts.CUDA);
1111 Record.push_back(LangOpts.CatchUndefined);
1112 Record.push_back(LangOpts.DefaultFPContract);
1113 Record.push_back(LangOpts.ElideConstructors);
1114 Record.push_back(LangOpts.SpellChecking);
1115 Record.push_back(LangOpts.MRTD);
1116 Record.push_back(LangOpts.ObjCAutoRefCount);
1117 Record.push_back(LangOpts.ObjCInferRelatedReturnType);
1118 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1119 }
1120
1121 //===----------------------------------------------------------------------===//
1122 // stat cache Serialization
1123 //===----------------------------------------------------------------------===//
1124
1125 namespace {
1126 // Trait used for the on-disk hash table of stat cache results.
1127 class ASTStatCacheTrait {
1128 public:
1129 typedef const char * key_type;
1130 typedef key_type key_type_ref;
1131
1132 typedef struct stat data_type;
1133 typedef const data_type &data_type_ref;
1134
ComputeHash(const char * path)1135 static unsigned ComputeHash(const char *path) {
1136 return llvm::HashString(path);
1137 }
1138
1139 std::pair<unsigned,unsigned>
EmitKeyDataLength(llvm::raw_ostream & Out,const char * path,data_type_ref Data)1140 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
1141 data_type_ref Data) {
1142 unsigned StrLen = strlen(path);
1143 clang::io::Emit16(Out, StrLen);
1144 unsigned DataLen = 4 + 4 + 2 + 8 + 8;
1145 clang::io::Emit8(Out, DataLen);
1146 return std::make_pair(StrLen + 1, DataLen);
1147 }
1148
EmitKey(llvm::raw_ostream & Out,const char * path,unsigned KeyLen)1149 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
1150 Out.write(path, KeyLen);
1151 }
1152
EmitData(llvm::raw_ostream & Out,key_type_ref,data_type_ref Data,unsigned DataLen)1153 void EmitData(llvm::raw_ostream &Out, key_type_ref,
1154 data_type_ref Data, unsigned DataLen) {
1155 using namespace clang::io;
1156 uint64_t Start = Out.tell(); (void)Start;
1157
1158 Emit32(Out, (uint32_t) Data.st_ino);
1159 Emit32(Out, (uint32_t) Data.st_dev);
1160 Emit16(Out, (uint16_t) Data.st_mode);
1161 Emit64(Out, (uint64_t) Data.st_mtime);
1162 Emit64(Out, (uint64_t) Data.st_size);
1163
1164 assert(Out.tell() - Start == DataLen && "Wrong data length");
1165 }
1166 };
1167 } // end anonymous namespace
1168
1169 /// \brief Write the stat() system call cache to the AST file.
WriteStatCache(MemorizeStatCalls & StatCalls)1170 void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
1171 // Build the on-disk hash table containing information about every
1172 // stat() call.
1173 OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator;
1174 unsigned NumStatEntries = 0;
1175 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
1176 StatEnd = StatCalls.end();
1177 Stat != StatEnd; ++Stat, ++NumStatEntries) {
1178 llvm::StringRef Filename = Stat->first();
1179 Generator.insert(Filename.data(), Stat->second);
1180 }
1181
1182 // Create the on-disk hash table in a buffer.
1183 llvm::SmallString<4096> StatCacheData;
1184 uint32_t BucketOffset;
1185 {
1186 llvm::raw_svector_ostream Out(StatCacheData);
1187 // Make sure that no bucket is at offset 0
1188 clang::io::Emit32(Out, 0);
1189 BucketOffset = Generator.Emit(Out);
1190 }
1191
1192 // Create a blob abbreviation
1193 using namespace llvm;
1194 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1195 Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE));
1196 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1197 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1198 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1199 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
1200
1201 // Write the stat cache
1202 RecordData Record;
1203 Record.push_back(STAT_CACHE);
1204 Record.push_back(BucketOffset);
1205 Record.push_back(NumStatEntries);
1206 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
1207 }
1208
1209 //===----------------------------------------------------------------------===//
1210 // Source Manager Serialization
1211 //===----------------------------------------------------------------------===//
1212
1213 /// \brief Create an abbreviation for the SLocEntry that refers to a
1214 /// file.
CreateSLocFileAbbrev(llvm::BitstreamWriter & Stream)1215 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1216 using namespace llvm;
1217 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1218 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1219 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1220 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1221 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1222 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1223 // FileEntry fields.
1224 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1225 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1226 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1227 return Stream.EmitAbbrev(Abbrev);
1228 }
1229
1230 /// \brief Create an abbreviation for the SLocEntry that refers to a
1231 /// buffer.
CreateSLocBufferAbbrev(llvm::BitstreamWriter & Stream)1232 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1233 using namespace llvm;
1234 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1235 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1236 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1237 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1238 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1239 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1240 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1241 return Stream.EmitAbbrev(Abbrev);
1242 }
1243
1244 /// \brief Create an abbreviation for the SLocEntry that refers to a
1245 /// buffer's blob.
CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter & Stream)1246 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1247 using namespace llvm;
1248 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1249 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1250 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1251 return Stream.EmitAbbrev(Abbrev);
1252 }
1253
1254 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1255 /// expansion.
CreateSLocExpansionAbbrev(llvm::BitstreamWriter & Stream)1256 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1257 using namespace llvm;
1258 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1259 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1260 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1261 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1262 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1263 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1264 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1265 return Stream.EmitAbbrev(Abbrev);
1266 }
1267
1268 namespace {
1269 // Trait used for the on-disk hash table of header search information.
1270 class HeaderFileInfoTrait {
1271 ASTWriter &Writer;
1272 HeaderSearch &HS;
1273
1274 public:
HeaderFileInfoTrait(ASTWriter & Writer,HeaderSearch & HS)1275 HeaderFileInfoTrait(ASTWriter &Writer, HeaderSearch &HS)
1276 : Writer(Writer), HS(HS) { }
1277
1278 typedef const char *key_type;
1279 typedef key_type key_type_ref;
1280
1281 typedef HeaderFileInfo data_type;
1282 typedef const data_type &data_type_ref;
1283
ComputeHash(const char * path)1284 static unsigned ComputeHash(const char *path) {
1285 // The hash is based only on the filename portion of the key, so that the
1286 // reader can match based on filenames when symlinking or excess path
1287 // elements ("foo/../", "../") change the form of the name. However,
1288 // complete path is still the key.
1289 return llvm::HashString(llvm::sys::path::filename(path));
1290 }
1291
1292 std::pair<unsigned,unsigned>
EmitKeyDataLength(llvm::raw_ostream & Out,const char * path,data_type_ref Data)1293 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
1294 data_type_ref Data) {
1295 unsigned StrLen = strlen(path);
1296 clang::io::Emit16(Out, StrLen);
1297 unsigned DataLen = 1 + 2 + 4;
1298 clang::io::Emit8(Out, DataLen);
1299 return std::make_pair(StrLen + 1, DataLen);
1300 }
1301
EmitKey(llvm::raw_ostream & Out,const char * path,unsigned KeyLen)1302 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
1303 Out.write(path, KeyLen);
1304 }
1305
EmitData(llvm::raw_ostream & Out,key_type_ref,data_type_ref Data,unsigned DataLen)1306 void EmitData(llvm::raw_ostream &Out, key_type_ref,
1307 data_type_ref Data, unsigned DataLen) {
1308 using namespace clang::io;
1309 uint64_t Start = Out.tell(); (void)Start;
1310
1311 unsigned char Flags = (Data.isImport << 4)
1312 | (Data.isPragmaOnce << 3)
1313 | (Data.DirInfo << 1)
1314 | Data.Resolved;
1315 Emit8(Out, (uint8_t)Flags);
1316 Emit16(Out, (uint16_t) Data.NumIncludes);
1317
1318 if (!Data.ControllingMacro)
1319 Emit32(Out, (uint32_t)Data.ControllingMacroID);
1320 else
1321 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
1322 assert(Out.tell() - Start == DataLen && "Wrong data length");
1323 }
1324 };
1325 } // end anonymous namespace
1326
1327 /// \brief Write the header search block for the list of files that
1328 ///
1329 /// \param HS The header search structure to save.
1330 ///
1331 /// \param Chain Whether we're creating a chained AST file.
WriteHeaderSearch(HeaderSearch & HS,const char * isysroot)1332 void ASTWriter::WriteHeaderSearch(HeaderSearch &HS, const char* isysroot) {
1333 llvm::SmallVector<const FileEntry *, 16> FilesByUID;
1334 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1335
1336 if (FilesByUID.size() > HS.header_file_size())
1337 FilesByUID.resize(HS.header_file_size());
1338
1339 HeaderFileInfoTrait GeneratorTrait(*this, HS);
1340 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1341 llvm::SmallVector<const char *, 4> SavedStrings;
1342 unsigned NumHeaderSearchEntries = 0;
1343 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1344 const FileEntry *File = FilesByUID[UID];
1345 if (!File)
1346 continue;
1347
1348 const HeaderFileInfo &HFI = HS.header_file_begin()[UID];
1349 if (HFI.External && Chain)
1350 continue;
1351
1352 // Turn the file name into an absolute path, if it isn't already.
1353 const char *Filename = File->getName();
1354 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1355
1356 // If we performed any translation on the file name at all, we need to
1357 // save this string, since the generator will refer to it later.
1358 if (Filename != File->getName()) {
1359 Filename = strdup(Filename);
1360 SavedStrings.push_back(Filename);
1361 }
1362
1363 Generator.insert(Filename, HFI, GeneratorTrait);
1364 ++NumHeaderSearchEntries;
1365 }
1366
1367 // Create the on-disk hash table in a buffer.
1368 llvm::SmallString<4096> TableData;
1369 uint32_t BucketOffset;
1370 {
1371 llvm::raw_svector_ostream Out(TableData);
1372 // Make sure that no bucket is at offset 0
1373 clang::io::Emit32(Out, 0);
1374 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1375 }
1376
1377 // Create a blob abbreviation
1378 using namespace llvm;
1379 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1380 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1381 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1382 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1383 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1384 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1385
1386 // Write the stat cache
1387 RecordData Record;
1388 Record.push_back(HEADER_SEARCH_TABLE);
1389 Record.push_back(BucketOffset);
1390 Record.push_back(NumHeaderSearchEntries);
1391 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1392
1393 // Free all of the strings we had to duplicate.
1394 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1395 free((void*)SavedStrings[I]);
1396 }
1397
1398 /// \brief Writes the block containing the serialized form of the
1399 /// source manager.
1400 ///
1401 /// TODO: We should probably use an on-disk hash table (stored in a
1402 /// blob), indexed based on the file name, so that we only create
1403 /// entries for files that we actually need. In the common case (no
1404 /// errors), we probably won't have to create file entries for any of
1405 /// the files in the AST.
WriteSourceManagerBlock(SourceManager & SourceMgr,const Preprocessor & PP,const char * isysroot)1406 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1407 const Preprocessor &PP,
1408 const char *isysroot) {
1409 RecordData Record;
1410
1411 // Enter the source manager block.
1412 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1413
1414 // Abbreviations for the various kinds of source-location entries.
1415 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1416 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1417 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1418 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1419
1420 // Write out the source location entry table. We skip the first
1421 // entry, which is always the same dummy entry.
1422 std::vector<uint32_t> SLocEntryOffsets;
1423 // Write out the offsets of only source location file entries.
1424 // We will go through them in ASTReader::validateFileEntries().
1425 std::vector<uint32_t> SLocFileEntryOffsets;
1426 RecordData PreloadSLocs;
1427 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1428 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1429 I != N; ++I) {
1430 // Get this source location entry.
1431 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1432
1433 // Record the offset of this source-location entry.
1434 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1435
1436 // Figure out which record code to use.
1437 unsigned Code;
1438 if (SLoc->isFile()) {
1439 if (SLoc->getFile().getContentCache()->OrigEntry) {
1440 Code = SM_SLOC_FILE_ENTRY;
1441 SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo());
1442 } else
1443 Code = SM_SLOC_BUFFER_ENTRY;
1444 } else
1445 Code = SM_SLOC_EXPANSION_ENTRY;
1446 Record.clear();
1447 Record.push_back(Code);
1448
1449 // Starting offset of this entry within this module, so skip the dummy.
1450 Record.push_back(SLoc->getOffset() - 2);
1451 if (SLoc->isFile()) {
1452 const SrcMgr::FileInfo &File = SLoc->getFile();
1453 Record.push_back(File.getIncludeLoc().getRawEncoding());
1454 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1455 Record.push_back(File.hasLineDirectives());
1456
1457 const SrcMgr::ContentCache *Content = File.getContentCache();
1458 if (Content->OrigEntry) {
1459 assert(Content->OrigEntry == Content->ContentsEntry &&
1460 "Writing to AST an overriden file is not supported");
1461
1462 // The source location entry is a file. The blob associated
1463 // with this entry is the file name.
1464
1465 // Emit size/modification time for this file.
1466 Record.push_back(Content->OrigEntry->getSize());
1467 Record.push_back(Content->OrigEntry->getModificationTime());
1468
1469 // Turn the file name into an absolute path, if it isn't already.
1470 const char *Filename = Content->OrigEntry->getName();
1471 llvm::SmallString<128> FilePath(Filename);
1472
1473 // Ask the file manager to fixup the relative path for us. This will
1474 // honor the working directory.
1475 SourceMgr.getFileManager().FixupRelativePath(FilePath);
1476
1477 // FIXME: This call to make_absolute shouldn't be necessary, the
1478 // call to FixupRelativePath should always return an absolute path.
1479 llvm::sys::fs::make_absolute(FilePath);
1480 Filename = FilePath.c_str();
1481
1482 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1483 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
1484 } else {
1485 // The source location entry is a buffer. The blob associated
1486 // with this entry contains the contents of the buffer.
1487
1488 // We add one to the size so that we capture the trailing NULL
1489 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1490 // the reader side).
1491 const llvm::MemoryBuffer *Buffer
1492 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1493 const char *Name = Buffer->getBufferIdentifier();
1494 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1495 llvm::StringRef(Name, strlen(Name) + 1));
1496 Record.clear();
1497 Record.push_back(SM_SLOC_BUFFER_BLOB);
1498 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1499 llvm::StringRef(Buffer->getBufferStart(),
1500 Buffer->getBufferSize() + 1));
1501
1502 if (strcmp(Name, "<built-in>") == 0) {
1503 PreloadSLocs.push_back(SLocEntryOffsets.size());
1504 }
1505 }
1506 } else {
1507 // The source location entry is a macro expansion.
1508 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
1509 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
1510 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
1511 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
1512
1513 // Compute the token length for this macro expansion.
1514 unsigned NextOffset = SourceMgr.getNextLocalOffset();
1515 if (I + 1 != N)
1516 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
1517 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1518 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
1519 }
1520 }
1521
1522 Stream.ExitBlock();
1523
1524 if (SLocEntryOffsets.empty())
1525 return;
1526
1527 // Write the source-location offsets table into the AST block. This
1528 // table is used for lazily loading source-location information.
1529 using namespace llvm;
1530 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1531 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1532 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1533 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
1534 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1535 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1536
1537 Record.clear();
1538 Record.push_back(SOURCE_LOCATION_OFFSETS);
1539 Record.push_back(SLocEntryOffsets.size());
1540 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
1541 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
1542
1543 // If we have module dependencies, write the mapping from source locations to
1544 // their containing modules, so that the reader can build the remapping.
1545 if (Chain) {
1546 // The map consists solely of a blob with the following format:
1547 // *(offset:i32 len:i16 name:len*i8)
1548 // Sorted by offset.
1549 typedef std::pair<uint32_t, llvm::StringRef> ModuleOffset;
1550 llvm::SmallVector<ModuleOffset, 16> Modules;
1551 Modules.reserve(Chain->Modules.size());
1552 for (llvm::StringMap<ASTReader::PerFileData*>::const_iterator
1553 I = Chain->Modules.begin(), E = Chain->Modules.end();
1554 I != E; ++I) {
1555 Modules.push_back(ModuleOffset(I->getValue()->SLocEntryBaseOffset,
1556 I->getKey()));
1557 }
1558 std::sort(Modules.begin(), Modules.end());
1559
1560 Abbrev = new BitCodeAbbrev();
1561 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_MAP));
1562 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1563 unsigned SLocMapAbbrev = Stream.EmitAbbrev(Abbrev);
1564 llvm::SmallString<2048> Buffer;
1565 {
1566 llvm::raw_svector_ostream Out(Buffer);
1567 for (llvm::SmallVector<ModuleOffset, 16>::iterator I = Modules.begin(),
1568 E = Modules.end();
1569 I != E; ++I) {
1570 io::Emit32(Out, I->first);
1571 io::Emit16(Out, I->second.size());
1572 Out.write(I->second.data(), I->second.size());
1573 }
1574 }
1575 Record.clear();
1576 Record.push_back(SOURCE_LOCATION_MAP);
1577 Stream.EmitRecordWithBlob(SLocMapAbbrev, Record,
1578 Buffer.data(), Buffer.size());
1579 }
1580
1581 Abbrev = new BitCodeAbbrev();
1582 Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS));
1583 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1584 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1585 unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1586
1587 Record.clear();
1588 Record.push_back(FILE_SOURCE_LOCATION_OFFSETS);
1589 Record.push_back(SLocFileEntryOffsets.size());
1590 Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record,
1591 data(SLocFileEntryOffsets));
1592
1593 // Write the source location entry preloads array, telling the AST
1594 // reader which source locations entries it should load eagerly.
1595 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1596
1597 // Write the line table. It depends on remapping working, so it must come
1598 // after the source location offsets.
1599 if (SourceMgr.hasLineTable()) {
1600 LineTableInfo &LineTable = SourceMgr.getLineTable();
1601
1602 Record.clear();
1603 // Emit the file names
1604 Record.push_back(LineTable.getNumFilenames());
1605 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1606 // Emit the file name
1607 const char *Filename = LineTable.getFilename(I);
1608 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1609 unsigned FilenameLen = Filename? strlen(Filename) : 0;
1610 Record.push_back(FilenameLen);
1611 if (FilenameLen)
1612 Record.insert(Record.end(), Filename, Filename + FilenameLen);
1613 }
1614
1615 // Emit the line entries
1616 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1617 L != LEnd; ++L) {
1618 // Only emit entries for local files.
1619 if (L->first < 0)
1620 continue;
1621
1622 // Emit the file ID
1623 Record.push_back(L->first);
1624
1625 // Emit the line entries
1626 Record.push_back(L->second.size());
1627 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1628 LEEnd = L->second.end();
1629 LE != LEEnd; ++LE) {
1630 Record.push_back(LE->FileOffset);
1631 Record.push_back(LE->LineNo);
1632 Record.push_back(LE->FilenameID);
1633 Record.push_back((unsigned)LE->FileKind);
1634 Record.push_back(LE->IncludeOffset);
1635 }
1636 }
1637 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
1638 }
1639 }
1640
1641 //===----------------------------------------------------------------------===//
1642 // Preprocessor Serialization
1643 //===----------------------------------------------------------------------===//
1644
compareMacroDefinitions(const void * XPtr,const void * YPtr)1645 static int compareMacroDefinitions(const void *XPtr, const void *YPtr) {
1646 const std::pair<const IdentifierInfo *, MacroInfo *> &X =
1647 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr;
1648 const std::pair<const IdentifierInfo *, MacroInfo *> &Y =
1649 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr;
1650 return X.first->getName().compare(Y.first->getName());
1651 }
1652
1653 /// \brief Writes the block containing the serialized form of the
1654 /// preprocessor.
1655 ///
WritePreprocessor(const Preprocessor & PP)1656 void ASTWriter::WritePreprocessor(const Preprocessor &PP) {
1657 RecordData Record;
1658
1659 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1660 if (PP.getCounterValue() != 0) {
1661 Record.push_back(PP.getCounterValue());
1662 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1663 Record.clear();
1664 }
1665
1666 // Enter the preprocessor block.
1667 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1668
1669 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1670 // FIXME: use diagnostics subsystem for localization etc.
1671 if (PP.SawDateOrTime())
1672 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1673
1674
1675 // Loop over all the macro definitions that are live at the end of the file,
1676 // emitting each to the PP section.
1677 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1678
1679 // Construct the list of macro definitions that need to be serialized.
1680 llvm::SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2>
1681 MacrosToEmit;
1682 llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen;
1683 for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0),
1684 E = PP.macro_end(Chain == 0);
1685 I != E; ++I) {
1686 MacroDefinitionsSeen.insert(I->first);
1687 MacrosToEmit.push_back(std::make_pair(I->first, I->second));
1688 }
1689
1690 // Sort the set of macro definitions that need to be serialized by the
1691 // name of the macro, to provide a stable ordering.
1692 llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(),
1693 &compareMacroDefinitions);
1694
1695 // Resolve any identifiers that defined macros at the time they were
1696 // deserialized, adding them to the list of macros to emit (if appropriate).
1697 for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) {
1698 IdentifierInfo *Name
1699 = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]);
1700 if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name))
1701 MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name)));
1702 }
1703
1704 for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) {
1705 const IdentifierInfo *Name = MacrosToEmit[I].first;
1706 MacroInfo *MI = MacrosToEmit[I].second;
1707 if (!MI)
1708 continue;
1709
1710 // Don't emit builtin macros like __LINE__ to the AST file unless they have
1711 // been redefined by the header (in which case they are not isBuiltinMacro).
1712 // Also skip macros from a AST file if we're chaining.
1713
1714 // FIXME: There is a (probably minor) optimization we could do here, if
1715 // the macro comes from the original PCH but the identifier comes from a
1716 // chained PCH, by storing the offset into the original PCH rather than
1717 // writing the macro definition a second time.
1718 if (MI->isBuiltinMacro() ||
1719 (Chain && Name->isFromAST() && MI->isFromAST()))
1720 continue;
1721
1722 AddIdentifierRef(Name, Record);
1723 MacroOffsets[Name] = Stream.GetCurrentBitNo();
1724 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1725 Record.push_back(MI->isUsed());
1726
1727 unsigned Code;
1728 if (MI->isObjectLike()) {
1729 Code = PP_MACRO_OBJECT_LIKE;
1730 } else {
1731 Code = PP_MACRO_FUNCTION_LIKE;
1732
1733 Record.push_back(MI->isC99Varargs());
1734 Record.push_back(MI->isGNUVarargs());
1735 Record.push_back(MI->getNumArgs());
1736 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1737 I != E; ++I)
1738 AddIdentifierRef(*I, Record);
1739 }
1740
1741 // If we have a detailed preprocessing record, record the macro definition
1742 // ID that corresponds to this macro.
1743 if (PPRec)
1744 Record.push_back(getMacroDefinitionID(PPRec->findMacroDefinition(MI)));
1745
1746 Stream.EmitRecord(Code, Record);
1747 Record.clear();
1748
1749 // Emit the tokens array.
1750 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1751 // Note that we know that the preprocessor does not have any annotation
1752 // tokens in it because they are created by the parser, and thus can't be
1753 // in a macro definition.
1754 const Token &Tok = MI->getReplacementToken(TokNo);
1755
1756 Record.push_back(Tok.getLocation().getRawEncoding());
1757 Record.push_back(Tok.getLength());
1758
1759 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1760 // it is needed.
1761 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
1762 // FIXME: Should translate token kind to a stable encoding.
1763 Record.push_back(Tok.getKind());
1764 // FIXME: Should translate token flags to a stable encoding.
1765 Record.push_back(Tok.getFlags());
1766
1767 Stream.EmitRecord(PP_TOKEN, Record);
1768 Record.clear();
1769 }
1770 ++NumMacros;
1771 }
1772 Stream.ExitBlock();
1773
1774 if (PPRec)
1775 WritePreprocessorDetail(*PPRec);
1776 }
1777
WritePreprocessorDetail(PreprocessingRecord & PPRec)1778 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
1779 if (PPRec.begin(Chain) == PPRec.end(Chain))
1780 return;
1781
1782 // Enter the preprocessor block.
1783 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
1784
1785 // If the preprocessor has a preprocessing record, emit it.
1786 unsigned NumPreprocessingRecords = 0;
1787 using namespace llvm;
1788
1789 // Set up the abbreviation for
1790 unsigned InclusionAbbrev = 0;
1791 {
1792 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1793 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
1794 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1795 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // start location
1796 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // end location
1797 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
1798 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
1799 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
1800 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1801 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
1802 }
1803
1804 unsigned IndexBase = Chain ? PPRec.getNumPreallocatedEntities() : 0;
1805 RecordData Record;
1806 for (PreprocessingRecord::iterator E = PPRec.begin(Chain),
1807 EEnd = PPRec.end(Chain);
1808 E != EEnd; ++E) {
1809 Record.clear();
1810
1811 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
1812 // Record this macro definition's location.
1813 MacroID ID = getMacroDefinitionID(MD);
1814
1815 // Don't write the macro definition if it is from another AST file.
1816 if (ID < FirstMacroID)
1817 continue;
1818
1819 // Notify the serialization listener that we're serializing this entity.
1820 if (SerializationListener)
1821 SerializationListener->SerializedPreprocessedEntity(*E,
1822 Stream.GetCurrentBitNo());
1823
1824 unsigned Position = ID - FirstMacroID;
1825 if (Position != MacroDefinitionOffsets.size()) {
1826 if (Position > MacroDefinitionOffsets.size())
1827 MacroDefinitionOffsets.resize(Position + 1);
1828
1829 MacroDefinitionOffsets[Position] = Stream.GetCurrentBitNo();
1830 } else
1831 MacroDefinitionOffsets.push_back(Stream.GetCurrentBitNo());
1832
1833 Record.push_back(IndexBase + NumPreprocessingRecords++);
1834 Record.push_back(ID);
1835 AddSourceLocation(MD->getSourceRange().getBegin(), Record);
1836 AddSourceLocation(MD->getSourceRange().getEnd(), Record);
1837 AddIdentifierRef(MD->getName(), Record);
1838 AddSourceLocation(MD->getLocation(), Record);
1839 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
1840 continue;
1841 }
1842
1843 // Notify the serialization listener that we're serializing this entity.
1844 if (SerializationListener)
1845 SerializationListener->SerializedPreprocessedEntity(*E,
1846 Stream.GetCurrentBitNo());
1847
1848 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
1849 Record.push_back(IndexBase + NumPreprocessingRecords++);
1850 AddSourceLocation(ME->getSourceRange().getBegin(), Record);
1851 AddSourceLocation(ME->getSourceRange().getEnd(), Record);
1852 AddIdentifierRef(ME->getName(), Record);
1853 Record.push_back(getMacroDefinitionID(ME->getDefinition()));
1854 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
1855 continue;
1856 }
1857
1858 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
1859 Record.push_back(PPD_INCLUSION_DIRECTIVE);
1860 Record.push_back(IndexBase + NumPreprocessingRecords++);
1861 AddSourceLocation(ID->getSourceRange().getBegin(), Record);
1862 AddSourceLocation(ID->getSourceRange().getEnd(), Record);
1863 Record.push_back(ID->getFileName().size());
1864 Record.push_back(ID->wasInQuotes());
1865 Record.push_back(static_cast<unsigned>(ID->getKind()));
1866 llvm::SmallString<64> Buffer;
1867 Buffer += ID->getFileName();
1868 Buffer += ID->getFile()->getName();
1869 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
1870 continue;
1871 }
1872
1873 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
1874 }
1875 Stream.ExitBlock();
1876
1877 // Write the offsets table for the preprocessing record.
1878 if (NumPreprocessingRecords > 0) {
1879 // Write the offsets table for identifier IDs.
1880 using namespace llvm;
1881 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1882 Abbrev->Add(BitCodeAbbrevOp(MACRO_DEFINITION_OFFSETS));
1883 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of records
1884 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macro defs
1885 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1886 unsigned MacroDefOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1887
1888 Record.clear();
1889 Record.push_back(MACRO_DEFINITION_OFFSETS);
1890 Record.push_back(NumPreprocessingRecords);
1891 Record.push_back(MacroDefinitionOffsets.size());
1892 Stream.EmitRecordWithBlob(MacroDefOffsetAbbrev, Record,
1893 data(MacroDefinitionOffsets));
1894 }
1895 }
1896
WritePragmaDiagnosticMappings(const Diagnostic & Diag)1897 void ASTWriter::WritePragmaDiagnosticMappings(const Diagnostic &Diag) {
1898 RecordData Record;
1899 for (Diagnostic::DiagStatePointsTy::const_iterator
1900 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
1901 I != E; ++I) {
1902 const Diagnostic::DiagStatePoint &point = *I;
1903 if (point.Loc.isInvalid())
1904 continue;
1905
1906 Record.push_back(point.Loc.getRawEncoding());
1907 for (Diagnostic::DiagState::iterator
1908 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
1909 unsigned diag = I->first, map = I->second;
1910 if (map & 0x10) { // mapping from a diagnostic pragma.
1911 Record.push_back(diag);
1912 Record.push_back(map & 0x7);
1913 }
1914 }
1915 Record.push_back(-1); // mark the end of the diag/map pairs for this
1916 // location.
1917 }
1918
1919 if (!Record.empty())
1920 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
1921 }
1922
WriteCXXBaseSpecifiersOffsets()1923 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
1924 if (CXXBaseSpecifiersOffsets.empty())
1925 return;
1926
1927 RecordData Record;
1928
1929 // Create a blob abbreviation for the C++ base specifiers offsets.
1930 using namespace llvm;
1931
1932 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1933 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
1934 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
1935 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1936 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1937
1938 // Write the selector offsets table.
1939 Record.clear();
1940 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
1941 Record.push_back(CXXBaseSpecifiersOffsets.size());
1942 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
1943 data(CXXBaseSpecifiersOffsets));
1944 }
1945
1946 //===----------------------------------------------------------------------===//
1947 // Type Serialization
1948 //===----------------------------------------------------------------------===//
1949
1950 /// \brief Write the representation of a type to the AST stream.
WriteType(QualType T)1951 void ASTWriter::WriteType(QualType T) {
1952 TypeIdx &Idx = TypeIdxs[T];
1953 if (Idx.getIndex() == 0) // we haven't seen this type before.
1954 Idx = TypeIdx(NextTypeID++);
1955
1956 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
1957
1958 // Record the offset for this type.
1959 unsigned Index = Idx.getIndex() - FirstTypeID;
1960 if (TypeOffsets.size() == Index)
1961 TypeOffsets.push_back(Stream.GetCurrentBitNo());
1962 else if (TypeOffsets.size() < Index) {
1963 TypeOffsets.resize(Index + 1);
1964 TypeOffsets[Index] = Stream.GetCurrentBitNo();
1965 }
1966
1967 RecordData Record;
1968
1969 // Emit the type's representation.
1970 ASTTypeWriter W(*this, Record);
1971
1972 if (T.hasLocalNonFastQualifiers()) {
1973 Qualifiers Qs = T.getLocalQualifiers();
1974 AddTypeRef(T.getLocalUnqualifiedType(), Record);
1975 Record.push_back(Qs.getAsOpaqueValue());
1976 W.Code = TYPE_EXT_QUAL;
1977 } else {
1978 switch (T->getTypeClass()) {
1979 // For all of the concrete, non-dependent types, call the
1980 // appropriate visitor function.
1981 #define TYPE(Class, Base) \
1982 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1983 #define ABSTRACT_TYPE(Class, Base)
1984 #include "clang/AST/TypeNodes.def"
1985 }
1986 }
1987
1988 // Emit the serialized record.
1989 Stream.EmitRecord(W.Code, Record);
1990
1991 // Flush any expressions that were written as part of this type.
1992 FlushStmts();
1993 }
1994
1995 //===----------------------------------------------------------------------===//
1996 // Declaration Serialization
1997 //===----------------------------------------------------------------------===//
1998
1999 /// \brief Write the block containing all of the declaration IDs
2000 /// lexically declared within the given DeclContext.
2001 ///
2002 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2003 /// bistream, or 0 if no block was written.
WriteDeclContextLexicalBlock(ASTContext & Context,DeclContext * DC)2004 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2005 DeclContext *DC) {
2006 if (DC->decls_empty())
2007 return 0;
2008
2009 uint64_t Offset = Stream.GetCurrentBitNo();
2010 RecordData Record;
2011 Record.push_back(DECL_CONTEXT_LEXICAL);
2012 llvm::SmallVector<KindDeclIDPair, 64> Decls;
2013 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
2014 D != DEnd; ++D)
2015 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
2016
2017 ++NumLexicalDeclContexts;
2018 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
2019 return Offset;
2020 }
2021
WriteTypeDeclOffsets()2022 void ASTWriter::WriteTypeDeclOffsets() {
2023 using namespace llvm;
2024 RecordData Record;
2025
2026 // Write the type offsets array
2027 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2028 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2029 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2030 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2031 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2032 Record.clear();
2033 Record.push_back(TYPE_OFFSET);
2034 Record.push_back(TypeOffsets.size());
2035 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
2036
2037 // Write the declaration offsets array
2038 Abbrev = new BitCodeAbbrev();
2039 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2040 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2041 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2042 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2043 Record.clear();
2044 Record.push_back(DECL_OFFSET);
2045 Record.push_back(DeclOffsets.size());
2046 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
2047 }
2048
2049 //===----------------------------------------------------------------------===//
2050 // Global Method Pool and Selector Serialization
2051 //===----------------------------------------------------------------------===//
2052
2053 namespace {
2054 // Trait used for the on-disk hash table used in the method pool.
2055 class ASTMethodPoolTrait {
2056 ASTWriter &Writer;
2057
2058 public:
2059 typedef Selector key_type;
2060 typedef key_type key_type_ref;
2061
2062 struct data_type {
2063 SelectorID ID;
2064 ObjCMethodList Instance, Factory;
2065 };
2066 typedef const data_type& data_type_ref;
2067
ASTMethodPoolTrait(ASTWriter & Writer)2068 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2069
ComputeHash(Selector Sel)2070 static unsigned ComputeHash(Selector Sel) {
2071 return serialization::ComputeHash(Sel);
2072 }
2073
2074 std::pair<unsigned,unsigned>
EmitKeyDataLength(llvm::raw_ostream & Out,Selector Sel,data_type_ref Methods)2075 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
2076 data_type_ref Methods) {
2077 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2078 clang::io::Emit16(Out, KeyLen);
2079 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2080 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2081 Method = Method->Next)
2082 if (Method->Method)
2083 DataLen += 4;
2084 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2085 Method = Method->Next)
2086 if (Method->Method)
2087 DataLen += 4;
2088 clang::io::Emit16(Out, DataLen);
2089 return std::make_pair(KeyLen, DataLen);
2090 }
2091
EmitKey(llvm::raw_ostream & Out,Selector Sel,unsigned)2092 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
2093 uint64_t Start = Out.tell();
2094 assert((Start >> 32) == 0 && "Selector key offset too large");
2095 Writer.SetSelectorOffset(Sel, Start);
2096 unsigned N = Sel.getNumArgs();
2097 clang::io::Emit16(Out, N);
2098 if (N == 0)
2099 N = 1;
2100 for (unsigned I = 0; I != N; ++I)
2101 clang::io::Emit32(Out,
2102 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2103 }
2104
EmitData(llvm::raw_ostream & Out,key_type_ref,data_type_ref Methods,unsigned DataLen)2105 void EmitData(llvm::raw_ostream& Out, key_type_ref,
2106 data_type_ref Methods, unsigned DataLen) {
2107 uint64_t Start = Out.tell(); (void)Start;
2108 clang::io::Emit32(Out, Methods.ID);
2109 unsigned NumInstanceMethods = 0;
2110 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2111 Method = Method->Next)
2112 if (Method->Method)
2113 ++NumInstanceMethods;
2114
2115 unsigned NumFactoryMethods = 0;
2116 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2117 Method = Method->Next)
2118 if (Method->Method)
2119 ++NumFactoryMethods;
2120
2121 clang::io::Emit16(Out, NumInstanceMethods);
2122 clang::io::Emit16(Out, NumFactoryMethods);
2123 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2124 Method = Method->Next)
2125 if (Method->Method)
2126 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2127 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2128 Method = Method->Next)
2129 if (Method->Method)
2130 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2131
2132 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2133 }
2134 };
2135 } // end anonymous namespace
2136
2137 /// \brief Write ObjC data: selectors and the method pool.
2138 ///
2139 /// The method pool contains both instance and factory methods, stored
2140 /// in an on-disk hash table indexed by the selector. The hash table also
2141 /// contains an empty entry for every other selector known to Sema.
WriteSelectors(Sema & SemaRef)2142 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2143 using namespace llvm;
2144
2145 // Do we have to do anything at all?
2146 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2147 return;
2148 unsigned NumTableEntries = 0;
2149 // Create and write out the blob that contains selectors and the method pool.
2150 {
2151 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2152 ASTMethodPoolTrait Trait(*this);
2153
2154 // Create the on-disk hash table representation. We walk through every
2155 // selector we've seen and look it up in the method pool.
2156 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2157 for (llvm::DenseMap<Selector, SelectorID>::iterator
2158 I = SelectorIDs.begin(), E = SelectorIDs.end();
2159 I != E; ++I) {
2160 Selector S = I->first;
2161 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2162 ASTMethodPoolTrait::data_type Data = {
2163 I->second,
2164 ObjCMethodList(),
2165 ObjCMethodList()
2166 };
2167 if (F != SemaRef.MethodPool.end()) {
2168 Data.Instance = F->second.first;
2169 Data.Factory = F->second.second;
2170 }
2171 // Only write this selector if it's not in an existing AST or something
2172 // changed.
2173 if (Chain && I->second < FirstSelectorID) {
2174 // Selector already exists. Did it change?
2175 bool changed = false;
2176 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2177 M = M->Next) {
2178 if (M->Method->getPCHLevel() == 0)
2179 changed = true;
2180 }
2181 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2182 M = M->Next) {
2183 if (M->Method->getPCHLevel() == 0)
2184 changed = true;
2185 }
2186 if (!changed)
2187 continue;
2188 } else if (Data.Instance.Method || Data.Factory.Method) {
2189 // A new method pool entry.
2190 ++NumTableEntries;
2191 }
2192 Generator.insert(S, Data, Trait);
2193 }
2194
2195 // Create the on-disk hash table in a buffer.
2196 llvm::SmallString<4096> MethodPool;
2197 uint32_t BucketOffset;
2198 {
2199 ASTMethodPoolTrait Trait(*this);
2200 llvm::raw_svector_ostream Out(MethodPool);
2201 // Make sure that no bucket is at offset 0
2202 clang::io::Emit32(Out, 0);
2203 BucketOffset = Generator.Emit(Out, Trait);
2204 }
2205
2206 // Create a blob abbreviation
2207 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2208 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2209 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2210 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2211 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2212 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2213
2214 // Write the method pool
2215 RecordData Record;
2216 Record.push_back(METHOD_POOL);
2217 Record.push_back(BucketOffset);
2218 Record.push_back(NumTableEntries);
2219 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
2220
2221 // Create a blob abbreviation for the selector table offsets.
2222 Abbrev = new BitCodeAbbrev();
2223 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
2224 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2225 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2226 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2227
2228 // Write the selector offsets table.
2229 Record.clear();
2230 Record.push_back(SELECTOR_OFFSETS);
2231 Record.push_back(SelectorOffsets.size());
2232 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
2233 data(SelectorOffsets));
2234 }
2235 }
2236
2237 /// \brief Write the selectors referenced in @selector expression into AST file.
WriteReferencedSelectorsPool(Sema & SemaRef)2238 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
2239 using namespace llvm;
2240 if (SemaRef.ReferencedSelectors.empty())
2241 return;
2242
2243 RecordData Record;
2244
2245 // Note: this writes out all references even for a dependent AST. But it is
2246 // very tricky to fix, and given that @selector shouldn't really appear in
2247 // headers, probably not worth it. It's not a correctness issue.
2248 for (DenseMap<Selector, SourceLocation>::iterator S =
2249 SemaRef.ReferencedSelectors.begin(),
2250 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2251 Selector Sel = (*S).first;
2252 SourceLocation Loc = (*S).second;
2253 AddSelectorRef(Sel, Record);
2254 AddSourceLocation(Loc, Record);
2255 }
2256 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
2257 }
2258
2259 //===----------------------------------------------------------------------===//
2260 // Identifier Table Serialization
2261 //===----------------------------------------------------------------------===//
2262
2263 namespace {
2264 class ASTIdentifierTableTrait {
2265 ASTWriter &Writer;
2266 Preprocessor &PP;
2267
2268 /// \brief Determines whether this is an "interesting" identifier
2269 /// that needs a full IdentifierInfo structure written into the hash
2270 /// table.
isInterestingIdentifier(const IdentifierInfo * II)2271 static bool isInterestingIdentifier(const IdentifierInfo *II) {
2272 return II->isPoisoned() ||
2273 II->isExtensionToken() ||
2274 II->hasMacroDefinition() ||
2275 II->getObjCOrBuiltinID() ||
2276 II->getFETokenInfo<void>();
2277 }
2278
2279 public:
2280 typedef const IdentifierInfo* key_type;
2281 typedef key_type key_type_ref;
2282
2283 typedef IdentID data_type;
2284 typedef data_type data_type_ref;
2285
ASTIdentifierTableTrait(ASTWriter & Writer,Preprocessor & PP)2286 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP)
2287 : Writer(Writer), PP(PP) { }
2288
ComputeHash(const IdentifierInfo * II)2289 static unsigned ComputeHash(const IdentifierInfo* II) {
2290 return llvm::HashString(II->getName());
2291 }
2292
2293 std::pair<unsigned,unsigned>
EmitKeyDataLength(llvm::raw_ostream & Out,const IdentifierInfo * II,IdentID ID)2294 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
2295 IdentID ID) {
2296 unsigned KeyLen = II->getLength() + 1;
2297 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
2298 if (isInterestingIdentifier(II)) {
2299 DataLen += 2; // 2 bytes for builtin ID, flags
2300 if (II->hasMacroDefinition() &&
2301 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
2302 DataLen += 4;
2303 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
2304 DEnd = IdentifierResolver::end();
2305 D != DEnd; ++D)
2306 DataLen += sizeof(DeclID);
2307 }
2308 clang::io::Emit16(Out, DataLen);
2309 // We emit the key length after the data length so that every
2310 // string is preceded by a 16-bit length. This matches the PTH
2311 // format for storing identifiers.
2312 clang::io::Emit16(Out, KeyLen);
2313 return std::make_pair(KeyLen, DataLen);
2314 }
2315
EmitKey(llvm::raw_ostream & Out,const IdentifierInfo * II,unsigned KeyLen)2316 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
2317 unsigned KeyLen) {
2318 // Record the location of the key data. This is used when generating
2319 // the mapping from persistent IDs to strings.
2320 Writer.SetIdentifierOffset(II, Out.tell());
2321 Out.write(II->getNameStart(), KeyLen);
2322 }
2323
EmitData(llvm::raw_ostream & Out,const IdentifierInfo * II,IdentID ID,unsigned)2324 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
2325 IdentID ID, unsigned) {
2326 if (!isInterestingIdentifier(II)) {
2327 clang::io::Emit32(Out, ID << 1);
2328 return;
2329 }
2330
2331 clang::io::Emit32(Out, (ID << 1) | 0x01);
2332 uint32_t Bits = 0;
2333 bool hasMacroDefinition =
2334 II->hasMacroDefinition() &&
2335 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
2336 Bits = (uint32_t)II->getObjCOrBuiltinID();
2337 Bits = (Bits << 1) | unsigned(hasMacroDefinition);
2338 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
2339 Bits = (Bits << 1) | unsigned(II->isPoisoned());
2340 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
2341 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
2342 clang::io::Emit16(Out, Bits);
2343
2344 if (hasMacroDefinition)
2345 clang::io::Emit32(Out, Writer.getMacroOffset(II));
2346
2347 // Emit the declaration IDs in reverse order, because the
2348 // IdentifierResolver provides the declarations as they would be
2349 // visible (e.g., the function "stat" would come before the struct
2350 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
2351 // adds declarations to the end of the list (so we need to see the
2352 // struct "status" before the function "status").
2353 // Only emit declarations that aren't from a chained PCH, though.
2354 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
2355 IdentifierResolver::end());
2356 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
2357 DEnd = Decls.rend();
2358 D != DEnd; ++D)
2359 clang::io::Emit32(Out, Writer.getDeclID(*D));
2360 }
2361 };
2362 } // end anonymous namespace
2363
2364 /// \brief Write the identifier table into the AST file.
2365 ///
2366 /// The identifier table consists of a blob containing string data
2367 /// (the actual identifiers themselves) and a separate "offsets" index
2368 /// that maps identifier IDs to locations within the blob.
WriteIdentifierTable(Preprocessor & PP)2369 void ASTWriter::WriteIdentifierTable(Preprocessor &PP) {
2370 using namespace llvm;
2371
2372 // Create and write out the blob that contains the identifier
2373 // strings.
2374 {
2375 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
2376 ASTIdentifierTableTrait Trait(*this, PP);
2377
2378 // Look for any identifiers that were named while processing the
2379 // headers, but are otherwise not needed. We add these to the hash
2380 // table to enable checking of the predefines buffer in the case
2381 // where the user adds new macro definitions when building the AST
2382 // file.
2383 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
2384 IDEnd = PP.getIdentifierTable().end();
2385 ID != IDEnd; ++ID)
2386 getIdentifierRef(ID->second);
2387
2388 // Create the on-disk hash table representation. We only store offsets
2389 // for identifiers that appear here for the first time.
2390 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
2391 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
2392 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
2393 ID != IDEnd; ++ID) {
2394 assert(ID->first && "NULL identifier in identifier table");
2395 if (!Chain || !ID->first->isFromAST())
2396 Generator.insert(ID->first, ID->second, Trait);
2397 }
2398
2399 // Create the on-disk hash table in a buffer.
2400 llvm::SmallString<4096> IdentifierTable;
2401 uint32_t BucketOffset;
2402 {
2403 ASTIdentifierTableTrait Trait(*this, PP);
2404 llvm::raw_svector_ostream Out(IdentifierTable);
2405 // Make sure that no bucket is at offset 0
2406 clang::io::Emit32(Out, 0);
2407 BucketOffset = Generator.Emit(Out, Trait);
2408 }
2409
2410 // Create a blob abbreviation
2411 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2412 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
2413 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2414 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2415 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
2416
2417 // Write the identifier table
2418 RecordData Record;
2419 Record.push_back(IDENTIFIER_TABLE);
2420 Record.push_back(BucketOffset);
2421 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
2422 }
2423
2424 // Write the offsets table for identifier IDs.
2425 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2426 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
2427 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
2428 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2429 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2430
2431 RecordData Record;
2432 Record.push_back(IDENTIFIER_OFFSET);
2433 Record.push_back(IdentifierOffsets.size());
2434 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
2435 data(IdentifierOffsets));
2436 }
2437
2438 //===----------------------------------------------------------------------===//
2439 // DeclContext's Name Lookup Table Serialization
2440 //===----------------------------------------------------------------------===//
2441
2442 namespace {
2443 // Trait used for the on-disk hash table used in the method pool.
2444 class ASTDeclContextNameLookupTrait {
2445 ASTWriter &Writer;
2446
2447 public:
2448 typedef DeclarationName key_type;
2449 typedef key_type key_type_ref;
2450
2451 typedef DeclContext::lookup_result data_type;
2452 typedef const data_type& data_type_ref;
2453
ASTDeclContextNameLookupTrait(ASTWriter & Writer)2454 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
2455
ComputeHash(DeclarationName Name)2456 unsigned ComputeHash(DeclarationName Name) {
2457 llvm::FoldingSetNodeID ID;
2458 ID.AddInteger(Name.getNameKind());
2459
2460 switch (Name.getNameKind()) {
2461 case DeclarationName::Identifier:
2462 ID.AddString(Name.getAsIdentifierInfo()->getName());
2463 break;
2464 case DeclarationName::ObjCZeroArgSelector:
2465 case DeclarationName::ObjCOneArgSelector:
2466 case DeclarationName::ObjCMultiArgSelector:
2467 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
2468 break;
2469 case DeclarationName::CXXConstructorName:
2470 case DeclarationName::CXXDestructorName:
2471 case DeclarationName::CXXConversionFunctionName:
2472 ID.AddInteger(Writer.GetOrCreateTypeID(Name.getCXXNameType()));
2473 break;
2474 case DeclarationName::CXXOperatorName:
2475 ID.AddInteger(Name.getCXXOverloadedOperator());
2476 break;
2477 case DeclarationName::CXXLiteralOperatorName:
2478 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
2479 case DeclarationName::CXXUsingDirective:
2480 break;
2481 }
2482
2483 return ID.ComputeHash();
2484 }
2485
2486 std::pair<unsigned,unsigned>
EmitKeyDataLength(llvm::raw_ostream & Out,DeclarationName Name,data_type_ref Lookup)2487 EmitKeyDataLength(llvm::raw_ostream& Out, DeclarationName Name,
2488 data_type_ref Lookup) {
2489 unsigned KeyLen = 1;
2490 switch (Name.getNameKind()) {
2491 case DeclarationName::Identifier:
2492 case DeclarationName::ObjCZeroArgSelector:
2493 case DeclarationName::ObjCOneArgSelector:
2494 case DeclarationName::ObjCMultiArgSelector:
2495 case DeclarationName::CXXConstructorName:
2496 case DeclarationName::CXXDestructorName:
2497 case DeclarationName::CXXConversionFunctionName:
2498 case DeclarationName::CXXLiteralOperatorName:
2499 KeyLen += 4;
2500 break;
2501 case DeclarationName::CXXOperatorName:
2502 KeyLen += 1;
2503 break;
2504 case DeclarationName::CXXUsingDirective:
2505 break;
2506 }
2507 clang::io::Emit16(Out, KeyLen);
2508
2509 // 2 bytes for num of decls and 4 for each DeclID.
2510 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
2511 clang::io::Emit16(Out, DataLen);
2512
2513 return std::make_pair(KeyLen, DataLen);
2514 }
2515
EmitKey(llvm::raw_ostream & Out,DeclarationName Name,unsigned)2516 void EmitKey(llvm::raw_ostream& Out, DeclarationName Name, unsigned) {
2517 using namespace clang::io;
2518
2519 assert(Name.getNameKind() < 0x100 && "Invalid name kind ?");
2520 Emit8(Out, Name.getNameKind());
2521 switch (Name.getNameKind()) {
2522 case DeclarationName::Identifier:
2523 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
2524 break;
2525 case DeclarationName::ObjCZeroArgSelector:
2526 case DeclarationName::ObjCOneArgSelector:
2527 case DeclarationName::ObjCMultiArgSelector:
2528 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
2529 break;
2530 case DeclarationName::CXXConstructorName:
2531 case DeclarationName::CXXDestructorName:
2532 case DeclarationName::CXXConversionFunctionName:
2533 Emit32(Out, Writer.getTypeID(Name.getCXXNameType()));
2534 break;
2535 case DeclarationName::CXXOperatorName:
2536 assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?");
2537 Emit8(Out, Name.getCXXOverloadedOperator());
2538 break;
2539 case DeclarationName::CXXLiteralOperatorName:
2540 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
2541 break;
2542 case DeclarationName::CXXUsingDirective:
2543 break;
2544 }
2545 }
2546
EmitData(llvm::raw_ostream & Out,key_type_ref,data_type Lookup,unsigned DataLen)2547 void EmitData(llvm::raw_ostream& Out, key_type_ref,
2548 data_type Lookup, unsigned DataLen) {
2549 uint64_t Start = Out.tell(); (void)Start;
2550 clang::io::Emit16(Out, Lookup.second - Lookup.first);
2551 for (; Lookup.first != Lookup.second; ++Lookup.first)
2552 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
2553
2554 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2555 }
2556 };
2557 } // end anonymous namespace
2558
2559 /// \brief Write the block containing all of the declaration IDs
2560 /// visible from the given DeclContext.
2561 ///
2562 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
2563 /// bitstream, or 0 if no block was written.
WriteDeclContextVisibleBlock(ASTContext & Context,DeclContext * DC)2564 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
2565 DeclContext *DC) {
2566 if (DC->getPrimaryContext() != DC)
2567 return 0;
2568
2569 // Since there is no name lookup into functions or methods, don't bother to
2570 // build a visible-declarations table for these entities.
2571 if (DC->isFunctionOrMethod())
2572 return 0;
2573
2574 // If not in C++, we perform name lookup for the translation unit via the
2575 // IdentifierInfo chains, don't bother to build a visible-declarations table.
2576 // FIXME: In C++ we need the visible declarations in order to "see" the
2577 // friend declarations, is there a way to do this without writing the table ?
2578 if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus)
2579 return 0;
2580
2581 // Force the DeclContext to build a its name-lookup table.
2582 if (DC->hasExternalVisibleStorage())
2583 DC->MaterializeVisibleDeclsFromExternalStorage();
2584 else
2585 DC->lookup(DeclarationName());
2586
2587 // Serialize the contents of the mapping used for lookup. Note that,
2588 // although we have two very different code paths, the serialized
2589 // representation is the same for both cases: a declaration name,
2590 // followed by a size, followed by references to the visible
2591 // declarations that have that name.
2592 uint64_t Offset = Stream.GetCurrentBitNo();
2593 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2594 if (!Map || Map->empty())
2595 return 0;
2596
2597 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2598 ASTDeclContextNameLookupTrait Trait(*this);
2599
2600 // Create the on-disk hash table representation.
2601 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2602 D != DEnd; ++D) {
2603 DeclarationName Name = D->first;
2604 DeclContext::lookup_result Result = D->second.getLookupResult();
2605 Generator.insert(Name, Result, Trait);
2606 }
2607
2608 // Create the on-disk hash table in a buffer.
2609 llvm::SmallString<4096> LookupTable;
2610 uint32_t BucketOffset;
2611 {
2612 llvm::raw_svector_ostream Out(LookupTable);
2613 // Make sure that no bucket is at offset 0
2614 clang::io::Emit32(Out, 0);
2615 BucketOffset = Generator.Emit(Out, Trait);
2616 }
2617
2618 // Write the lookup table
2619 RecordData Record;
2620 Record.push_back(DECL_CONTEXT_VISIBLE);
2621 Record.push_back(BucketOffset);
2622 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
2623 LookupTable.str());
2624
2625 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
2626 ++NumVisibleDeclContexts;
2627 return Offset;
2628 }
2629
2630 /// \brief Write an UPDATE_VISIBLE block for the given context.
2631 ///
2632 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
2633 /// DeclContext in a dependent AST file. As such, they only exist for the TU
2634 /// (in C++) and for namespaces.
WriteDeclContextVisibleUpdate(const DeclContext * DC)2635 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
2636 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2637 if (!Map || Map->empty())
2638 return;
2639
2640 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2641 ASTDeclContextNameLookupTrait Trait(*this);
2642
2643 // Create the hash table.
2644 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2645 D != DEnd; ++D) {
2646 DeclarationName Name = D->first;
2647 DeclContext::lookup_result Result = D->second.getLookupResult();
2648 // For any name that appears in this table, the results are complete, i.e.
2649 // they overwrite results from previous PCHs. Merging is always a mess.
2650 Generator.insert(Name, Result, Trait);
2651 }
2652
2653 // Create the on-disk hash table in a buffer.
2654 llvm::SmallString<4096> LookupTable;
2655 uint32_t BucketOffset;
2656 {
2657 llvm::raw_svector_ostream Out(LookupTable);
2658 // Make sure that no bucket is at offset 0
2659 clang::io::Emit32(Out, 0);
2660 BucketOffset = Generator.Emit(Out, Trait);
2661 }
2662
2663 // Write the lookup table
2664 RecordData Record;
2665 Record.push_back(UPDATE_VISIBLE);
2666 Record.push_back(getDeclID(cast<Decl>(DC)));
2667 Record.push_back(BucketOffset);
2668 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
2669 }
2670
2671 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
WriteFPPragmaOptions(const FPOptions & Opts)2672 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
2673 RecordData Record;
2674 Record.push_back(Opts.fp_contract);
2675 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
2676 }
2677
2678 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
WriteOpenCLExtensions(Sema & SemaRef)2679 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
2680 if (!SemaRef.Context.getLangOptions().OpenCL)
2681 return;
2682
2683 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
2684 RecordData Record;
2685 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
2686 #include "clang/Basic/OpenCLExtensions.def"
2687 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
2688 }
2689
2690 //===----------------------------------------------------------------------===//
2691 // General Serialization Routines
2692 //===----------------------------------------------------------------------===//
2693
2694 /// \brief Write a record containing the given attributes.
WriteAttributes(const AttrVec & Attrs,RecordDataImpl & Record)2695 void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) {
2696 Record.push_back(Attrs.size());
2697 for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){
2698 const Attr * A = *i;
2699 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
2700 AddSourceLocation(A->getLocation(), Record);
2701
2702 #include "clang/Serialization/AttrPCHWrite.inc"
2703
2704 }
2705 }
2706
AddString(llvm::StringRef Str,RecordDataImpl & Record)2707 void ASTWriter::AddString(llvm::StringRef Str, RecordDataImpl &Record) {
2708 Record.push_back(Str.size());
2709 Record.insert(Record.end(), Str.begin(), Str.end());
2710 }
2711
AddVersionTuple(const VersionTuple & Version,RecordDataImpl & Record)2712 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
2713 RecordDataImpl &Record) {
2714 Record.push_back(Version.getMajor());
2715 if (llvm::Optional<unsigned> Minor = Version.getMinor())
2716 Record.push_back(*Minor + 1);
2717 else
2718 Record.push_back(0);
2719 if (llvm::Optional<unsigned> Subminor = Version.getSubminor())
2720 Record.push_back(*Subminor + 1);
2721 else
2722 Record.push_back(0);
2723 }
2724
2725 /// \brief Note that the identifier II occurs at the given offset
2726 /// within the identifier table.
SetIdentifierOffset(const IdentifierInfo * II,uint32_t Offset)2727 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
2728 IdentID ID = IdentifierIDs[II];
2729 // Only store offsets new to this AST file. Other identifier names are looked
2730 // up earlier in the chain and thus don't need an offset.
2731 if (ID >= FirstIdentID)
2732 IdentifierOffsets[ID - FirstIdentID] = Offset;
2733 }
2734
2735 /// \brief Note that the selector Sel occurs at the given offset
2736 /// within the method pool/selector table.
SetSelectorOffset(Selector Sel,uint32_t Offset)2737 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
2738 unsigned ID = SelectorIDs[Sel];
2739 assert(ID && "Unknown selector");
2740 // Don't record offsets for selectors that are also available in a different
2741 // file.
2742 if (ID < FirstSelectorID)
2743 return;
2744 SelectorOffsets[ID - FirstSelectorID] = Offset;
2745 }
2746
ASTWriter(llvm::BitstreamWriter & Stream)2747 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
2748 : Stream(Stream), Chain(0), SerializationListener(0),
2749 FirstDeclID(1), NextDeclID(FirstDeclID),
2750 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
2751 FirstIdentID(1), NextIdentID(FirstIdentID), FirstSelectorID(1),
2752 NextSelectorID(FirstSelectorID), FirstMacroID(1), NextMacroID(FirstMacroID),
2753 CollectedStmts(&StmtsToEmit),
2754 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
2755 NumVisibleDeclContexts(0),
2756 FirstCXXBaseSpecifiersID(1), NextCXXBaseSpecifiersID(1),
2757 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
2758 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
2759 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
2760 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
2761 DeclTypedefAbbrev(0),
2762 DeclVarAbbrev(0), DeclFieldAbbrev(0),
2763 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
2764 {
2765 }
2766
WriteAST(Sema & SemaRef,MemorizeStatCalls * StatCalls,const std::string & OutputFile,const char * isysroot)2767 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2768 const std::string &OutputFile,
2769 const char *isysroot) {
2770 // Emit the file header.
2771 Stream.Emit((unsigned)'C', 8);
2772 Stream.Emit((unsigned)'P', 8);
2773 Stream.Emit((unsigned)'C', 8);
2774 Stream.Emit((unsigned)'H', 8);
2775
2776 WriteBlockInfoBlock();
2777
2778 if (Chain)
2779 WriteASTChain(SemaRef, StatCalls, isysroot);
2780 else
2781 WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile);
2782 }
2783
WriteASTCore(Sema & SemaRef,MemorizeStatCalls * StatCalls,const char * isysroot,const std::string & OutputFile)2784 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2785 const char *isysroot,
2786 const std::string &OutputFile) {
2787 using namespace llvm;
2788
2789 ASTContext &Context = SemaRef.Context;
2790 Preprocessor &PP = SemaRef.PP;
2791
2792 // The translation unit is the first declaration we'll emit.
2793 DeclIDs[Context.getTranslationUnitDecl()] = 1;
2794 ++NextDeclID;
2795 DeclTypesToEmit.push(Context.getTranslationUnitDecl());
2796
2797 // Make sure that we emit IdentifierInfos (and any attached
2798 // declarations) for builtins.
2799 {
2800 IdentifierTable &Table = PP.getIdentifierTable();
2801 llvm::SmallVector<const char *, 32> BuiltinNames;
2802 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
2803 Context.getLangOptions().NoBuiltin);
2804 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
2805 getIdentifierRef(&Table.get(BuiltinNames[I]));
2806 }
2807
2808 // Build a record containing all of the tentative definitions in this file, in
2809 // TentativeDefinitions order. Generally, this record will be empty for
2810 // headers.
2811 RecordData TentativeDefinitions;
2812 for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
2813 AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
2814 }
2815
2816 // Build a record containing all of the file scoped decls in this file.
2817 RecordData UnusedFileScopedDecls;
2818 for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i)
2819 AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
2820
2821 RecordData DelegatingCtorDecls;
2822 for (unsigned i=0, e = SemaRef.DelegatingCtorDecls.size(); i != e; ++i)
2823 AddDeclRef(SemaRef.DelegatingCtorDecls[i], DelegatingCtorDecls);
2824
2825 RecordData WeakUndeclaredIdentifiers;
2826 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
2827 WeakUndeclaredIdentifiers.push_back(
2828 SemaRef.WeakUndeclaredIdentifiers.size());
2829 for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
2830 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
2831 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
2832 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
2833 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
2834 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
2835 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
2836 }
2837 }
2838
2839 // Build a record containing all of the locally-scoped external
2840 // declarations in this header file. Generally, this record will be
2841 // empty.
2842 RecordData LocallyScopedExternalDecls;
2843 // FIXME: This is filling in the AST file in densemap order which is
2844 // nondeterminstic!
2845 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
2846 TD = SemaRef.LocallyScopedExternalDecls.begin(),
2847 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
2848 TD != TDEnd; ++TD)
2849 AddDeclRef(TD->second, LocallyScopedExternalDecls);
2850
2851 // Build a record containing all of the ext_vector declarations.
2852 RecordData ExtVectorDecls;
2853 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
2854 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
2855
2856 // Build a record containing all of the VTable uses information.
2857 RecordData VTableUses;
2858 if (!SemaRef.VTableUses.empty()) {
2859 VTableUses.push_back(SemaRef.VTableUses.size());
2860 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
2861 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
2862 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
2863 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
2864 }
2865 }
2866
2867 // Build a record containing all of dynamic classes declarations.
2868 RecordData DynamicClasses;
2869 for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
2870 AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
2871
2872 // Build a record containing all of pending implicit instantiations.
2873 RecordData PendingInstantiations;
2874 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
2875 I = SemaRef.PendingInstantiations.begin(),
2876 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
2877 AddDeclRef(I->first, PendingInstantiations);
2878 AddSourceLocation(I->second, PendingInstantiations);
2879 }
2880 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
2881 "There are local ones at end of translation unit!");
2882
2883 // Build a record containing some declaration references.
2884 RecordData SemaDeclRefs;
2885 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
2886 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
2887 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
2888 }
2889
2890 RecordData CUDASpecialDeclRefs;
2891 if (Context.getcudaConfigureCallDecl()) {
2892 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
2893 }
2894
2895 // Build a record containing all of the known namespaces.
2896 RecordData KnownNamespaces;
2897 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
2898 I = SemaRef.KnownNamespaces.begin(),
2899 IEnd = SemaRef.KnownNamespaces.end();
2900 I != IEnd; ++I) {
2901 if (!I->second)
2902 AddDeclRef(I->first, KnownNamespaces);
2903 }
2904
2905 // Write the remaining AST contents.
2906 RecordData Record;
2907 Stream.EnterSubblock(AST_BLOCK_ID, 5);
2908 WriteMetadata(Context, isysroot, OutputFile);
2909 WriteLanguageOptions(Context.getLangOptions());
2910 if (StatCalls && !isysroot)
2911 WriteStatCache(*StatCalls);
2912 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2913 // Write the record of special types.
2914 Record.clear();
2915
2916 AddTypeRef(Context.getBuiltinVaListType(), Record);
2917 AddTypeRef(Context.getObjCIdType(), Record);
2918 AddTypeRef(Context.getObjCSelType(), Record);
2919 AddTypeRef(Context.getObjCProtoType(), Record);
2920 AddTypeRef(Context.getObjCClassType(), Record);
2921 AddTypeRef(Context.getRawCFConstantStringType(), Record);
2922 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
2923 AddTypeRef(Context.getFILEType(), Record);
2924 AddTypeRef(Context.getjmp_bufType(), Record);
2925 AddTypeRef(Context.getsigjmp_bufType(), Record);
2926 AddTypeRef(Context.ObjCIdRedefinitionType, Record);
2927 AddTypeRef(Context.ObjCClassRedefinitionType, Record);
2928 AddTypeRef(Context.getRawBlockdescriptorType(), Record);
2929 AddTypeRef(Context.getRawBlockdescriptorExtendedType(), Record);
2930 AddTypeRef(Context.ObjCSelRedefinitionType, Record);
2931 AddTypeRef(Context.getRawNSConstantStringType(), Record);
2932 Record.push_back(Context.isInt128Installed());
2933 AddTypeRef(Context.AutoDeductTy, Record);
2934 AddTypeRef(Context.AutoRRefDeductTy, Record);
2935 Stream.EmitRecord(SPECIAL_TYPES, Record);
2936
2937 // Keep writing types and declarations until all types and
2938 // declarations have been written.
2939 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
2940 WriteDeclsBlockAbbrevs();
2941 while (!DeclTypesToEmit.empty()) {
2942 DeclOrType DOT = DeclTypesToEmit.front();
2943 DeclTypesToEmit.pop();
2944 if (DOT.isType())
2945 WriteType(DOT.getType());
2946 else
2947 WriteDecl(Context, DOT.getDecl());
2948 }
2949 Stream.ExitBlock();
2950
2951 WritePreprocessor(PP);
2952 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
2953 WriteSelectors(SemaRef);
2954 WriteReferencedSelectorsPool(SemaRef);
2955 WriteIdentifierTable(PP);
2956 WriteFPPragmaOptions(SemaRef.getFPOptions());
2957 WriteOpenCLExtensions(SemaRef);
2958
2959 WriteTypeDeclOffsets();
2960 WritePragmaDiagnosticMappings(Context.getDiagnostics());
2961
2962 WriteCXXBaseSpecifiersOffsets();
2963
2964 // Write the record containing external, unnamed definitions.
2965 if (!ExternalDefinitions.empty())
2966 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
2967
2968 // Write the record containing tentative definitions.
2969 if (!TentativeDefinitions.empty())
2970 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
2971
2972 // Write the record containing unused file scoped decls.
2973 if (!UnusedFileScopedDecls.empty())
2974 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
2975
2976 // Write the record containing weak undeclared identifiers.
2977 if (!WeakUndeclaredIdentifiers.empty())
2978 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
2979 WeakUndeclaredIdentifiers);
2980
2981 // Write the record containing locally-scoped external definitions.
2982 if (!LocallyScopedExternalDecls.empty())
2983 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
2984 LocallyScopedExternalDecls);
2985
2986 // Write the record containing ext_vector type names.
2987 if (!ExtVectorDecls.empty())
2988 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
2989
2990 // Write the record containing VTable uses information.
2991 if (!VTableUses.empty())
2992 Stream.EmitRecord(VTABLE_USES, VTableUses);
2993
2994 // Write the record containing dynamic classes declarations.
2995 if (!DynamicClasses.empty())
2996 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
2997
2998 // Write the record containing pending implicit instantiations.
2999 if (!PendingInstantiations.empty())
3000 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
3001
3002 // Write the record containing declaration references of Sema.
3003 if (!SemaDeclRefs.empty())
3004 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
3005
3006 // Write the record containing CUDA-specific declaration references.
3007 if (!CUDASpecialDeclRefs.empty())
3008 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
3009
3010 // Write the delegating constructors.
3011 if (!DelegatingCtorDecls.empty())
3012 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
3013
3014 // Write the known namespaces.
3015 if (!KnownNamespaces.empty())
3016 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
3017
3018 // Some simple statistics
3019 Record.clear();
3020 Record.push_back(NumStatements);
3021 Record.push_back(NumMacros);
3022 Record.push_back(NumLexicalDeclContexts);
3023 Record.push_back(NumVisibleDeclContexts);
3024 Stream.EmitRecord(STATISTICS, Record);
3025 Stream.ExitBlock();
3026 }
3027
WriteASTChain(Sema & SemaRef,MemorizeStatCalls * StatCalls,const char * isysroot)3028 void ASTWriter::WriteASTChain(Sema &SemaRef, MemorizeStatCalls *StatCalls,
3029 const char *isysroot) {
3030 using namespace llvm;
3031
3032 ASTContext &Context = SemaRef.Context;
3033 Preprocessor &PP = SemaRef.PP;
3034
3035 RecordData Record;
3036 Stream.EnterSubblock(AST_BLOCK_ID, 5);
3037 WriteMetadata(Context, isysroot, "");
3038 if (StatCalls && !isysroot)
3039 WriteStatCache(*StatCalls);
3040 // FIXME: Source manager block should only write new stuff, which could be
3041 // done by tracking the largest ID in the chain
3042 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
3043
3044 // The special types are in the chained PCH.
3045
3046 // We don't start with the translation unit, but with its decls that
3047 // don't come from the chained PCH.
3048 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3049 llvm::SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
3050 for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
3051 E = TU->noload_decls_end();
3052 I != E; ++I) {
3053 if ((*I)->getPCHLevel() == 0)
3054 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
3055 else if ((*I)->isChangedSinceDeserialization())
3056 (void)GetDeclRef(*I); // Make sure it's written, but don't record it.
3057 }
3058 // We also need to write a lexical updates block for the TU.
3059 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
3060 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
3061 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3062 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
3063 Record.clear();
3064 Record.push_back(TU_UPDATE_LEXICAL);
3065 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
3066 data(NewGlobalDecls));
3067 // And a visible updates block for the DeclContexts.
3068 Abv = new llvm::BitCodeAbbrev();
3069 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
3070 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3071 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
3072 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3073 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
3074 WriteDeclContextVisibleUpdate(TU);
3075
3076 // Build a record containing all of the new tentative definitions in this
3077 // file, in TentativeDefinitions order.
3078 RecordData TentativeDefinitions;
3079 for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
3080 if (SemaRef.TentativeDefinitions[i]->getPCHLevel() == 0)
3081 AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
3082 }
3083
3084 // Build a record containing all of the file scoped decls in this file.
3085 RecordData UnusedFileScopedDecls;
3086 for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i) {
3087 if (SemaRef.UnusedFileScopedDecls[i]->getPCHLevel() == 0)
3088 AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
3089 }
3090
3091 // Build a record containing all of the delegating constructor decls in this
3092 // file.
3093 RecordData DelegatingCtorDecls;
3094 for (unsigned i=0, e = SemaRef.DelegatingCtorDecls.size(); i != e; ++i) {
3095 if (SemaRef.DelegatingCtorDecls[i]->getPCHLevel() == 0)
3096 AddDeclRef(SemaRef.DelegatingCtorDecls[i], DelegatingCtorDecls);
3097 }
3098
3099 // We write the entire table, overwriting the tables from the chain.
3100 RecordData WeakUndeclaredIdentifiers;
3101 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
3102 WeakUndeclaredIdentifiers.push_back(
3103 SemaRef.WeakUndeclaredIdentifiers.size());
3104 for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
3105 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
3106 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
3107 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
3108 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
3109 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
3110 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
3111 }
3112 }
3113
3114 // Build a record containing all of the locally-scoped external
3115 // declarations in this header file. Generally, this record will be
3116 // empty.
3117 RecordData LocallyScopedExternalDecls;
3118 // FIXME: This is filling in the AST file in densemap order which is
3119 // nondeterminstic!
3120 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3121 TD = SemaRef.LocallyScopedExternalDecls.begin(),
3122 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
3123 TD != TDEnd; ++TD) {
3124 if (TD->second->getPCHLevel() == 0)
3125 AddDeclRef(TD->second, LocallyScopedExternalDecls);
3126 }
3127
3128 // Build a record containing all of the ext_vector declarations.
3129 RecordData ExtVectorDecls;
3130 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I) {
3131 if (SemaRef.ExtVectorDecls[I]->getPCHLevel() == 0)
3132 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
3133 }
3134
3135 // Build a record containing all of the VTable uses information.
3136 // We write everything here, because it's too hard to determine whether
3137 // a use is new to this part.
3138 RecordData VTableUses;
3139 if (!SemaRef.VTableUses.empty()) {
3140 VTableUses.push_back(SemaRef.VTableUses.size());
3141 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
3142 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
3143 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
3144 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
3145 }
3146 }
3147
3148 // Build a record containing all of dynamic classes declarations.
3149 RecordData DynamicClasses;
3150 for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
3151 if (SemaRef.DynamicClasses[I]->getPCHLevel() == 0)
3152 AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
3153
3154 // Build a record containing all of pending implicit instantiations.
3155 RecordData PendingInstantiations;
3156 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
3157 I = SemaRef.PendingInstantiations.begin(),
3158 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
3159 AddDeclRef(I->first, PendingInstantiations);
3160 AddSourceLocation(I->second, PendingInstantiations);
3161 }
3162 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
3163 "There are local ones at end of translation unit!");
3164
3165 // Build a record containing some declaration references.
3166 // It's not worth the effort to avoid duplication here.
3167 RecordData SemaDeclRefs;
3168 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
3169 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
3170 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
3171 }
3172
3173 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3174 WriteDeclsBlockAbbrevs();
3175 for (DeclsToRewriteTy::iterator
3176 I = DeclsToRewrite.begin(), E = DeclsToRewrite.end(); I != E; ++I)
3177 DeclTypesToEmit.push(const_cast<Decl*>(*I));
3178 while (!DeclTypesToEmit.empty()) {
3179 DeclOrType DOT = DeclTypesToEmit.front();
3180 DeclTypesToEmit.pop();
3181 if (DOT.isType())
3182 WriteType(DOT.getType());
3183 else
3184 WriteDecl(Context, DOT.getDecl());
3185 }
3186 Stream.ExitBlock();
3187
3188 WritePreprocessor(PP);
3189 WriteSelectors(SemaRef);
3190 WriteReferencedSelectorsPool(SemaRef);
3191 WriteIdentifierTable(PP);
3192 WriteFPPragmaOptions(SemaRef.getFPOptions());
3193 WriteOpenCLExtensions(SemaRef);
3194
3195 WriteTypeDeclOffsets();
3196 // FIXME: For chained PCH only write the new mappings (we currently
3197 // write all of them again).
3198 WritePragmaDiagnosticMappings(Context.getDiagnostics());
3199
3200 WriteCXXBaseSpecifiersOffsets();
3201
3202 /// Build a record containing first declarations from a chained PCH and the
3203 /// most recent declarations in this AST that they point to.
3204 RecordData FirstLatestDeclIDs;
3205 for (FirstLatestDeclMap::iterator
3206 I = FirstLatestDecls.begin(), E = FirstLatestDecls.end(); I != E; ++I) {
3207 assert(I->first->getPCHLevel() > I->second->getPCHLevel() &&
3208 "Expected first & second to be in different PCHs");
3209 AddDeclRef(I->first, FirstLatestDeclIDs);
3210 AddDeclRef(I->second, FirstLatestDeclIDs);
3211 }
3212 if (!FirstLatestDeclIDs.empty())
3213 Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs);
3214
3215 // Write the record containing external, unnamed definitions.
3216 if (!ExternalDefinitions.empty())
3217 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
3218
3219 // Write the record containing tentative definitions.
3220 if (!TentativeDefinitions.empty())
3221 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
3222
3223 // Write the record containing unused file scoped decls.
3224 if (!UnusedFileScopedDecls.empty())
3225 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
3226
3227 // Write the record containing weak undeclared identifiers.
3228 if (!WeakUndeclaredIdentifiers.empty())
3229 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
3230 WeakUndeclaredIdentifiers);
3231
3232 // Write the record containing locally-scoped external definitions.
3233 if (!LocallyScopedExternalDecls.empty())
3234 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
3235 LocallyScopedExternalDecls);
3236
3237 // Write the record containing ext_vector type names.
3238 if (!ExtVectorDecls.empty())
3239 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
3240
3241 // Write the record containing VTable uses information.
3242 if (!VTableUses.empty())
3243 Stream.EmitRecord(VTABLE_USES, VTableUses);
3244
3245 // Write the record containing dynamic classes declarations.
3246 if (!DynamicClasses.empty())
3247 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
3248
3249 // Write the record containing pending implicit instantiations.
3250 if (!PendingInstantiations.empty())
3251 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
3252
3253 // Write the record containing declaration references of Sema.
3254 if (!SemaDeclRefs.empty())
3255 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
3256
3257 // Write the delegating constructors.
3258 if (!DelegatingCtorDecls.empty())
3259 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
3260
3261 // Write the updates to DeclContexts.
3262 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
3263 I = UpdatedDeclContexts.begin(),
3264 E = UpdatedDeclContexts.end();
3265 I != E; ++I)
3266 WriteDeclContextVisibleUpdate(*I);
3267
3268 WriteDeclUpdatesBlocks();
3269
3270 Record.clear();
3271 Record.push_back(NumStatements);
3272 Record.push_back(NumMacros);
3273 Record.push_back(NumLexicalDeclContexts);
3274 Record.push_back(NumVisibleDeclContexts);
3275 WriteDeclReplacementsBlock();
3276 Stream.EmitRecord(STATISTICS, Record);
3277 Stream.ExitBlock();
3278 }
3279
WriteDeclUpdatesBlocks()3280 void ASTWriter::WriteDeclUpdatesBlocks() {
3281 if (DeclUpdates.empty())
3282 return;
3283
3284 RecordData OffsetsRecord;
3285 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3286 for (DeclUpdateMap::iterator
3287 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
3288 const Decl *D = I->first;
3289 UpdateRecord &URec = I->second;
3290
3291 if (DeclsToRewrite.count(D))
3292 continue; // The decl will be written completely,no need to store updates.
3293
3294 uint64_t Offset = Stream.GetCurrentBitNo();
3295 Stream.EmitRecord(DECL_UPDATES, URec);
3296
3297 OffsetsRecord.push_back(GetDeclRef(D));
3298 OffsetsRecord.push_back(Offset);
3299 }
3300 Stream.ExitBlock();
3301 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
3302 }
3303
WriteDeclReplacementsBlock()3304 void ASTWriter::WriteDeclReplacementsBlock() {
3305 if (ReplacedDecls.empty())
3306 return;
3307
3308 RecordData Record;
3309 for (llvm::SmallVector<std::pair<DeclID, uint64_t>, 16>::iterator
3310 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
3311 Record.push_back(I->first);
3312 Record.push_back(I->second);
3313 }
3314 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
3315 }
3316
AddSourceLocation(SourceLocation Loc,RecordDataImpl & Record)3317 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
3318 Record.push_back(Loc.getRawEncoding());
3319 }
3320
AddSourceRange(SourceRange Range,RecordDataImpl & Record)3321 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
3322 AddSourceLocation(Range.getBegin(), Record);
3323 AddSourceLocation(Range.getEnd(), Record);
3324 }
3325
AddAPInt(const llvm::APInt & Value,RecordDataImpl & Record)3326 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
3327 Record.push_back(Value.getBitWidth());
3328 const uint64_t *Words = Value.getRawData();
3329 Record.append(Words, Words + Value.getNumWords());
3330 }
3331
AddAPSInt(const llvm::APSInt & Value,RecordDataImpl & Record)3332 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
3333 Record.push_back(Value.isUnsigned());
3334 AddAPInt(Value, Record);
3335 }
3336
AddAPFloat(const llvm::APFloat & Value,RecordDataImpl & Record)3337 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
3338 AddAPInt(Value.bitcastToAPInt(), Record);
3339 }
3340
AddIdentifierRef(const IdentifierInfo * II,RecordDataImpl & Record)3341 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
3342 Record.push_back(getIdentifierRef(II));
3343 }
3344
getIdentifierRef(const IdentifierInfo * II)3345 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
3346 if (II == 0)
3347 return 0;
3348
3349 IdentID &ID = IdentifierIDs[II];
3350 if (ID == 0)
3351 ID = NextIdentID++;
3352 return ID;
3353 }
3354
getMacroDefinitionID(MacroDefinition * MD)3355 MacroID ASTWriter::getMacroDefinitionID(MacroDefinition *MD) {
3356 if (MD == 0)
3357 return 0;
3358
3359 MacroID &ID = MacroDefinitions[MD];
3360 if (ID == 0)
3361 ID = NextMacroID++;
3362 return ID;
3363 }
3364
AddSelectorRef(const Selector SelRef,RecordDataImpl & Record)3365 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
3366 Record.push_back(getSelectorRef(SelRef));
3367 }
3368
getSelectorRef(Selector Sel)3369 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
3370 if (Sel.getAsOpaquePtr() == 0) {
3371 return 0;
3372 }
3373
3374 SelectorID &SID = SelectorIDs[Sel];
3375 if (SID == 0 && Chain) {
3376 // This might trigger a ReadSelector callback, which will set the ID for
3377 // this selector.
3378 Chain->LoadSelector(Sel);
3379 }
3380 if (SID == 0) {
3381 SID = NextSelectorID++;
3382 }
3383 return SID;
3384 }
3385
AddCXXTemporary(const CXXTemporary * Temp,RecordDataImpl & Record)3386 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
3387 AddDeclRef(Temp->getDestructor(), Record);
3388 }
3389
AddCXXBaseSpecifiersRef(CXXBaseSpecifier const * Bases,CXXBaseSpecifier const * BasesEnd,RecordDataImpl & Record)3390 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
3391 CXXBaseSpecifier const *BasesEnd,
3392 RecordDataImpl &Record) {
3393 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
3394 CXXBaseSpecifiersToWrite.push_back(
3395 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
3396 Bases, BasesEnd));
3397 Record.push_back(NextCXXBaseSpecifiersID++);
3398 }
3399
AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,const TemplateArgumentLocInfo & Arg,RecordDataImpl & Record)3400 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
3401 const TemplateArgumentLocInfo &Arg,
3402 RecordDataImpl &Record) {
3403 switch (Kind) {
3404 case TemplateArgument::Expression:
3405 AddStmt(Arg.getAsExpr());
3406 break;
3407 case TemplateArgument::Type:
3408 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
3409 break;
3410 case TemplateArgument::Template:
3411 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3412 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3413 break;
3414 case TemplateArgument::TemplateExpansion:
3415 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3416 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3417 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
3418 break;
3419 case TemplateArgument::Null:
3420 case TemplateArgument::Integral:
3421 case TemplateArgument::Declaration:
3422 case TemplateArgument::Pack:
3423 break;
3424 }
3425 }
3426
AddTemplateArgumentLoc(const TemplateArgumentLoc & Arg,RecordDataImpl & Record)3427 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
3428 RecordDataImpl &Record) {
3429 AddTemplateArgument(Arg.getArgument(), Record);
3430
3431 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
3432 bool InfoHasSameExpr
3433 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
3434 Record.push_back(InfoHasSameExpr);
3435 if (InfoHasSameExpr)
3436 return; // Avoid storing the same expr twice.
3437 }
3438 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
3439 Record);
3440 }
3441
AddTypeSourceInfo(TypeSourceInfo * TInfo,RecordDataImpl & Record)3442 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
3443 RecordDataImpl &Record) {
3444 if (TInfo == 0) {
3445 AddTypeRef(QualType(), Record);
3446 return;
3447 }
3448
3449 AddTypeLoc(TInfo->getTypeLoc(), Record);
3450 }
3451
AddTypeLoc(TypeLoc TL,RecordDataImpl & Record)3452 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
3453 AddTypeRef(TL.getType(), Record);
3454
3455 TypeLocWriter TLW(*this, Record);
3456 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
3457 TLW.Visit(TL);
3458 }
3459
AddTypeRef(QualType T,RecordDataImpl & Record)3460 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
3461 Record.push_back(GetOrCreateTypeID(T));
3462 }
3463
GetOrCreateTypeID(QualType T)3464 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
3465 return MakeTypeID(T,
3466 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
3467 }
3468
getTypeID(QualType T) const3469 TypeID ASTWriter::getTypeID(QualType T) const {
3470 return MakeTypeID(T,
3471 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
3472 }
3473
GetOrCreateTypeIdx(QualType T)3474 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
3475 if (T.isNull())
3476 return TypeIdx();
3477 assert(!T.getLocalFastQualifiers());
3478
3479 TypeIdx &Idx = TypeIdxs[T];
3480 if (Idx.getIndex() == 0) {
3481 // We haven't seen this type before. Assign it a new ID and put it
3482 // into the queue of types to emit.
3483 Idx = TypeIdx(NextTypeID++);
3484 DeclTypesToEmit.push(T);
3485 }
3486 return Idx;
3487 }
3488
getTypeIdx(QualType T) const3489 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
3490 if (T.isNull())
3491 return TypeIdx();
3492 assert(!T.getLocalFastQualifiers());
3493
3494 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
3495 assert(I != TypeIdxs.end() && "Type not emitted!");
3496 return I->second;
3497 }
3498
AddDeclRef(const Decl * D,RecordDataImpl & Record)3499 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
3500 Record.push_back(GetDeclRef(D));
3501 }
3502
GetDeclRef(const Decl * D)3503 DeclID ASTWriter::GetDeclRef(const Decl *D) {
3504 if (D == 0) {
3505 return 0;
3506 }
3507 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
3508 DeclID &ID = DeclIDs[D];
3509 if (ID == 0) {
3510 // We haven't seen this declaration before. Give it a new ID and
3511 // enqueue it in the list of declarations to emit.
3512 ID = NextDeclID++;
3513 DeclTypesToEmit.push(const_cast<Decl *>(D));
3514 } else if (ID < FirstDeclID && D->isChangedSinceDeserialization()) {
3515 // We don't add it to the replacement collection here, because we don't
3516 // have the offset yet.
3517 DeclTypesToEmit.push(const_cast<Decl *>(D));
3518 // Reset the flag, so that we don't add this decl multiple times.
3519 const_cast<Decl *>(D)->setChangedSinceDeserialization(false);
3520 }
3521
3522 return ID;
3523 }
3524
getDeclID(const Decl * D)3525 DeclID ASTWriter::getDeclID(const Decl *D) {
3526 if (D == 0)
3527 return 0;
3528
3529 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
3530 return DeclIDs[D];
3531 }
3532
AddDeclarationName(DeclarationName Name,RecordDataImpl & Record)3533 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
3534 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
3535 Record.push_back(Name.getNameKind());
3536 switch (Name.getNameKind()) {
3537 case DeclarationName::Identifier:
3538 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
3539 break;
3540
3541 case DeclarationName::ObjCZeroArgSelector:
3542 case DeclarationName::ObjCOneArgSelector:
3543 case DeclarationName::ObjCMultiArgSelector:
3544 AddSelectorRef(Name.getObjCSelector(), Record);
3545 break;
3546
3547 case DeclarationName::CXXConstructorName:
3548 case DeclarationName::CXXDestructorName:
3549 case DeclarationName::CXXConversionFunctionName:
3550 AddTypeRef(Name.getCXXNameType(), Record);
3551 break;
3552
3553 case DeclarationName::CXXOperatorName:
3554 Record.push_back(Name.getCXXOverloadedOperator());
3555 break;
3556
3557 case DeclarationName::CXXLiteralOperatorName:
3558 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
3559 break;
3560
3561 case DeclarationName::CXXUsingDirective:
3562 // No extra data to emit
3563 break;
3564 }
3565 }
3566
AddDeclarationNameLoc(const DeclarationNameLoc & DNLoc,DeclarationName Name,RecordDataImpl & Record)3567 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
3568 DeclarationName Name, RecordDataImpl &Record) {
3569 switch (Name.getNameKind()) {
3570 case DeclarationName::CXXConstructorName:
3571 case DeclarationName::CXXDestructorName:
3572 case DeclarationName::CXXConversionFunctionName:
3573 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
3574 break;
3575
3576 case DeclarationName::CXXOperatorName:
3577 AddSourceLocation(
3578 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
3579 Record);
3580 AddSourceLocation(
3581 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
3582 Record);
3583 break;
3584
3585 case DeclarationName::CXXLiteralOperatorName:
3586 AddSourceLocation(
3587 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
3588 Record);
3589 break;
3590
3591 case DeclarationName::Identifier:
3592 case DeclarationName::ObjCZeroArgSelector:
3593 case DeclarationName::ObjCOneArgSelector:
3594 case DeclarationName::ObjCMultiArgSelector:
3595 case DeclarationName::CXXUsingDirective:
3596 break;
3597 }
3598 }
3599
AddDeclarationNameInfo(const DeclarationNameInfo & NameInfo,RecordDataImpl & Record)3600 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3601 RecordDataImpl &Record) {
3602 AddDeclarationName(NameInfo.getName(), Record);
3603 AddSourceLocation(NameInfo.getLoc(), Record);
3604 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
3605 }
3606
AddQualifierInfo(const QualifierInfo & Info,RecordDataImpl & Record)3607 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
3608 RecordDataImpl &Record) {
3609 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
3610 Record.push_back(Info.NumTemplParamLists);
3611 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
3612 AddTemplateParameterList(Info.TemplParamLists[i], Record);
3613 }
3614
AddNestedNameSpecifier(NestedNameSpecifier * NNS,RecordDataImpl & Record)3615 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
3616 RecordDataImpl &Record) {
3617 // Nested name specifiers usually aren't too long. I think that 8 would
3618 // typically accommodate the vast majority.
3619 llvm::SmallVector<NestedNameSpecifier *, 8> NestedNames;
3620
3621 // Push each of the NNS's onto a stack for serialization in reverse order.
3622 while (NNS) {
3623 NestedNames.push_back(NNS);
3624 NNS = NNS->getPrefix();
3625 }
3626
3627 Record.push_back(NestedNames.size());
3628 while(!NestedNames.empty()) {
3629 NNS = NestedNames.pop_back_val();
3630 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
3631 Record.push_back(Kind);
3632 switch (Kind) {
3633 case NestedNameSpecifier::Identifier:
3634 AddIdentifierRef(NNS->getAsIdentifier(), Record);
3635 break;
3636
3637 case NestedNameSpecifier::Namespace:
3638 AddDeclRef(NNS->getAsNamespace(), Record);
3639 break;
3640
3641 case NestedNameSpecifier::NamespaceAlias:
3642 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
3643 break;
3644
3645 case NestedNameSpecifier::TypeSpec:
3646 case NestedNameSpecifier::TypeSpecWithTemplate:
3647 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
3648 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3649 break;
3650
3651 case NestedNameSpecifier::Global:
3652 // Don't need to write an associated value.
3653 break;
3654 }
3655 }
3656 }
3657
AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,RecordDataImpl & Record)3658 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
3659 RecordDataImpl &Record) {
3660 // Nested name specifiers usually aren't too long. I think that 8 would
3661 // typically accommodate the vast majority.
3662 llvm::SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
3663
3664 // Push each of the nested-name-specifiers's onto a stack for
3665 // serialization in reverse order.
3666 while (NNS) {
3667 NestedNames.push_back(NNS);
3668 NNS = NNS.getPrefix();
3669 }
3670
3671 Record.push_back(NestedNames.size());
3672 while(!NestedNames.empty()) {
3673 NNS = NestedNames.pop_back_val();
3674 NestedNameSpecifier::SpecifierKind Kind
3675 = NNS.getNestedNameSpecifier()->getKind();
3676 Record.push_back(Kind);
3677 switch (Kind) {
3678 case NestedNameSpecifier::Identifier:
3679 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
3680 AddSourceRange(NNS.getLocalSourceRange(), Record);
3681 break;
3682
3683 case NestedNameSpecifier::Namespace:
3684 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
3685 AddSourceRange(NNS.getLocalSourceRange(), Record);
3686 break;
3687
3688 case NestedNameSpecifier::NamespaceAlias:
3689 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
3690 AddSourceRange(NNS.getLocalSourceRange(), Record);
3691 break;
3692
3693 case NestedNameSpecifier::TypeSpec:
3694 case NestedNameSpecifier::TypeSpecWithTemplate:
3695 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3696 AddTypeLoc(NNS.getTypeLoc(), Record);
3697 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3698 break;
3699
3700 case NestedNameSpecifier::Global:
3701 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3702 break;
3703 }
3704 }
3705 }
3706
AddTemplateName(TemplateName Name,RecordDataImpl & Record)3707 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
3708 TemplateName::NameKind Kind = Name.getKind();
3709 Record.push_back(Kind);
3710 switch (Kind) {
3711 case TemplateName::Template:
3712 AddDeclRef(Name.getAsTemplateDecl(), Record);
3713 break;
3714
3715 case TemplateName::OverloadedTemplate: {
3716 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
3717 Record.push_back(OvT->size());
3718 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
3719 I != E; ++I)
3720 AddDeclRef(*I, Record);
3721 break;
3722 }
3723
3724 case TemplateName::QualifiedTemplate: {
3725 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
3726 AddNestedNameSpecifier(QualT->getQualifier(), Record);
3727 Record.push_back(QualT->hasTemplateKeyword());
3728 AddDeclRef(QualT->getTemplateDecl(), Record);
3729 break;
3730 }
3731
3732 case TemplateName::DependentTemplate: {
3733 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
3734 AddNestedNameSpecifier(DepT->getQualifier(), Record);
3735 Record.push_back(DepT->isIdentifier());
3736 if (DepT->isIdentifier())
3737 AddIdentifierRef(DepT->getIdentifier(), Record);
3738 else
3739 Record.push_back(DepT->getOperator());
3740 break;
3741 }
3742
3743 case TemplateName::SubstTemplateTemplateParm: {
3744 SubstTemplateTemplateParmStorage *subst
3745 = Name.getAsSubstTemplateTemplateParm();
3746 AddDeclRef(subst->getParameter(), Record);
3747 AddTemplateName(subst->getReplacement(), Record);
3748 break;
3749 }
3750
3751 case TemplateName::SubstTemplateTemplateParmPack: {
3752 SubstTemplateTemplateParmPackStorage *SubstPack
3753 = Name.getAsSubstTemplateTemplateParmPack();
3754 AddDeclRef(SubstPack->getParameterPack(), Record);
3755 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
3756 break;
3757 }
3758 }
3759 }
3760
AddTemplateArgument(const TemplateArgument & Arg,RecordDataImpl & Record)3761 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
3762 RecordDataImpl &Record) {
3763 Record.push_back(Arg.getKind());
3764 switch (Arg.getKind()) {
3765 case TemplateArgument::Null:
3766 break;
3767 case TemplateArgument::Type:
3768 AddTypeRef(Arg.getAsType(), Record);
3769 break;
3770 case TemplateArgument::Declaration:
3771 AddDeclRef(Arg.getAsDecl(), Record);
3772 break;
3773 case TemplateArgument::Integral:
3774 AddAPSInt(*Arg.getAsIntegral(), Record);
3775 AddTypeRef(Arg.getIntegralType(), Record);
3776 break;
3777 case TemplateArgument::Template:
3778 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3779 break;
3780 case TemplateArgument::TemplateExpansion:
3781 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3782 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
3783 Record.push_back(*NumExpansions + 1);
3784 else
3785 Record.push_back(0);
3786 break;
3787 case TemplateArgument::Expression:
3788 AddStmt(Arg.getAsExpr());
3789 break;
3790 case TemplateArgument::Pack:
3791 Record.push_back(Arg.pack_size());
3792 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
3793 I != E; ++I)
3794 AddTemplateArgument(*I, Record);
3795 break;
3796 }
3797 }
3798
3799 void
AddTemplateParameterList(const TemplateParameterList * TemplateParams,RecordDataImpl & Record)3800 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
3801 RecordDataImpl &Record) {
3802 assert(TemplateParams && "No TemplateParams!");
3803 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
3804 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
3805 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
3806 Record.push_back(TemplateParams->size());
3807 for (TemplateParameterList::const_iterator
3808 P = TemplateParams->begin(), PEnd = TemplateParams->end();
3809 P != PEnd; ++P)
3810 AddDeclRef(*P, Record);
3811 }
3812
3813 /// \brief Emit a template argument list.
3814 void
AddTemplateArgumentList(const TemplateArgumentList * TemplateArgs,RecordDataImpl & Record)3815 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
3816 RecordDataImpl &Record) {
3817 assert(TemplateArgs && "No TemplateArgs!");
3818 Record.push_back(TemplateArgs->size());
3819 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
3820 AddTemplateArgument(TemplateArgs->get(i), Record);
3821 }
3822
3823
3824 void
AddUnresolvedSet(const UnresolvedSetImpl & Set,RecordDataImpl & Record)3825 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
3826 Record.push_back(Set.size());
3827 for (UnresolvedSetImpl::const_iterator
3828 I = Set.begin(), E = Set.end(); I != E; ++I) {
3829 AddDeclRef(I.getDecl(), Record);
3830 Record.push_back(I.getAccess());
3831 }
3832 }
3833
AddCXXBaseSpecifier(const CXXBaseSpecifier & Base,RecordDataImpl & Record)3834 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
3835 RecordDataImpl &Record) {
3836 Record.push_back(Base.isVirtual());
3837 Record.push_back(Base.isBaseOfClass());
3838 Record.push_back(Base.getAccessSpecifierAsWritten());
3839 Record.push_back(Base.getInheritConstructors());
3840 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
3841 AddSourceRange(Base.getSourceRange(), Record);
3842 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
3843 : SourceLocation(),
3844 Record);
3845 }
3846
FlushCXXBaseSpecifiers()3847 void ASTWriter::FlushCXXBaseSpecifiers() {
3848 RecordData Record;
3849 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
3850 Record.clear();
3851
3852 // Record the offset of this base-specifier set.
3853 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - FirstCXXBaseSpecifiersID;
3854 if (Index == CXXBaseSpecifiersOffsets.size())
3855 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
3856 else {
3857 if (Index > CXXBaseSpecifiersOffsets.size())
3858 CXXBaseSpecifiersOffsets.resize(Index + 1);
3859 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
3860 }
3861
3862 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
3863 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
3864 Record.push_back(BEnd - B);
3865 for (; B != BEnd; ++B)
3866 AddCXXBaseSpecifier(*B, Record);
3867 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
3868
3869 // Flush any expressions that were written as part of the base specifiers.
3870 FlushStmts();
3871 }
3872
3873 CXXBaseSpecifiersToWrite.clear();
3874 }
3875
AddCXXCtorInitializers(const CXXCtorInitializer * const * CtorInitializers,unsigned NumCtorInitializers,RecordDataImpl & Record)3876 void ASTWriter::AddCXXCtorInitializers(
3877 const CXXCtorInitializer * const *CtorInitializers,
3878 unsigned NumCtorInitializers,
3879 RecordDataImpl &Record) {
3880 Record.push_back(NumCtorInitializers);
3881 for (unsigned i=0; i != NumCtorInitializers; ++i) {
3882 const CXXCtorInitializer *Init = CtorInitializers[i];
3883
3884 if (Init->isBaseInitializer()) {
3885 Record.push_back(CTOR_INITIALIZER_BASE);
3886 AddTypeSourceInfo(Init->getBaseClassInfo(), Record);
3887 Record.push_back(Init->isBaseVirtual());
3888 } else if (Init->isDelegatingInitializer()) {
3889 Record.push_back(CTOR_INITIALIZER_DELEGATING);
3890 AddDeclRef(Init->getTargetConstructor(), Record);
3891 } else if (Init->isMemberInitializer()){
3892 Record.push_back(CTOR_INITIALIZER_MEMBER);
3893 AddDeclRef(Init->getMember(), Record);
3894 } else {
3895 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
3896 AddDeclRef(Init->getIndirectMember(), Record);
3897 }
3898
3899 AddSourceLocation(Init->getMemberLocation(), Record);
3900 AddStmt(Init->getInit());
3901 AddSourceLocation(Init->getLParenLoc(), Record);
3902 AddSourceLocation(Init->getRParenLoc(), Record);
3903 Record.push_back(Init->isWritten());
3904 if (Init->isWritten()) {
3905 Record.push_back(Init->getSourceOrder());
3906 } else {
3907 Record.push_back(Init->getNumArrayIndices());
3908 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
3909 AddDeclRef(Init->getArrayIndex(i), Record);
3910 }
3911 }
3912 }
3913
AddCXXDefinitionData(const CXXRecordDecl * D,RecordDataImpl & Record)3914 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
3915 assert(D->DefinitionData);
3916 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
3917 Record.push_back(Data.UserDeclaredConstructor);
3918 Record.push_back(Data.UserDeclaredCopyConstructor);
3919 Record.push_back(Data.UserDeclaredCopyAssignment);
3920 Record.push_back(Data.UserDeclaredDestructor);
3921 Record.push_back(Data.Aggregate);
3922 Record.push_back(Data.PlainOldData);
3923 Record.push_back(Data.Empty);
3924 Record.push_back(Data.Polymorphic);
3925 Record.push_back(Data.Abstract);
3926 Record.push_back(Data.IsStandardLayout);
3927 Record.push_back(Data.HasNoNonEmptyBases);
3928 Record.push_back(Data.HasPrivateFields);
3929 Record.push_back(Data.HasProtectedFields);
3930 Record.push_back(Data.HasPublicFields);
3931 Record.push_back(Data.HasMutableFields);
3932 Record.push_back(Data.HasTrivialDefaultConstructor);
3933 Record.push_back(Data.HasConstExprNonCopyMoveConstructor);
3934 Record.push_back(Data.HasTrivialCopyConstructor);
3935 Record.push_back(Data.HasTrivialMoveConstructor);
3936 Record.push_back(Data.HasTrivialCopyAssignment);
3937 Record.push_back(Data.HasTrivialMoveAssignment);
3938 Record.push_back(Data.HasTrivialDestructor);
3939 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
3940 Record.push_back(Data.ComputedVisibleConversions);
3941 Record.push_back(Data.UserProvidedDefaultConstructor);
3942 Record.push_back(Data.DeclaredDefaultConstructor);
3943 Record.push_back(Data.DeclaredCopyConstructor);
3944 Record.push_back(Data.DeclaredCopyAssignment);
3945 Record.push_back(Data.DeclaredDestructor);
3946
3947 Record.push_back(Data.NumBases);
3948 if (Data.NumBases > 0)
3949 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
3950 Record);
3951
3952 // FIXME: Make VBases lazily computed when needed to avoid storing them.
3953 Record.push_back(Data.NumVBases);
3954 if (Data.NumVBases > 0)
3955 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
3956 Record);
3957
3958 AddUnresolvedSet(Data.Conversions, Record);
3959 AddUnresolvedSet(Data.VisibleConversions, Record);
3960 // Data.Definition is the owning decl, no need to write it.
3961 AddDeclRef(Data.FirstFriend, Record);
3962 }
3963
ReaderInitialized(ASTReader * Reader)3964 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
3965 assert(Reader && "Cannot remove chain");
3966 assert(!Chain && "Cannot replace chain");
3967 assert(FirstDeclID == NextDeclID &&
3968 FirstTypeID == NextTypeID &&
3969 FirstIdentID == NextIdentID &&
3970 FirstSelectorID == NextSelectorID &&
3971 FirstMacroID == NextMacroID &&
3972 FirstCXXBaseSpecifiersID == NextCXXBaseSpecifiersID &&
3973 "Setting chain after writing has started.");
3974
3975 Chain = Reader;
3976
3977 FirstDeclID += Chain->getTotalNumDecls();
3978 FirstTypeID += Chain->getTotalNumTypes();
3979 FirstIdentID += Chain->getTotalNumIdentifiers();
3980 FirstSelectorID += Chain->getTotalNumSelectors();
3981 FirstMacroID += Chain->getTotalNumMacroDefinitions();
3982 FirstCXXBaseSpecifiersID += Chain->getTotalNumCXXBaseSpecifiers();
3983 NextDeclID = FirstDeclID;
3984 NextTypeID = FirstTypeID;
3985 NextIdentID = FirstIdentID;
3986 NextSelectorID = FirstSelectorID;
3987 NextMacroID = FirstMacroID;
3988 NextCXXBaseSpecifiersID = FirstCXXBaseSpecifiersID;
3989 }
3990
IdentifierRead(IdentID ID,IdentifierInfo * II)3991 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
3992 IdentifierIDs[II] = ID;
3993 if (II->hasMacroDefinition())
3994 DeserializedMacroNames.push_back(II);
3995 }
3996
TypeRead(TypeIdx Idx,QualType T)3997 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
3998 // Always take the highest-numbered type index. This copes with an interesting
3999 // case for chained AST writing where we schedule writing the type and then,
4000 // later, deserialize the type from another AST. In this case, we want to
4001 // keep the higher-numbered entry so that we can properly write it out to
4002 // the AST file.
4003 TypeIdx &StoredIdx = TypeIdxs[T];
4004 if (Idx.getIndex() >= StoredIdx.getIndex())
4005 StoredIdx = Idx;
4006 }
4007
DeclRead(DeclID ID,const Decl * D)4008 void ASTWriter::DeclRead(DeclID ID, const Decl *D) {
4009 DeclIDs[D] = ID;
4010 }
4011
SelectorRead(SelectorID ID,Selector S)4012 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
4013 SelectorIDs[S] = ID;
4014 }
4015
MacroDefinitionRead(serialization::MacroID ID,MacroDefinition * MD)4016 void ASTWriter::MacroDefinitionRead(serialization::MacroID ID,
4017 MacroDefinition *MD) {
4018 MacroDefinitions[MD] = ID;
4019 }
4020
CompletedTagDefinition(const TagDecl * D)4021 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
4022 assert(D->isDefinition());
4023 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
4024 // We are interested when a PCH decl is modified.
4025 if (RD->getPCHLevel() > 0) {
4026 // A forward reference was mutated into a definition. Rewrite it.
4027 // FIXME: This happens during template instantiation, should we
4028 // have created a new definition decl instead ?
4029 RewriteDecl(RD);
4030 }
4031
4032 for (CXXRecordDecl::redecl_iterator
4033 I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) {
4034 CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I);
4035 if (Redecl == RD)
4036 continue;
4037
4038 // We are interested when a PCH decl is modified.
4039 if (Redecl->getPCHLevel() > 0) {
4040 UpdateRecord &Record = DeclUpdates[Redecl];
4041 Record.push_back(UPD_CXX_SET_DEFINITIONDATA);
4042 assert(Redecl->DefinitionData);
4043 assert(Redecl->DefinitionData->Definition == D);
4044 AddDeclRef(D, Record); // the DefinitionDecl
4045 }
4046 }
4047 }
4048 }
AddedVisibleDecl(const DeclContext * DC,const Decl * D)4049 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
4050 // TU and namespaces are handled elsewhere.
4051 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
4052 return;
4053
4054 if (!(D->getPCHLevel() == 0 && cast<Decl>(DC)->getPCHLevel() > 0))
4055 return; // Not a source decl added to a DeclContext from PCH.
4056
4057 AddUpdatedDeclContext(DC);
4058 }
4059
AddedCXXImplicitMember(const CXXRecordDecl * RD,const Decl * D)4060 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
4061 assert(D->isImplicit());
4062 if (!(D->getPCHLevel() == 0 && RD->getPCHLevel() > 0))
4063 return; // Not a source member added to a class from PCH.
4064 if (!isa<CXXMethodDecl>(D))
4065 return; // We are interested in lazily declared implicit methods.
4066
4067 // A decl coming from PCH was modified.
4068 assert(RD->isDefinition());
4069 UpdateRecord &Record = DeclUpdates[RD];
4070 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
4071 AddDeclRef(D, Record);
4072 }
4073
AddedCXXTemplateSpecialization(const ClassTemplateDecl * TD,const ClassTemplateSpecializationDecl * D)4074 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
4075 const ClassTemplateSpecializationDecl *D) {
4076 // The specializations set is kept in the canonical template.
4077 TD = TD->getCanonicalDecl();
4078 if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0))
4079 return; // Not a source specialization added to a template from PCH.
4080
4081 UpdateRecord &Record = DeclUpdates[TD];
4082 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4083 AddDeclRef(D, Record);
4084 }
4085
AddedCXXTemplateSpecialization(const FunctionTemplateDecl * TD,const FunctionDecl * D)4086 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
4087 const FunctionDecl *D) {
4088 // The specializations set is kept in the canonical template.
4089 TD = TD->getCanonicalDecl();
4090 if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0))
4091 return; // Not a source specialization added to a template from PCH.
4092
4093 UpdateRecord &Record = DeclUpdates[TD];
4094 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4095 AddDeclRef(D, Record);
4096 }
4097
CompletedImplicitDefinition(const FunctionDecl * D)4098 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
4099 if (D->getPCHLevel() == 0)
4100 return; // Declaration not imported from PCH.
4101
4102 // Implicit decl from a PCH was defined.
4103 // FIXME: Should implicit definition be a separate FunctionDecl?
4104 RewriteDecl(D);
4105 }
4106
StaticDataMemberInstantiated(const VarDecl * D)4107 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
4108 if (D->getPCHLevel() == 0)
4109 return;
4110
4111 // Since the actual instantiation is delayed, this really means that we need
4112 // to update the instantiation location.
4113 UpdateRecord &Record = DeclUpdates[D];
4114 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER);
4115 AddSourceLocation(
4116 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record);
4117 }
4118
~ASTSerializationListener()4119 ASTSerializationListener::~ASTSerializationListener() { }
4120