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