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