blob: 2df90da2ef9e47692e50b14b1a706fe9a0272232 [file] [log] [blame]
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001//===-- ASTReader.cpp - AST File Reader -----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000019#include "clang/AST/ASTMutationListener.h"
20#include "clang/AST/ASTUnresolvedSet.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclGroup.h"
24#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/NestedNameSpecifier.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000029#include "clang/AST/RawCommentList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/AST/Type.h"
31#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000032#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/CommentOptions.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000034#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000035#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000037#include "clang/Basic/FileSystemOptions.h"
38#include "clang/Basic/LangOptions.h"
39#include "clang/Basic/ObjCRuntime.h"
40#include "clang/Basic/OperatorKinds.h"
41#include "clang/Basic/Sanitizers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000042#include "clang/Basic/SourceManager.h"
43#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000044#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Basic/TargetInfo.h"
46#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000047#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "clang/Basic/Version.h"
49#include "clang/Basic/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000050#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000051#include "clang/Lex/HeaderSearch.h"
52#include "clang/Lex/HeaderSearchOptions.h"
53#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000054#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "clang/Lex/PreprocessingRecord.h"
56#include "clang/Lex/Preprocessor.h"
57#include "clang/Lex/PreprocessorOptions.h"
58#include "clang/Sema/Scope.h"
59#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Sema/Weak.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000061#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000062#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000063#include "clang/Serialization/ModuleManager.h"
64#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "llvm/ADT/APFloat.h"
66#include "llvm/ADT/APInt.h"
67#include "llvm/ADT/APSInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000068#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000069#include "llvm/ADT/SmallString.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000070#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000071#include "llvm/ADT/Triple.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000072#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000073#include "llvm/Support/Compression.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000074#include "llvm/Support/Compiler.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000075#include "llvm/Support/ErrorHandling.h"
76#include "llvm/Support/FileSystem.h"
77#include "llvm/Support/MemoryBuffer.h"
78#include "llvm/Support/Path.h"
79#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000080#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000081#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000082#include <cassert>
83#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +000084#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000085#include <cstring>
86#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +000087#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000088#include <limits>
89#include <map>
90#include <memory>
91#include <new>
92#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000093#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000094#include <tuple>
95#include <utility>
96#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +000097
98using namespace clang;
99using namespace clang::serialization;
100using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000101using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000102
Ben Langmuircb69b572014-03-07 06:40:32 +0000103//===----------------------------------------------------------------------===//
104// ChainedASTReaderListener implementation
105//===----------------------------------------------------------------------===//
106
107bool
108ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
109 return First->ReadFullVersionInformation(FullVersion) ||
110 Second->ReadFullVersionInformation(FullVersion);
111}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000112
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000113void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
114 First->ReadModuleName(ModuleName);
115 Second->ReadModuleName(ModuleName);
116}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000117
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000118void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
119 First->ReadModuleMapFile(ModuleMapPath);
120 Second->ReadModuleMapFile(ModuleMapPath);
121}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000122
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000123bool
124ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
125 bool Complain,
126 bool AllowCompatibleDifferences) {
127 return First->ReadLanguageOptions(LangOpts, Complain,
128 AllowCompatibleDifferences) ||
129 Second->ReadLanguageOptions(LangOpts, Complain,
130 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000131}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000132
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000133bool ChainedASTReaderListener::ReadTargetOptions(
134 const TargetOptions &TargetOpts, bool Complain,
135 bool AllowCompatibleDifferences) {
136 return First->ReadTargetOptions(TargetOpts, Complain,
137 AllowCompatibleDifferences) ||
138 Second->ReadTargetOptions(TargetOpts, Complain,
139 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000140}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000141
Ben Langmuircb69b572014-03-07 06:40:32 +0000142bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000143 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000144 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
145 Second->ReadDiagnosticOptions(DiagOpts, Complain);
146}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000147
Ben Langmuircb69b572014-03-07 06:40:32 +0000148bool
149ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
150 bool Complain) {
151 return First->ReadFileSystemOptions(FSOpts, Complain) ||
152 Second->ReadFileSystemOptions(FSOpts, Complain);
153}
154
155bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000156 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
157 bool Complain) {
158 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
159 Complain) ||
160 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
161 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000162}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000163
Ben Langmuircb69b572014-03-07 06:40:32 +0000164bool ChainedASTReaderListener::ReadPreprocessorOptions(
165 const PreprocessorOptions &PPOpts, bool Complain,
166 std::string &SuggestedPredefines) {
167 return First->ReadPreprocessorOptions(PPOpts, Complain,
168 SuggestedPredefines) ||
169 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
170}
171void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
172 unsigned Value) {
173 First->ReadCounter(M, Value);
174 Second->ReadCounter(M, Value);
175}
176bool ChainedASTReaderListener::needsInputFileVisitation() {
177 return First->needsInputFileVisitation() ||
178 Second->needsInputFileVisitation();
179}
180bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
181 return First->needsSystemInputFileVisitation() ||
182 Second->needsSystemInputFileVisitation();
183}
Richard Smith216a3bd2015-08-13 17:57:10 +0000184void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
185 ModuleKind Kind) {
186 First->visitModuleFile(Filename, Kind);
187 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000188}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000189
Ben Langmuircb69b572014-03-07 06:40:32 +0000190bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000191 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000192 bool isOverridden,
193 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000194 bool Continue = false;
195 if (First->needsInputFileVisitation() &&
196 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000197 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
198 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000199 if (Second->needsInputFileVisitation() &&
200 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000201 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
202 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000203 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000204}
205
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000206void ChainedASTReaderListener::readModuleFileExtension(
207 const ModuleFileExtensionMetadata &Metadata) {
208 First->readModuleFileExtension(Metadata);
209 Second->readModuleFileExtension(Metadata);
210}
211
Guy Benyei11169dd2012-12-18 14:30:41 +0000212//===----------------------------------------------------------------------===//
213// PCH validator implementation
214//===----------------------------------------------------------------------===//
215
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000216ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000217
218/// \brief Compare the given set of language options against an existing set of
219/// language options.
220///
221/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000222/// \param AllowCompatibleDifferences If true, differences between compatible
223/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000224///
225/// \returns true if the languagae options mis-match, false otherwise.
226static bool checkLanguageOptions(const LangOptions &LangOpts,
227 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000228 DiagnosticsEngine *Diags,
229 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000230#define LANGOPT(Name, Bits, Default, Description) \
231 if (ExistingLangOpts.Name != LangOpts.Name) { \
232 if (Diags) \
233 Diags->Report(diag::err_pch_langopt_mismatch) \
234 << Description << LangOpts.Name << ExistingLangOpts.Name; \
235 return true; \
236 }
237
238#define VALUE_LANGOPT(Name, Bits, Default, Description) \
239 if (ExistingLangOpts.Name != LangOpts.Name) { \
240 if (Diags) \
241 Diags->Report(diag::err_pch_langopt_value_mismatch) \
242 << Description; \
243 return true; \
244 }
245
246#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
247 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
248 if (Diags) \
249 Diags->Report(diag::err_pch_langopt_value_mismatch) \
250 << Description; \
251 return true; \
252 }
253
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000254#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
255 if (!AllowCompatibleDifferences) \
256 LANGOPT(Name, Bits, Default, Description)
257
258#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
259 if (!AllowCompatibleDifferences) \
260 ENUM_LANGOPT(Name, Bits, Default, Description)
261
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000262#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
263 if (!AllowCompatibleDifferences) \
264 VALUE_LANGOPT(Name, Bits, Default, Description)
265
Guy Benyei11169dd2012-12-18 14:30:41 +0000266#define BENIGN_LANGOPT(Name, Bits, Default, Description)
267#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000268#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000269#include "clang/Basic/LangOptions.def"
270
Ben Langmuircd98cb72015-06-23 18:20:18 +0000271 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
272 if (Diags)
273 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
274 return true;
275 }
276
Guy Benyei11169dd2012-12-18 14:30:41 +0000277 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
278 if (Diags)
279 Diags->Report(diag::err_pch_langopt_value_mismatch)
280 << "target Objective-C runtime";
281 return true;
282 }
283
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000284 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
285 LangOpts.CommentOpts.BlockCommandNames) {
286 if (Diags)
287 Diags->Report(diag::err_pch_langopt_value_mismatch)
288 << "block command names";
289 return true;
290 }
291
Guy Benyei11169dd2012-12-18 14:30:41 +0000292 return false;
293}
294
295/// \brief Compare the given set of target options against an existing set of
296/// target options.
297///
298/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
299///
300/// \returns true if the target options mis-match, false otherwise.
301static bool checkTargetOptions(const TargetOptions &TargetOpts,
302 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000303 DiagnosticsEngine *Diags,
304 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000305#define CHECK_TARGET_OPT(Field, Name) \
306 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
307 if (Diags) \
308 Diags->Report(diag::err_pch_targetopt_mismatch) \
309 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
310 return true; \
311 }
312
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000313 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000314 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000315 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000316
317 // We can tolerate different CPUs in many cases, notably when one CPU
318 // supports a strict superset of another. When allowing compatible
319 // differences skip this check.
320 if (!AllowCompatibleDifferences)
321 CHECK_TARGET_OPT(CPU, "target CPU");
322
Guy Benyei11169dd2012-12-18 14:30:41 +0000323#undef CHECK_TARGET_OPT
324
325 // Compare feature sets.
326 SmallVector<StringRef, 4> ExistingFeatures(
327 ExistingTargetOpts.FeaturesAsWritten.begin(),
328 ExistingTargetOpts.FeaturesAsWritten.end());
329 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
330 TargetOpts.FeaturesAsWritten.end());
331 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
332 std::sort(ReadFeatures.begin(), ReadFeatures.end());
333
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000334 // We compute the set difference in both directions explicitly so that we can
335 // diagnose the differences differently.
336 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
337 std::set_difference(
338 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
339 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
340 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
341 ExistingFeatures.begin(), ExistingFeatures.end(),
342 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000343
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000344 // If we are allowing compatible differences and the read feature set is
345 // a strict subset of the existing feature set, there is nothing to diagnose.
346 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
347 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000348
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000349 if (Diags) {
350 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000351 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000352 << /* is-existing-feature */ false << Feature;
353 for (StringRef Feature : UnmatchedExistingFeatures)
354 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
355 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000356 }
357
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000358 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000359}
360
361bool
362PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000363 bool Complain,
364 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000365 const LangOptions &ExistingLangOpts = PP.getLangOpts();
366 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000367 Complain ? &Reader.Diags : nullptr,
368 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000369}
370
371bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000372 bool Complain,
373 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000374 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
375 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000376 Complain ? &Reader.Diags : nullptr,
377 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000378}
379
380namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000381
Guy Benyei11169dd2012-12-18 14:30:41 +0000382 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
383 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000384 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
385 DeclsMap;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000386
387} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000388
Ben Langmuirb92de022014-04-29 16:25:26 +0000389static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
390 DiagnosticsEngine &Diags,
391 bool Complain) {
392 typedef DiagnosticsEngine::Level Level;
393
394 // Check current mappings for new -Werror mappings, and the stored mappings
395 // for cases that were explicitly mapped to *not* be errors that are now
396 // errors because of options like -Werror.
397 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
398
399 for (DiagnosticsEngine *MappingSource : MappingSources) {
400 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
401 diag::kind DiagID = DiagIDMappingPair.first;
402 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
403 if (CurLevel < DiagnosticsEngine::Error)
404 continue; // not significant
405 Level StoredLevel =
406 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
407 if (StoredLevel < DiagnosticsEngine::Error) {
408 if (Complain)
409 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
410 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
411 return true;
412 }
413 }
414 }
415
416 return false;
417}
418
Alp Tokerac4e8e52014-06-22 21:58:33 +0000419static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
420 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
421 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
422 return true;
423 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000424}
425
426static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
427 DiagnosticsEngine &Diags,
428 bool IsSystem, bool Complain) {
429 // Top-level options
430 if (IsSystem) {
431 if (Diags.getSuppressSystemWarnings())
432 return false;
433 // If -Wsystem-headers was not enabled before, be conservative
434 if (StoredDiags.getSuppressSystemWarnings()) {
435 if (Complain)
436 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
437 return true;
438 }
439 }
440
441 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
442 if (Complain)
443 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
444 return true;
445 }
446
447 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
448 !StoredDiags.getEnableAllWarnings()) {
449 if (Complain)
450 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
451 return true;
452 }
453
454 if (isExtHandlingFromDiagsError(Diags) &&
455 !isExtHandlingFromDiagsError(StoredDiags)) {
456 if (Complain)
457 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
458 return true;
459 }
460
461 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
462}
463
464bool PCHValidator::ReadDiagnosticOptions(
465 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
466 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
467 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
468 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000469 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000470 // This should never fail, because we would have processed these options
471 // before writing them to an ASTFile.
472 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
473
474 ModuleManager &ModuleMgr = Reader.getModuleManager();
475 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
476
477 // If the original import came from a file explicitly generated by the user,
478 // don't check the diagnostic mappings.
479 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000480 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000481 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
482 // the transitive closure of its imports, since unrelated modules cannot be
483 // imported until after this module finishes validation.
484 ModuleFile *TopImport = *ModuleMgr.rbegin();
485 while (!TopImport->ImportedBy.empty())
486 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000487 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000488 return false;
489
490 StringRef ModuleName = TopImport->ModuleName;
491 assert(!ModuleName.empty() && "diagnostic options read before module name");
492
493 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
494 assert(M && "missing module");
495
496 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
497 // contains the union of their flags.
498 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
499}
500
Guy Benyei11169dd2012-12-18 14:30:41 +0000501/// \brief Collect the macro definitions provided by the given preprocessor
502/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000503static void
504collectMacroDefinitions(const PreprocessorOptions &PPOpts,
505 MacroDefinitionsMap &Macros,
506 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000507 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
508 StringRef Macro = PPOpts.Macros[I].first;
509 bool IsUndef = PPOpts.Macros[I].second;
510
511 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
512 StringRef MacroName = MacroPair.first;
513 StringRef MacroBody = MacroPair.second;
514
515 // For an #undef'd macro, we only care about the name.
516 if (IsUndef) {
517 if (MacroNames && !Macros.count(MacroName))
518 MacroNames->push_back(MacroName);
519
520 Macros[MacroName] = std::make_pair("", true);
521 continue;
522 }
523
524 // For a #define'd macro, figure out the actual definition.
525 if (MacroName.size() == Macro.size())
526 MacroBody = "1";
527 else {
528 // Note: GCC drops anything following an end-of-line character.
529 StringRef::size_type End = MacroBody.find_first_of("\n\r");
530 MacroBody = MacroBody.substr(0, End);
531 }
532
533 if (MacroNames && !Macros.count(MacroName))
534 MacroNames->push_back(MacroName);
535 Macros[MacroName] = std::make_pair(MacroBody, false);
536 }
537}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000538
Guy Benyei11169dd2012-12-18 14:30:41 +0000539/// \brief Check the preprocessor options deserialized from the control block
540/// against the preprocessor options in an existing preprocessor.
541///
542/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000543/// \param Validate If true, validate preprocessor options. If false, allow
544/// macros defined by \p ExistingPPOpts to override those defined by
545/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000546static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
547 const PreprocessorOptions &ExistingPPOpts,
548 DiagnosticsEngine *Diags,
549 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000550 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000551 const LangOptions &LangOpts,
552 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000553 // Check macro definitions.
554 MacroDefinitionsMap ASTFileMacros;
555 collectMacroDefinitions(PPOpts, ASTFileMacros);
556 MacroDefinitionsMap ExistingMacros;
557 SmallVector<StringRef, 4> ExistingMacroNames;
558 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
559
560 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
561 // Dig out the macro definition in the existing preprocessor options.
562 StringRef MacroName = ExistingMacroNames[I];
563 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
564
565 // Check whether we know anything about this macro name or not.
566 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
567 = ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000568 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 // FIXME: Check whether this identifier was referenced anywhere in the
570 // AST file. If so, we should reject the AST file. Unfortunately, this
571 // information isn't in the control block. What shall we do about it?
572
573 if (Existing.second) {
574 SuggestedPredefines += "#undef ";
575 SuggestedPredefines += MacroName.str();
576 SuggestedPredefines += '\n';
577 } else {
578 SuggestedPredefines += "#define ";
579 SuggestedPredefines += MacroName.str();
580 SuggestedPredefines += ' ';
581 SuggestedPredefines += Existing.first.str();
582 SuggestedPredefines += '\n';
583 }
584 continue;
585 }
586
587 // If the macro was defined in one but undef'd in the other, we have a
588 // conflict.
589 if (Existing.second != Known->second.second) {
590 if (Diags) {
591 Diags->Report(diag::err_pch_macro_def_undef)
592 << MacroName << Known->second.second;
593 }
594 return true;
595 }
596
597 // If the macro was #undef'd in both, or if the macro bodies are identical,
598 // it's fine.
599 if (Existing.second || Existing.first == Known->second.first)
600 continue;
601
602 // The macro bodies differ; complain.
603 if (Diags) {
604 Diags->Report(diag::err_pch_macro_def_conflict)
605 << MacroName << Known->second.first << Existing.first;
606 }
607 return true;
608 }
609
610 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000611 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000612 if (Diags) {
613 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
614 }
615 return true;
616 }
617
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000618 // Detailed record is important since it is used for the module cache hash.
619 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000620 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000621 if (Diags) {
622 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
623 }
624 return true;
625 }
626
Guy Benyei11169dd2012-12-18 14:30:41 +0000627 // Compute the #include and #include_macros lines we need.
628 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
629 StringRef File = ExistingPPOpts.Includes[I];
630 if (File == ExistingPPOpts.ImplicitPCHInclude)
631 continue;
632
633 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
634 != PPOpts.Includes.end())
635 continue;
636
637 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000638 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 SuggestedPredefines += "\"\n";
640 }
641
642 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
643 StringRef File = ExistingPPOpts.MacroIncludes[I];
644 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
645 File)
646 != PPOpts.MacroIncludes.end())
647 continue;
648
649 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000650 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000651 SuggestedPredefines += "\"\n##\n";
652 }
653
654 return false;
655}
656
657bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
658 bool Complain,
659 std::string &SuggestedPredefines) {
660 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
661
662 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000663 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000664 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000665 SuggestedPredefines,
666 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000667}
668
Yaxun Liu43712e02016-09-07 18:40:20 +0000669bool SimpleASTReaderListener::ReadPreprocessorOptions(
670 const PreprocessorOptions &PPOpts,
671 bool Complain,
672 std::string &SuggestedPredefines) {
673 return checkPreprocessorOptions(PPOpts,
674 PP.getPreprocessorOpts(),
675 nullptr,
676 PP.getFileManager(),
677 SuggestedPredefines,
678 PP.getLangOpts(),
679 false);
680}
681
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000682/// Check the header search options deserialized from the control block
683/// against the header search options in an existing preprocessor.
684///
685/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
686static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
687 StringRef SpecificModuleCachePath,
688 StringRef ExistingModuleCachePath,
689 DiagnosticsEngine *Diags,
690 const LangOptions &LangOpts) {
691 if (LangOpts.Modules) {
692 if (SpecificModuleCachePath != ExistingModuleCachePath) {
693 if (Diags)
694 Diags->Report(diag::err_pch_modulecache_mismatch)
695 << SpecificModuleCachePath << ExistingModuleCachePath;
696 return true;
697 }
698 }
699
700 return false;
701}
702
703bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
704 StringRef SpecificModuleCachePath,
705 bool Complain) {
706 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
707 PP.getHeaderSearchInfo().getModuleCachePath(),
708 Complain ? &Reader.Diags : nullptr,
709 PP.getLangOpts());
710}
711
Guy Benyei11169dd2012-12-18 14:30:41 +0000712void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
713 PP.setCounterValue(Value);
714}
715
716//===----------------------------------------------------------------------===//
717// AST reader implementation
718//===----------------------------------------------------------------------===//
719
Nico Weber824285e2014-05-08 04:26:47 +0000720void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
721 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000722 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000723 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000724}
725
Guy Benyei11169dd2012-12-18 14:30:41 +0000726unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
727 return serialization::ComputeHash(Sel);
728}
729
Guy Benyei11169dd2012-12-18 14:30:41 +0000730std::pair<unsigned, unsigned>
731ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000732 using namespace llvm::support;
733 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
734 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000735 return std::make_pair(KeyLen, DataLen);
736}
737
738ASTSelectorLookupTrait::internal_key_type
739ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000740 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000741 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000742 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
743 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
744 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 if (N == 0)
746 return SelTable.getNullarySelector(FirstII);
747 else if (N == 1)
748 return SelTable.getUnarySelector(FirstII);
749
750 SmallVector<IdentifierInfo *, 16> Args;
751 Args.push_back(FirstII);
752 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000753 Args.push_back(Reader.getLocalIdentifier(
754 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000755
756 return SelTable.getSelector(N, Args.data());
757}
758
759ASTSelectorLookupTrait::data_type
760ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
761 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000762 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000763
764 data_type Result;
765
Justin Bogner57ba0b22014-03-28 22:03:24 +0000766 Result.ID = Reader.getGlobalSelectorID(
767 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000768 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
769 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
770 Result.InstanceBits = FullInstanceBits & 0x3;
771 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
772 Result.FactoryBits = FullFactoryBits & 0x3;
773 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
774 unsigned NumInstanceMethods = FullInstanceBits >> 3;
775 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000776
777 // Load instance methods
778 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000779 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
780 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 Result.Instance.push_back(Method);
782 }
783
784 // Load factory methods
785 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000786 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
787 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000788 Result.Factory.push_back(Method);
789 }
790
791 return Result;
792}
793
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000794unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
795 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000796}
797
798std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000799ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000800 using namespace llvm::support;
801 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
802 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000803 return std::make_pair(KeyLen, DataLen);
804}
805
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000806ASTIdentifierLookupTraitBase::internal_key_type
807ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000808 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000809 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000810}
811
Douglas Gregordcf25082013-02-11 18:16:18 +0000812/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000813static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
814 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000815 return II.hadMacroDefinition() ||
816 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000817 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000818 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000819 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
820 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000821}
822
Richard Smith76c2f2c2015-07-17 20:09:43 +0000823static bool readBit(unsigned &Bits) {
824 bool Value = Bits & 0x1;
825 Bits >>= 1;
826 return Value;
827}
828
Richard Smith79bf9202015-08-24 03:33:22 +0000829IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
830 using namespace llvm::support;
831 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
832 return Reader.getGlobalIdentifierID(F, RawID >> 1);
833}
834
Richard Smitheb4b58f62016-02-05 01:40:54 +0000835static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
836 if (!II.isFromAST()) {
837 II.setIsFromAST();
838 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
839 if (isInterestingIdentifier(Reader, II, IsModule))
840 II.setChangedSinceDeserialization();
841 }
842}
843
Guy Benyei11169dd2012-12-18 14:30:41 +0000844IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
845 const unsigned char* d,
846 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000847 using namespace llvm::support;
848 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000849 bool IsInteresting = RawID & 0x01;
850
851 // Wipe out the "is interesting" bit.
852 RawID = RawID >> 1;
853
Richard Smith76c2f2c2015-07-17 20:09:43 +0000854 // Build the IdentifierInfo and link the identifier ID with it.
855 IdentifierInfo *II = KnownII;
856 if (!II) {
857 II = &Reader.getIdentifierTable().getOwn(k);
858 KnownII = II;
859 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000860 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000861 Reader.markIdentifierUpToDate(II);
862
Guy Benyei11169dd2012-12-18 14:30:41 +0000863 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
864 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000865 // For uninteresting identifiers, there's nothing else to do. Just notify
866 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000868 return II;
869 }
870
Justin Bogner57ba0b22014-03-28 22:03:24 +0000871 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
872 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000873 bool CPlusPlusOperatorKeyword = readBit(Bits);
874 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000875 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000876 bool Poisoned = readBit(Bits);
877 bool ExtensionToken = readBit(Bits);
878 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000879
880 assert(Bits == 0 && "Extra bits in the identifier?");
881 DataLen -= 8;
882
Guy Benyei11169dd2012-12-18 14:30:41 +0000883 // Set or check the various bits in the IdentifierInfo structure.
884 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000885 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000886 II->revertTokenIDToIdentifier();
887 if (!F.isModule())
888 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
889 else if (HasRevertedBuiltin && II->getBuiltinID()) {
890 II->revertBuiltin();
891 assert((II->hasRevertedBuiltin() ||
892 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
893 "Incorrect ObjC keyword or builtin ID");
894 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000895 assert(II->isExtensionToken() == ExtensionToken &&
896 "Incorrect extension token flag");
897 (void)ExtensionToken;
898 if (Poisoned)
899 II->setIsPoisoned(true);
900 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
901 "Incorrect C++ operator keyword flag");
902 (void)CPlusPlusOperatorKeyword;
903
904 // If this identifier is a macro, deserialize the macro
905 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000906 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000907 uint32_t MacroDirectivesOffset =
908 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000909 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000910
Richard Smithd7329392015-04-21 21:46:32 +0000911 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000912 }
913
914 Reader.SetIdentifierInfo(ID, II);
915
916 // Read all of the declarations visible at global scope with this
917 // name.
918 if (DataLen > 0) {
919 SmallVector<uint32_t, 4> DeclIDs;
920 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000921 DeclIDs.push_back(Reader.getGlobalDeclID(
922 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000923 Reader.SetGloballyVisibleDecls(II, DeclIDs);
924 }
925
926 return II;
927}
928
Richard Smitha06c7e62015-08-26 23:55:49 +0000929DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
930 : Kind(Name.getNameKind()) {
931 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000933 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000934 break;
935 case DeclarationName::ObjCZeroArgSelector:
936 case DeclarationName::ObjCOneArgSelector:
937 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000938 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 break;
940 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000941 Data = Name.getCXXOverloadedOperator();
942 break;
943 case DeclarationName::CXXLiteralOperatorName:
944 Data = (uint64_t)Name.getCXXLiteralIdentifier();
945 break;
946 case DeclarationName::CXXConstructorName:
947 case DeclarationName::CXXDestructorName:
948 case DeclarationName::CXXConversionFunctionName:
949 case DeclarationName::CXXUsingDirective:
950 Data = 0;
951 break;
952 }
953}
954
955unsigned DeclarationNameKey::getHash() const {
956 llvm::FoldingSetNodeID ID;
957 ID.AddInteger(Kind);
958
959 switch (Kind) {
960 case DeclarationName::Identifier:
961 case DeclarationName::CXXLiteralOperatorName:
962 ID.AddString(((IdentifierInfo*)Data)->getName());
963 break;
964 case DeclarationName::ObjCZeroArgSelector:
965 case DeclarationName::ObjCOneArgSelector:
966 case DeclarationName::ObjCMultiArgSelector:
967 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
968 break;
969 case DeclarationName::CXXOperatorName:
970 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 break;
972 case DeclarationName::CXXConstructorName:
973 case DeclarationName::CXXDestructorName:
974 case DeclarationName::CXXConversionFunctionName:
975 case DeclarationName::CXXUsingDirective:
976 break;
977 }
978
979 return ID.ComputeHash();
980}
981
Richard Smithd88a7f12015-09-01 20:35:42 +0000982ModuleFile *
983ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
984 using namespace llvm::support;
985 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
986 return Reader.getLocalModuleFile(F, ModuleFileID);
987}
988
Guy Benyei11169dd2012-12-18 14:30:41 +0000989std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000990ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000991 using namespace llvm::support;
992 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
993 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 return std::make_pair(KeyLen, DataLen);
995}
996
Richard Smitha06c7e62015-08-26 23:55:49 +0000997ASTDeclContextNameLookupTrait::internal_key_type
998ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000999 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001000
Richard Smitha06c7e62015-08-26 23:55:49 +00001001 auto Kind = (DeclarationName::NameKind)*d++;
1002 uint64_t Data;
1003 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001004 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001005 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001006 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001007 break;
1008 case DeclarationName::ObjCZeroArgSelector:
1009 case DeclarationName::ObjCOneArgSelector:
1010 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001011 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001012 (uint64_t)Reader.getLocalSelector(
1013 F, endian::readNext<uint32_t, little, unaligned>(
1014 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 break;
1016 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001017 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001018 break;
1019 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001020 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001021 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 break;
1023 case DeclarationName::CXXConstructorName:
1024 case DeclarationName::CXXDestructorName:
1025 case DeclarationName::CXXConversionFunctionName:
1026 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001027 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 break;
1029 }
1030
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001032}
1033
Richard Smithd88a7f12015-09-01 20:35:42 +00001034void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1035 const unsigned char *d,
1036 unsigned DataLen,
1037 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001038 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001039 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1040 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1041 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1042 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001043}
1044
Richard Smith0f4e2c42015-08-06 04:23:48 +00001045bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1046 BitstreamCursor &Cursor,
1047 uint64_t Offset,
1048 DeclContext *DC) {
1049 assert(Offset != 0);
1050
Guy Benyei11169dd2012-12-18 14:30:41 +00001051 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001052 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001053
Richard Smith0f4e2c42015-08-06 04:23:48 +00001054 RecordData Record;
1055 StringRef Blob;
1056 unsigned Code = Cursor.ReadCode();
1057 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1058 if (RecCode != DECL_CONTEXT_LEXICAL) {
1059 Error("Expected lexical block");
1060 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001061 }
1062
Richard Smith82f8fcd2015-08-06 22:07:25 +00001063 assert(!isa<TranslationUnitDecl>(DC) &&
1064 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001065 // If we are handling a C++ class template instantiation, we can see multiple
1066 // lexical updates for the same record. It's important that we select only one
1067 // of them, so that field numbering works properly. Just pick the first one we
1068 // see.
1069 auto &Lex = LexicalDecls[DC];
1070 if (!Lex.first) {
1071 Lex = std::make_pair(
1072 &M, llvm::makeArrayRef(
1073 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1074 Blob.data()),
1075 Blob.size() / 4));
1076 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001077 DC->setHasExternalLexicalStorage(true);
1078 return false;
1079}
Guy Benyei11169dd2012-12-18 14:30:41 +00001080
Richard Smith0f4e2c42015-08-06 04:23:48 +00001081bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1082 BitstreamCursor &Cursor,
1083 uint64_t Offset,
1084 DeclID ID) {
1085 assert(Offset != 0);
1086
1087 SavedStreamPosition SavedPosition(Cursor);
1088 Cursor.JumpToBit(Offset);
1089
1090 RecordData Record;
1091 StringRef Blob;
1092 unsigned Code = Cursor.ReadCode();
1093 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1094 if (RecCode != DECL_CONTEXT_VISIBLE) {
1095 Error("Expected visible lookup table block");
1096 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 }
1098
Richard Smith0f4e2c42015-08-06 04:23:48 +00001099 // We can't safely determine the primary context yet, so delay attaching the
1100 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001101 auto *Data = (const unsigned char*)Blob.data();
1102 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 return false;
1104}
1105
1106void ASTReader::Error(StringRef Msg) {
1107 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001108 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1109 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001110 Diag(diag::note_module_cache_path)
1111 << PP.getHeaderSearchInfo().getModuleCachePath();
1112 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001113}
1114
1115void ASTReader::Error(unsigned DiagID,
1116 StringRef Arg1, StringRef Arg2) {
1117 if (Diags.isDiagnosticInFlight())
1118 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1119 else
1120 Diag(DiagID) << Arg1 << Arg2;
1121}
1122
1123//===----------------------------------------------------------------------===//
1124// Source Manager Deserialization
1125//===----------------------------------------------------------------------===//
1126
1127/// \brief Read the line table in the source manager block.
1128/// \returns true if there was an error.
1129bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001130 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 unsigned Idx = 0;
1132 LineTableInfo &LineTable = SourceMgr.getLineTable();
1133
1134 // Parse the file names
1135 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001136 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001137 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001138 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001139 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1140 }
Richard Smith63078492015-09-01 07:41:55 +00001141 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001142
1143 // Parse the line entries
1144 std::vector<LineEntry> Entries;
1145 while (Idx < Record.size()) {
1146 int FID = Record[Idx++];
1147 assert(FID >= 0 && "Serialized line entries for non-local file.");
1148 // Remap FileID from 1-based old view.
1149 FID += F.SLocEntryBaseID - 1;
1150
1151 // Extract the line entries
1152 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001153 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001154 Entries.clear();
1155 Entries.reserve(NumEntries);
1156 for (unsigned I = 0; I != NumEntries; ++I) {
1157 unsigned FileOffset = Record[Idx++];
1158 unsigned LineNo = Record[Idx++];
1159 int FilenameID = FileIDs[Record[Idx++]];
1160 SrcMgr::CharacteristicKind FileKind
1161 = (SrcMgr::CharacteristicKind)Record[Idx++];
1162 unsigned IncludeOffset = Record[Idx++];
1163 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1164 FileKind, IncludeOffset));
1165 }
1166 LineTable.AddEntry(FileID::get(FID), Entries);
1167 }
1168
1169 return false;
1170}
1171
1172/// \brief Read a source manager block
1173bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1174 using namespace SrcMgr;
1175
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001176 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001177
1178 // Set the source-location entry cursor to the current position in
1179 // the stream. This cursor will be used to read the contents of the
1180 // source manager block initially, and then lazily read
1181 // source-location entries as needed.
1182 SLocEntryCursor = F.Stream;
1183
1184 // The stream itself is going to skip over the source manager block.
1185 if (F.Stream.SkipBlock()) {
1186 Error("malformed block record in AST file");
1187 return true;
1188 }
1189
1190 // Enter the source manager block.
1191 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1192 Error("malformed source manager block record in AST file");
1193 return true;
1194 }
1195
1196 RecordData Record;
1197 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001198 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1199
1200 switch (E.Kind) {
1201 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1202 case llvm::BitstreamEntry::Error:
1203 Error("malformed block record in AST file");
1204 return true;
1205 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001206 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001207 case llvm::BitstreamEntry::Record:
1208 // The interesting case.
1209 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001211
Guy Benyei11169dd2012-12-18 14:30:41 +00001212 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001213 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001214 StringRef Blob;
1215 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 default: // Default behavior: ignore.
1217 break;
1218
1219 case SM_SLOC_FILE_ENTRY:
1220 case SM_SLOC_BUFFER_ENTRY:
1221 case SM_SLOC_EXPANSION_ENTRY:
1222 // Once we hit one of the source location entries, we're done.
1223 return false;
1224 }
1225 }
1226}
1227
1228/// \brief If a header file is not found at the path that we expect it to be
1229/// and the PCH file was moved from its original location, try to resolve the
1230/// file by assuming that header+PCH were moved together and the header is in
1231/// the same place relative to the PCH.
1232static std::string
1233resolveFileRelativeToOriginalDir(const std::string &Filename,
1234 const std::string &OriginalDir,
1235 const std::string &CurrDir) {
1236 assert(OriginalDir != CurrDir &&
1237 "No point trying to resolve the file if the PCH dir didn't change");
1238 using namespace llvm::sys;
1239 SmallString<128> filePath(Filename);
1240 fs::make_absolute(filePath);
1241 assert(path::is_absolute(OriginalDir));
1242 SmallString<128> currPCHPath(CurrDir);
1243
1244 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1245 fileDirE = path::end(path::parent_path(filePath));
1246 path::const_iterator origDirI = path::begin(OriginalDir),
1247 origDirE = path::end(OriginalDir);
1248 // Skip the common path components from filePath and OriginalDir.
1249 while (fileDirI != fileDirE && origDirI != origDirE &&
1250 *fileDirI == *origDirI) {
1251 ++fileDirI;
1252 ++origDirI;
1253 }
1254 for (; origDirI != origDirE; ++origDirI)
1255 path::append(currPCHPath, "..");
1256 path::append(currPCHPath, fileDirI, fileDirE);
1257 path::append(currPCHPath, path::filename(Filename));
1258 return currPCHPath.str();
1259}
1260
1261bool ASTReader::ReadSLocEntry(int ID) {
1262 if (ID == 0)
1263 return false;
1264
1265 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1266 Error("source location entry ID out-of-range for AST file");
1267 return true;
1268 }
1269
Richard Smithaada85c2016-02-06 02:06:43 +00001270 // Local helper to read the (possibly-compressed) buffer data following the
1271 // entry record.
1272 auto ReadBuffer = [this](
1273 BitstreamCursor &SLocEntryCursor,
1274 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1275 RecordData Record;
1276 StringRef Blob;
1277 unsigned Code = SLocEntryCursor.ReadCode();
1278 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1279
1280 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1281 SmallString<0> Uncompressed;
1282 if (llvm::zlib::uncompress(Blob, Uncompressed, Record[0]) !=
1283 llvm::zlib::StatusOK) {
1284 Error("could not decompress embedded file contents");
1285 return nullptr;
1286 }
1287 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1288 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1289 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1290 } else {
1291 Error("AST record has invalid code");
1292 return nullptr;
1293 }
1294 };
1295
Guy Benyei11169dd2012-12-18 14:30:41 +00001296 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1297 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001298 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 unsigned BaseOffset = F->SLocEntryBaseOffset;
1300
1301 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001302 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1303 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001304 Error("incorrectly-formatted source location entry in AST file");
1305 return true;
1306 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001307
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001309 StringRef Blob;
1310 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 default:
1312 Error("incorrectly-formatted source location entry in AST file");
1313 return true;
1314
1315 case SM_SLOC_FILE_ENTRY: {
1316 // We will detect whether a file changed and return 'Failure' for it, but
1317 // we will also try to fail gracefully by setting up the SLocEntry.
1318 unsigned InputID = Record[4];
1319 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001320 const FileEntry *File = IF.getFile();
1321 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001322
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001323 // Note that we only check if a File was returned. If it was out-of-date
1324 // we have complained but we will continue creating a FileID to recover
1325 // gracefully.
1326 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001327 return true;
1328
1329 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1330 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1331 // This is the module's main file.
1332 IncludeLoc = getImportLocation(F);
1333 }
1334 SrcMgr::CharacteristicKind
1335 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1336 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1337 ID, BaseOffset + Record[0]);
1338 SrcMgr::FileInfo &FileInfo =
1339 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1340 FileInfo.NumCreatedFIDs = Record[5];
1341 if (Record[3])
1342 FileInfo.setHasLineDirectives();
1343
1344 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1345 unsigned NumFileDecls = Record[7];
1346 if (NumFileDecls) {
1347 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1348 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1349 NumFileDecls));
1350 }
Richard Smithaada85c2016-02-06 02:06:43 +00001351
Guy Benyei11169dd2012-12-18 14:30:41 +00001352 const SrcMgr::ContentCache *ContentCache
1353 = SourceMgr.getOrCreateContentCache(File,
1354 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1355 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001356 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1357 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001358 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1359 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001361 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 }
1363
1364 break;
1365 }
1366
1367 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001368 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 unsigned Offset = Record[0];
1370 SrcMgr::CharacteristicKind
1371 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1372 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001373 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 IncludeLoc = getImportLocation(F);
1375 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001376
Richard Smithaada85c2016-02-06 02:06:43 +00001377 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1378 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001380 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001381 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 break;
1383 }
1384
1385 case SM_SLOC_EXPANSION_ENTRY: {
1386 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1387 SourceMgr.createExpansionLoc(SpellingLoc,
1388 ReadSourceLocation(*F, Record[2]),
1389 ReadSourceLocation(*F, Record[3]),
1390 Record[4],
1391 ID,
1392 BaseOffset + Record[0]);
1393 break;
1394 }
1395 }
1396
1397 return false;
1398}
1399
1400std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1401 if (ID == 0)
1402 return std::make_pair(SourceLocation(), "");
1403
1404 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1405 Error("source location entry ID out-of-range for AST file");
1406 return std::make_pair(SourceLocation(), "");
1407 }
1408
1409 // Find which module file this entry lands in.
1410 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001411 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 return std::make_pair(SourceLocation(), "");
1413
1414 // FIXME: Can we map this down to a particular submodule? That would be
1415 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001416 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001417}
1418
1419/// \brief Find the location where the module F is imported.
1420SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1421 if (F->ImportLoc.isValid())
1422 return F->ImportLoc;
1423
1424 // Otherwise we have a PCH. It's considered to be "imported" at the first
1425 // location of its includer.
1426 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001427 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001428 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001429 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001430 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001431 return F->ImportedBy[0]->FirstLoc;
1432}
1433
1434/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1435/// specified cursor. Read the abbreviations that are at the top of the block
1436/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001437bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001438 if (Cursor.EnterSubBlock(BlockID))
1439 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001440
1441 while (true) {
1442 uint64_t Offset = Cursor.GetCurrentBitNo();
1443 unsigned Code = Cursor.ReadCode();
1444
1445 // We expect all abbrevs to be at the start of the block.
1446 if (Code != llvm::bitc::DEFINE_ABBREV) {
1447 Cursor.JumpToBit(Offset);
1448 return false;
1449 }
1450 Cursor.ReadAbbrevRecord();
1451 }
1452}
1453
Richard Smithe40f2ba2013-08-07 21:41:30 +00001454Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001455 unsigned &Idx) {
1456 Token Tok;
1457 Tok.startToken();
1458 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1459 Tok.setLength(Record[Idx++]);
1460 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1461 Tok.setIdentifierInfo(II);
1462 Tok.setKind((tok::TokenKind)Record[Idx++]);
1463 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1464 return Tok;
1465}
1466
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001467MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001468 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001469
1470 // Keep track of where we are in the stream, then jump back there
1471 // after reading this macro.
1472 SavedStreamPosition SavedPosition(Stream);
1473
1474 Stream.JumpToBit(Offset);
1475 RecordData Record;
1476 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001477 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001478
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001480 // Advance to the next record, but if we get to the end of the block, don't
1481 // pop it (removing all the abbreviations from the cursor) since we want to
1482 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001483 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001484 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1485
1486 switch (Entry.Kind) {
1487 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1488 case llvm::BitstreamEntry::Error:
1489 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001490 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001491 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001492 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001493 case llvm::BitstreamEntry::Record:
1494 // The interesting case.
1495 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 }
1497
1498 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001499 Record.clear();
1500 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001501 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001502 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001503 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001504 case PP_MACRO_DIRECTIVE_HISTORY:
1505 return Macro;
1506
Guy Benyei11169dd2012-12-18 14:30:41 +00001507 case PP_MACRO_OBJECT_LIKE:
1508 case PP_MACRO_FUNCTION_LIKE: {
1509 // If we already have a macro, that means that we've hit the end
1510 // of the definition of the macro we were looking for. We're
1511 // done.
1512 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001513 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001514
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001515 unsigned NextIndex = 1; // Skip identifier ID.
1516 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001518 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001519 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001520 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001521 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001522
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1524 // Decode function-like macro info.
1525 bool isC99VarArgs = Record[NextIndex++];
1526 bool isGNUVarArgs = Record[NextIndex++];
1527 bool hasCommaPasting = Record[NextIndex++];
1528 MacroArgs.clear();
1529 unsigned NumArgs = Record[NextIndex++];
1530 for (unsigned i = 0; i != NumArgs; ++i)
1531 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1532
1533 // Install function-like macro info.
1534 MI->setIsFunctionLike();
1535 if (isC99VarArgs) MI->setIsC99Varargs();
1536 if (isGNUVarArgs) MI->setIsGNUVarargs();
1537 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001538 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001539 }
1540
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 // Remember that we saw this macro last so that we add the tokens that
1542 // form its body to it.
1543 Macro = MI;
1544
1545 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1546 Record[NextIndex]) {
1547 // We have a macro definition. Register the association
1548 PreprocessedEntityID
1549 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1550 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001551 PreprocessingRecord::PPEntityID PPID =
1552 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1553 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1554 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001555 if (PPDef)
1556 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001557 }
1558
1559 ++NumMacrosRead;
1560 break;
1561 }
1562
1563 case PP_TOKEN: {
1564 // If we see a TOKEN before a PP_MACRO_*, then the file is
1565 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001566 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001567
John McCallf413f5e2013-05-03 00:10:13 +00001568 unsigned Idx = 0;
1569 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001570 Macro->AddTokenToBody(Tok);
1571 break;
1572 }
1573 }
1574 }
1575}
1576
1577PreprocessedEntityID
1578ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1579 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1580 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1581 assert(I != M.PreprocessedEntityRemap.end()
1582 && "Invalid index into preprocessed entity index remap");
1583
1584 return LocalID + I->second;
1585}
1586
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001587unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1588 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001589}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001590
Guy Benyei11169dd2012-12-18 14:30:41 +00001591HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001592HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001593 internal_key_type ikey = {FE->getSize(),
1594 M.HasTimestamps ? FE->getModificationTime() : 0,
1595 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001596 return ikey;
1597}
Guy Benyei11169dd2012-12-18 14:30:41 +00001598
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001599bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001600 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 return false;
1602
Mehdi Amini004b9c72016-10-10 22:52:47 +00001603 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001604 return true;
1605
Guy Benyei11169dd2012-12-18 14:30:41 +00001606 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001607 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001608 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1609 if (!Key.Imported)
1610 return FileMgr.getFile(Key.Filename);
1611
1612 std::string Resolved = Key.Filename;
1613 Reader.ResolveImportedPath(M, Resolved);
1614 return FileMgr.getFile(Resolved);
1615 };
1616
1617 const FileEntry *FEA = GetFile(a);
1618 const FileEntry *FEB = GetFile(b);
1619 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001620}
1621
1622std::pair<unsigned, unsigned>
1623HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001624 using namespace llvm::support;
1625 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001627 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001628}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001629
1630HeaderFileInfoTrait::internal_key_type
1631HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001632 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001633 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001634 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1635 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001636 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001637 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001638 return ikey;
1639}
1640
Guy Benyei11169dd2012-12-18 14:30:41 +00001641HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001642HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 unsigned DataLen) {
1644 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001645 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001646 HeaderFileInfo HFI;
1647 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001648 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1649 HFI.isImport |= (Flags >> 4) & 0x01;
1650 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1651 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001653 // FIXME: Find a better way to handle this. Maybe just store a
1654 // "has been included" flag?
1655 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1656 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001657 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1658 M, endian::readNext<uint32_t, little, unaligned>(d));
1659 if (unsigned FrameworkOffset =
1660 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 // The framework offset is 1 greater than the actual offset,
1662 // since 0 is used as an indicator for "no framework name".
1663 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1664 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1665 }
Richard Smith386bb072015-08-18 23:42:23 +00001666
1667 assert((End - d) % 4 == 0 &&
1668 "Wrong data length in HeaderFileInfo deserialization");
1669 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001670 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001671 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1672 LocalSMID >>= 2;
1673
1674 // This header is part of a module. Associate it with the module to enable
1675 // implicit module import.
1676 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1677 Module *Mod = Reader.getSubmodule(GlobalSMID);
1678 FileManager &FileMgr = Reader.getFileManager();
1679 ModuleMap &ModMap =
1680 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1681
1682 std::string Filename = key.Filename;
1683 if (key.Imported)
1684 Reader.ResolveImportedPath(M, Filename);
1685 // FIXME: This is not always the right filename-as-written, but we're not
1686 // going to use this information to rebuild the module, so it doesn't make
1687 // a lot of difference.
1688 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001689 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1690 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001691 }
1692
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 // This HeaderFileInfo was externally loaded.
1694 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001695 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001696 return HFI;
1697}
1698
Richard Smithd7329392015-04-21 21:46:32 +00001699void ASTReader::addPendingMacro(IdentifierInfo *II,
1700 ModuleFile *M,
1701 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001702 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1703 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001704}
1705
1706void ASTReader::ReadDefinedMacros() {
1707 // Note that we are loading defined macros.
1708 Deserializing Macros(this);
1709
Pete Cooper57d3f142015-07-30 17:22:52 +00001710 for (auto &I : llvm::reverse(ModuleMgr)) {
1711 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001712
1713 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001714 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001715 continue;
1716
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001717 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001718 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001719
1720 RecordData Record;
1721 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001722 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1723
1724 switch (E.Kind) {
1725 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1726 case llvm::BitstreamEntry::Error:
1727 Error("malformed block record in AST file");
1728 return;
1729 case llvm::BitstreamEntry::EndBlock:
1730 goto NextCursor;
1731
1732 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001733 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001734 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001735 default: // Default behavior: ignore.
1736 break;
1737
1738 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001739 case PP_MACRO_FUNCTION_LIKE: {
1740 IdentifierInfo *II = getLocalIdentifier(*I, Record[0]);
1741 if (II->isOutOfDate())
1742 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001743 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001744 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001745
1746 case PP_TOKEN:
1747 // Ignore tokens.
1748 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001749 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001750 break;
1751 }
1752 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001753 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 }
1755}
1756
1757namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001758
Guy Benyei11169dd2012-12-18 14:30:41 +00001759 /// \brief Visitor class used to look up identifirs in an AST file.
1760 class IdentifierLookupVisitor {
1761 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001762 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001764 unsigned &NumIdentifierLookups;
1765 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001766 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001767
Guy Benyei11169dd2012-12-18 14:30:41 +00001768 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001769 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1770 unsigned &NumIdentifierLookups,
1771 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001772 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1773 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001774 NumIdentifierLookups(NumIdentifierLookups),
1775 NumIdentifierLookupHits(NumIdentifierLookupHits),
1776 Found()
1777 {
1778 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001779
1780 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001781 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001782 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001783 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001784
Guy Benyei11169dd2012-12-18 14:30:41 +00001785 ASTIdentifierLookupTable *IdTable
1786 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1787 if (!IdTable)
1788 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001789
1790 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001791 Found);
1792 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001793 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001794 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001795 if (Pos == IdTable->end())
1796 return false;
1797
1798 // Dereferencing the iterator has the effect of building the
1799 // IdentifierInfo node and populating it with the various
1800 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001801 ++NumIdentifierLookupHits;
1802 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001803 return true;
1804 }
1805
1806 // \brief Retrieve the identifier info found within the module
1807 // files.
1808 IdentifierInfo *getIdentifierInfo() const { return Found; }
1809 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001810
1811} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001812
1813void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1814 // Note that we are loading an identifier.
1815 Deserializing AnIdentifier(this);
1816
1817 unsigned PriorGeneration = 0;
1818 if (getContext().getLangOpts().Modules)
1819 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001820
1821 // If there is a global index, look there first to determine which modules
1822 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001823 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001824 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001825 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001826 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1827 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001828 }
1829 }
1830
Douglas Gregor7211ac12013-01-25 23:32:03 +00001831 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001832 NumIdentifierLookups,
1833 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001834 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001835 markIdentifierUpToDate(&II);
1836}
1837
1838void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1839 if (!II)
1840 return;
1841
1842 II->setOutOfDate(false);
1843
1844 // Update the generation for this identifier.
1845 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001846 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001847}
1848
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001849void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1850 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001851 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001852
1853 BitstreamCursor &Cursor = M.MacroCursor;
1854 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001855 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001856
Richard Smith713369b2015-04-23 20:40:50 +00001857 struct ModuleMacroRecord {
1858 SubmoduleID SubModID;
1859 MacroInfo *MI;
1860 SmallVector<SubmoduleID, 8> Overrides;
1861 };
1862 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001863
Richard Smithd7329392015-04-21 21:46:32 +00001864 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1865 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1866 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001867 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001868 while (true) {
1869 llvm::BitstreamEntry Entry =
1870 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1871 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1872 Error("malformed block record in AST file");
1873 return;
1874 }
1875
1876 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001877 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001878 case PP_MACRO_DIRECTIVE_HISTORY:
1879 break;
1880
1881 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001882 ModuleMacros.push_back(ModuleMacroRecord());
1883 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001884 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1885 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001886 for (int I = 2, N = Record.size(); I != N; ++I)
1887 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001888 continue;
1889 }
1890
1891 default:
1892 Error("malformed block record in AST file");
1893 return;
1894 }
1895
1896 // We found the macro directive history; that's the last record
1897 // for this macro.
1898 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001899 }
1900
Richard Smithd7329392015-04-21 21:46:32 +00001901 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001902 {
1903 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001904 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001905 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001906 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001907 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001908 Module *Mod = getSubmodule(ModID);
1909 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001910 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001911 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001912 }
1913
1914 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001915 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001916 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001917 }
1918 }
1919
1920 // Don't read the directive history for a module; we don't have anywhere
1921 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001922 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001923 return;
1924
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001925 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001926 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001927 unsigned Idx = 0, N = Record.size();
1928 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001929 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001930 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001931 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1932 switch (K) {
1933 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001934 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001935 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001936 break;
1937 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001938 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001939 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001940 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001941 }
1942 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001943 bool isPublic = Record[Idx++];
1944 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1945 break;
1946 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001947
1948 if (!Latest)
1949 Latest = MD;
1950 if (Earliest)
1951 Earliest->setPrevious(MD);
1952 Earliest = MD;
1953 }
1954
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001955 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00001956 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001957}
1958
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001959ASTReader::InputFileInfo
1960ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001961 // Go find this input file.
1962 BitstreamCursor &Cursor = F.InputFilesCursor;
1963 SavedStreamPosition SavedPosition(Cursor);
1964 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1965
1966 unsigned Code = Cursor.ReadCode();
1967 RecordData Record;
1968 StringRef Blob;
1969
1970 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1971 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1972 "invalid record type for input file");
1973 (void)Result;
1974
1975 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001976 InputFileInfo R;
1977 R.StoredSize = static_cast<off_t>(Record[1]);
1978 R.StoredTime = static_cast<time_t>(Record[2]);
1979 R.Overridden = static_cast<bool>(Record[3]);
1980 R.Transient = static_cast<bool>(Record[4]);
1981 R.Filename = Blob;
1982 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001983 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001984}
1985
Manman Renc8c94152016-10-21 23:35:03 +00001986static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001987InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001988 // If this ID is bogus, just return an empty input file.
1989 if (ID == 0 || ID > F.InputFilesLoaded.size())
1990 return InputFile();
1991
1992 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001993 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001994 return F.InputFilesLoaded[ID-1];
1995
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001996 if (F.InputFilesLoaded[ID-1].isNotFound())
1997 return InputFile();
1998
Guy Benyei11169dd2012-12-18 14:30:41 +00001999 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002000 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002001 SavedStreamPosition SavedPosition(Cursor);
2002 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2003
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002004 InputFileInfo FI = readInputFileInfo(F, ID);
2005 off_t StoredSize = FI.StoredSize;
2006 time_t StoredTime = FI.StoredTime;
2007 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002008 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002009 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002010
Richard Smitha8cfffa2015-11-26 02:04:16 +00002011 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002012
2013 // If we didn't find the file, resolve it relative to the
2014 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002015 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002016 F.OriginalDir != CurrentDir) {
2017 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2018 F.OriginalDir,
2019 CurrentDir);
2020 if (!Resolved.empty())
2021 File = FileMgr.getFile(Resolved);
2022 }
2023
2024 // For an overridden file, create a virtual file with the stored
2025 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002026 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002027 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002028
Craig Toppera13603a2014-05-22 05:54:18 +00002029 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002030 if (Complain) {
2031 std::string ErrorStr = "could not find file '";
2032 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002033 ErrorStr += "' referenced by AST file '";
2034 ErrorStr += F.FileName;
2035 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002036 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002037 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002038 // Record that we didn't find the file.
2039 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2040 return InputFile();
2041 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002042
Ben Langmuir198c1682014-03-07 07:27:49 +00002043 // Check if there was a request to override the contents of the file
2044 // that was part of the precompiled header. Overridding such a file
2045 // can lead to problems when lexing using the source locations from the
2046 // PCH.
2047 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002048 // FIXME: Reject if the overrides are different.
2049 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002050 if (Complain)
2051 Error(diag::err_fe_pch_file_overridden, Filename);
2052 // After emitting the diagnostic, recover by disabling the override so
2053 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002054 //
2055 // FIXME: This recovery is just as broken as the original state; there may
2056 // be another precompiled module that's using the overridden contents, or
2057 // we might be half way through parsing it. Instead, we should treat the
2058 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002059 SM.disableFileContentsOverride(File);
2060 // The FileEntry is a virtual file entry with the size of the contents
2061 // that would override the original contents. Set it to the original's
2062 // size/time.
2063 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2064 StoredSize, StoredTime);
2065 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002066
Ben Langmuir198c1682014-03-07 07:27:49 +00002067 bool IsOutOfDate = false;
2068
2069 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002070 if (!Overridden && //
2071 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002072 (StoredTime && StoredTime != File->getModificationTime() &&
2073 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002074 )) {
2075 if (Complain) {
2076 // Build a list of the PCH imports that got us here (in reverse).
2077 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2078 while (ImportStack.back()->ImportedBy.size() > 0)
2079 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002080
Ben Langmuir198c1682014-03-07 07:27:49 +00002081 // The top-level PCH is stale.
2082 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002083 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2084 if (DiagnosticKind == 0)
2085 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2086 else if (DiagnosticKind == 1)
2087 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2088 else
2089 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002090
Ben Langmuir198c1682014-03-07 07:27:49 +00002091 // Print the import stack.
2092 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2093 Diag(diag::note_pch_required_by)
2094 << Filename << ImportStack[0]->FileName;
2095 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002096 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002097 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002098 }
2099
Ben Langmuir198c1682014-03-07 07:27:49 +00002100 if (!Diags.isDiagnosticInFlight())
2101 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002102 }
2103
Ben Langmuir198c1682014-03-07 07:27:49 +00002104 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002105 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002106 // FIXME: If the file is overridden and we've already opened it,
2107 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002108
Richard Smitha8cfffa2015-11-26 02:04:16 +00002109 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002110
2111 // Note that we've loaded this input file.
2112 F.InputFilesLoaded[ID-1] = IF;
2113 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002114}
2115
Richard Smith7ed1bc92014-12-05 22:42:13 +00002116/// \brief If we are loading a relocatable PCH or module file, and the filename
2117/// is not an absolute path, add the system or module root to the beginning of
2118/// the file name.
2119void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2120 // Resolve relative to the base directory, if we have one.
2121 if (!M.BaseDirectory.empty())
2122 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002123}
2124
Richard Smith7ed1bc92014-12-05 22:42:13 +00002125void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002126 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2127 return;
2128
Richard Smith7ed1bc92014-12-05 22:42:13 +00002129 SmallString<128> Buffer;
2130 llvm::sys::path::append(Buffer, Prefix, Filename);
2131 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002132}
2133
Richard Smith0f99d6a2015-08-09 08:48:41 +00002134static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2135 switch (ARR) {
2136 case ASTReader::Failure: return true;
2137 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2138 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2139 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2140 case ASTReader::ConfigurationMismatch:
2141 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2142 case ASTReader::HadErrors: return true;
2143 case ASTReader::Success: return false;
2144 }
2145
2146 llvm_unreachable("unknown ASTReadResult");
2147}
2148
Richard Smith0516b182015-09-08 19:40:14 +00002149ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2150 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2151 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Manman Ren47a44452016-07-26 17:12:17 +00002152 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
Richard Smith0516b182015-09-08 19:40:14 +00002153 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2154 return Failure;
2155
2156 // Read all of the records in the options block.
2157 RecordData Record;
2158 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002159 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002160 llvm::BitstreamEntry Entry = Stream.advance();
2161
2162 switch (Entry.Kind) {
2163 case llvm::BitstreamEntry::Error:
2164 case llvm::BitstreamEntry::SubBlock:
2165 return Failure;
2166
2167 case llvm::BitstreamEntry::EndBlock:
2168 return Result;
2169
2170 case llvm::BitstreamEntry::Record:
2171 // The interesting case.
2172 break;
2173 }
2174
2175 // Read and process a record.
2176 Record.clear();
2177 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2178 case LANGUAGE_OPTIONS: {
2179 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2180 if (ParseLanguageOptions(Record, Complain, Listener,
2181 AllowCompatibleConfigurationMismatch))
2182 Result = ConfigurationMismatch;
2183 break;
2184 }
2185
2186 case TARGET_OPTIONS: {
2187 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2188 if (ParseTargetOptions(Record, Complain, Listener,
2189 AllowCompatibleConfigurationMismatch))
2190 Result = ConfigurationMismatch;
2191 break;
2192 }
2193
2194 case DIAGNOSTIC_OPTIONS: {
2195 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Manman Ren47a44452016-07-26 17:12:17 +00002196 if (ValidateDiagnosticOptions &&
2197 !AllowCompatibleConfigurationMismatch &&
Richard Smith0516b182015-09-08 19:40:14 +00002198 ParseDiagnosticOptions(Record, Complain, Listener))
2199 return OutOfDate;
2200 break;
2201 }
2202
2203 case FILE_SYSTEM_OPTIONS: {
2204 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2205 if (!AllowCompatibleConfigurationMismatch &&
2206 ParseFileSystemOptions(Record, Complain, Listener))
2207 Result = ConfigurationMismatch;
2208 break;
2209 }
2210
2211 case HEADER_SEARCH_OPTIONS: {
2212 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2213 if (!AllowCompatibleConfigurationMismatch &&
2214 ParseHeaderSearchOptions(Record, Complain, Listener))
2215 Result = ConfigurationMismatch;
2216 break;
2217 }
2218
2219 case PREPROCESSOR_OPTIONS:
2220 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2221 if (!AllowCompatibleConfigurationMismatch &&
2222 ParsePreprocessorOptions(Record, Complain, Listener,
2223 SuggestedPredefines))
2224 Result = ConfigurationMismatch;
2225 break;
2226 }
2227 }
2228}
2229
Guy Benyei11169dd2012-12-18 14:30:41 +00002230ASTReader::ASTReadResult
2231ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002232 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002233 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002234 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002235 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002236 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002237
2238 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2239 Error("malformed block record in AST file");
2240 return Failure;
2241 }
2242
2243 // Read all of the records and blocks in the control block.
2244 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002245 unsigned NumInputs = 0;
2246 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002247 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002248 llvm::BitstreamEntry Entry = Stream.advance();
2249
2250 switch (Entry.Kind) {
2251 case llvm::BitstreamEntry::Error:
2252 Error("malformed block record in AST file");
2253 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002254 case llvm::BitstreamEntry::EndBlock: {
2255 // Validate input files.
2256 const HeaderSearchOptions &HSOpts =
2257 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002258
Richard Smitha1825302014-10-23 22:18:29 +00002259 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002260 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2261 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002262 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2263 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002264 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002265
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002266 // If we are reading a module, we will create a verification timestamp,
2267 // so we verify all input files. Otherwise, verify only user input
2268 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002269
2270 unsigned N = NumUserInputs;
2271 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002272 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002273 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002274 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002275 N = NumInputs;
2276
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002277 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002278 InputFile IF = getInputFile(F, I+1, Complain);
2279 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002280 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002281 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002282 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002283
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002284 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002285 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002286
Ben Langmuircb69b572014-03-07 06:40:32 +00002287 if (Listener && Listener->needsInputFileVisitation()) {
2288 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2289 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002290 for (unsigned I = 0; I < N; ++I) {
2291 bool IsSystem = I >= NumUserInputs;
2292 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002293 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002294 F.Kind == MK_ExplicitModule ||
2295 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002296 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002297 }
2298
Richard Smith8a308ec2015-11-05 00:54:55 +00002299 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002300 }
2301
Chris Lattnere7b154b2013-01-19 21:39:22 +00002302 case llvm::BitstreamEntry::SubBlock:
2303 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002304 case INPUT_FILES_BLOCK_ID:
2305 F.InputFilesCursor = Stream;
2306 if (Stream.SkipBlock() || // Skip with the main cursor
2307 // Read the abbreviations
2308 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2309 Error("malformed block record in AST file");
2310 return Failure;
2311 }
2312 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002313
2314 case OPTIONS_BLOCK_ID:
2315 // If we're reading the first module for this group, check its options
2316 // are compatible with ours. For modules it imports, no further checking
2317 // is required, because we checked them when we built it.
2318 if (Listener && !ImportedBy) {
2319 // Should we allow the configuration of the module file to differ from
2320 // the configuration of the current translation unit in a compatible
2321 // way?
2322 //
2323 // FIXME: Allow this for files explicitly specified with -include-pch.
2324 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002325 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Manman Ren47a44452016-07-26 17:12:17 +00002326 const HeaderSearchOptions &HSOpts =
2327 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Richard Smith0516b182015-09-08 19:40:14 +00002328
Richard Smith8a308ec2015-11-05 00:54:55 +00002329 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2330 AllowCompatibleConfigurationMismatch,
Manman Ren47a44452016-07-26 17:12:17 +00002331 *Listener, SuggestedPredefines,
2332 HSOpts.ModulesValidateDiagnosticOptions);
Richard Smith0516b182015-09-08 19:40:14 +00002333 if (Result == Failure) {
2334 Error("malformed block record in AST file");
2335 return Result;
2336 }
2337
Richard Smith8a308ec2015-11-05 00:54:55 +00002338 if (DisableValidation ||
2339 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2340 Result = Success;
2341
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002342 // If we can't load the module, exit early since we likely
2343 // will rebuild the module anyway. The stream may be in the
2344 // middle of a block.
2345 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002346 return Result;
2347 } else if (Stream.SkipBlock()) {
2348 Error("malformed block record in AST file");
2349 return Failure;
2350 }
2351 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002352
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002354 if (Stream.SkipBlock()) {
2355 Error("malformed block record in AST file");
2356 return Failure;
2357 }
2358 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002360
2361 case llvm::BitstreamEntry::Record:
2362 // The interesting case.
2363 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002364 }
2365
2366 // Read and process a record.
2367 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002368 StringRef Blob;
2369 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 case METADATA: {
2371 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2372 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002373 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2374 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002375 return VersionMismatch;
2376 }
2377
Richard Smithe75ee0f2015-08-17 07:13:32 +00002378 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2380 Diag(diag::err_pch_with_compiler_errors);
2381 return HadErrors;
2382 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002383 if (hasErrors) {
2384 Diags.ErrorOccurred = true;
2385 Diags.UncompilableErrorOccurred = true;
2386 Diags.UnrecoverableErrorOccurred = true;
2387 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002388
2389 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002390 // Relative paths in a relocatable PCH are relative to our sysroot.
2391 if (F.RelocatablePCH)
2392 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002393
Richard Smithe75ee0f2015-08-17 07:13:32 +00002394 F.HasTimestamps = Record[5];
2395
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002397 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2399 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002400 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 return VersionMismatch;
2402 }
2403 break;
2404 }
2405
Ben Langmuir487ea142014-10-23 18:05:36 +00002406 case SIGNATURE:
2407 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2408 F.Signature = Record[0];
2409 break;
2410
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 case IMPORTS: {
2412 // Load each of the imported PCH files.
2413 unsigned Idx = 0, N = Record.size();
2414 while (Idx < N) {
2415 // Read information about the AST file.
2416 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2417 // The import location will be the local one for now; we will adjust
2418 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002419 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002421 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002422 off_t StoredSize = (off_t)Record[Idx++];
2423 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002424 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002425 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002426
Richard Smith0f99d6a2015-08-09 08:48:41 +00002427 // If our client can't cope with us being out of date, we can't cope with
2428 // our dependency being missing.
2429 unsigned Capabilities = ClientLoadCapabilities;
2430 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2431 Capabilities &= ~ARR_Missing;
2432
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002434 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2435 Loaded, StoredSize, StoredModTime,
2436 StoredSignature, Capabilities);
2437
2438 // If we diagnosed a problem, produce a backtrace.
2439 if (isDiagnosedResult(Result, Capabilities))
2440 Diag(diag::note_module_file_imported_by)
2441 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2442
2443 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 case Failure: return Failure;
2445 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002446 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 case OutOfDate: return OutOfDate;
2448 case VersionMismatch: return VersionMismatch;
2449 case ConfigurationMismatch: return ConfigurationMismatch;
2450 case HadErrors: return HadErrors;
2451 case Success: break;
2452 }
2453 }
2454 break;
2455 }
2456
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 case ORIGINAL_FILE:
2458 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002459 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002461 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 break;
2463
2464 case ORIGINAL_FILE_ID:
2465 F.OriginalSourceFileID = FileID::get(Record[0]);
2466 break;
2467
2468 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002469 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 break;
2471
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002472 case MODULE_NAME:
2473 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002474 if (Listener)
2475 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002476 break;
2477
Richard Smith223d3f22014-12-06 03:21:08 +00002478 case MODULE_DIRECTORY: {
2479 assert(!F.ModuleName.empty() &&
2480 "MODULE_DIRECTORY found before MODULE_NAME");
2481 // If we've already loaded a module map file covering this module, we may
2482 // have a better path for it (relative to the current build).
2483 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2484 if (M && M->Directory) {
2485 // If we're implicitly loading a module, the base directory can't
2486 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002487 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002488 const DirectoryEntry *BuildDir =
2489 PP.getFileManager().getDirectory(Blob);
2490 if (!BuildDir || BuildDir != M->Directory) {
2491 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2492 Diag(diag::err_imported_module_relocated)
2493 << F.ModuleName << Blob << M->Directory->getName();
2494 return OutOfDate;
2495 }
2496 }
2497 F.BaseDirectory = M->Directory->getName();
2498 } else {
2499 F.BaseDirectory = Blob;
2500 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002501 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002502 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002503
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002504 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002505 if (ASTReadResult Result =
2506 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2507 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002508 break;
2509
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002510 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002511 NumInputs = Record[0];
2512 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002513 F.InputFileOffsets =
2514 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002515 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 break;
2517 }
2518 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002519}
2520
Ben Langmuir2c9af442014-04-10 17:57:43 +00002521ASTReader::ASTReadResult
2522ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002523 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002524
2525 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2526 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002527 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 }
2529
2530 // Read all of the records and blocks for the AST file.
2531 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002532 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002533 llvm::BitstreamEntry Entry = Stream.advance();
2534
2535 switch (Entry.Kind) {
2536 case llvm::BitstreamEntry::Error:
2537 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002538 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002539 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002540 // Outside of C++, we do not store a lookup map for the translation unit.
2541 // Instead, mark it as needing a lookup map to be built if this module
2542 // contains any declarations lexically within it (which it always does!).
2543 // This usually has no cost, since we very rarely need the lookup map for
2544 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002546 if (DC->hasExternalLexicalStorage() &&
2547 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002549
Ben Langmuir2c9af442014-04-10 17:57:43 +00002550 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002552 case llvm::BitstreamEntry::SubBlock:
2553 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 case DECLTYPES_BLOCK_ID:
2555 // We lazily load the decls block, but we want to set up the
2556 // DeclsCursor cursor to point into it. Clone our current bitcode
2557 // cursor to it, enter the block and read the abbrevs in that block.
2558 // With the main cursor, we just skip over it.
2559 F.DeclsCursor = Stream;
2560 if (Stream.SkipBlock() || // Skip with the main cursor.
2561 // Read the abbrevs.
2562 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2563 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002564 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 }
2566 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002567
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 case PREPROCESSOR_BLOCK_ID:
2569 F.MacroCursor = Stream;
2570 if (!PP.getExternalSource())
2571 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002572
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 if (Stream.SkipBlock() ||
2574 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2575 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002576 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 }
2578 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2579 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002580
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 case PREPROCESSOR_DETAIL_BLOCK_ID:
2582 F.PreprocessorDetailCursor = Stream;
2583 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002584 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002586 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002587 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002588 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002590 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2591
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 if (!PP.getPreprocessingRecord())
2593 PP.createPreprocessingRecord();
2594 if (!PP.getPreprocessingRecord()->getExternalSource())
2595 PP.getPreprocessingRecord()->SetExternalSource(*this);
2596 break;
2597
2598 case SOURCE_MANAGER_BLOCK_ID:
2599 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002600 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002602
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002604 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2605 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002607
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002609 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 if (Stream.SkipBlock() ||
2611 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2612 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002613 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 }
2615 CommentsCursors.push_back(std::make_pair(C, &F));
2616 break;
2617 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002618
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002620 if (Stream.SkipBlock()) {
2621 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002622 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002623 }
2624 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 }
2626 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002627
2628 case llvm::BitstreamEntry::Record:
2629 // The interesting case.
2630 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 }
2632
2633 // Read and process a record.
2634 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002635 StringRef Blob;
2636 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 default: // Default behavior: ignore.
2638 break;
2639
2640 case TYPE_OFFSET: {
2641 if (F.LocalNumTypes != 0) {
2642 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002643 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002645 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 F.LocalNumTypes = Record[0];
2647 unsigned LocalBaseTypeIndex = Record[1];
2648 F.BaseTypeIndex = getTotalNumTypes();
2649
2650 if (F.LocalNumTypes > 0) {
2651 // Introduce the global -> local mapping for types within this module.
2652 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2653
2654 // Introduce the local -> global mapping for types within this module.
2655 F.TypeRemap.insertOrReplace(
2656 std::make_pair(LocalBaseTypeIndex,
2657 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002658
2659 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 }
2661 break;
2662 }
2663
2664 case DECL_OFFSET: {
2665 if (F.LocalNumDecls != 0) {
2666 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002667 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002669 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 F.LocalNumDecls = Record[0];
2671 unsigned LocalBaseDeclID = Record[1];
2672 F.BaseDeclID = getTotalNumDecls();
2673
2674 if (F.LocalNumDecls > 0) {
2675 // Introduce the global -> local mapping for declarations within this
2676 // module.
2677 GlobalDeclMap.insert(
2678 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2679
2680 // Introduce the local -> global mapping for declarations within this
2681 // module.
2682 F.DeclRemap.insertOrReplace(
2683 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2684
2685 // Introduce the global -> local mapping for declarations within this
2686 // module.
2687 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002688
Ben Langmuir52ca6782014-10-20 16:27:32 +00002689 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2690 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 break;
2692 }
2693
2694 case TU_UPDATE_LEXICAL: {
2695 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002696 LexicalContents Contents(
2697 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2698 Blob.data()),
2699 static_cast<unsigned int>(Blob.size() / 4));
2700 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 TU->setHasExternalLexicalStorage(true);
2702 break;
2703 }
2704
2705 case UPDATE_VISIBLE: {
2706 unsigned Idx = 0;
2707 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002708 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002709 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002710 // If we've already loaded the decl, perform the updates when we finish
2711 // loading this block.
2712 if (Decl *D = GetExistingDecl(ID))
2713 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 break;
2715 }
2716
2717 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002718 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002720 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2721 (const unsigned char *)F.IdentifierTableData + Record[0],
2722 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2723 (const unsigned char *)F.IdentifierTableData,
2724 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002725
2726 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2727 }
2728 break;
2729
2730 case IDENTIFIER_OFFSET: {
2731 if (F.LocalNumIdentifiers != 0) {
2732 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002733 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002735 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 F.LocalNumIdentifiers = Record[0];
2737 unsigned LocalBaseIdentifierID = Record[1];
2738 F.BaseIdentifierID = getTotalNumIdentifiers();
2739
2740 if (F.LocalNumIdentifiers > 0) {
2741 // Introduce the global -> local mapping for identifiers within this
2742 // module.
2743 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2744 &F));
2745
2746 // Introduce the local -> global mapping for identifiers within this
2747 // module.
2748 F.IdentifierRemap.insertOrReplace(
2749 std::make_pair(LocalBaseIdentifierID,
2750 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002751
Ben Langmuir52ca6782014-10-20 16:27:32 +00002752 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2753 + F.LocalNumIdentifiers);
2754 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 break;
2756 }
2757
Richard Smith33e0f7e2015-07-22 02:08:40 +00002758 case INTERESTING_IDENTIFIERS:
2759 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2760 break;
2761
Ben Langmuir332aafe2014-01-31 01:06:56 +00002762 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002763 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2764 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002765 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002766 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002767 break;
2768
2769 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002770 if (SpecialTypes.empty()) {
2771 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2772 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2773 break;
2774 }
2775
2776 if (SpecialTypes.size() != Record.size()) {
2777 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002778 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002779 }
2780
2781 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2782 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2783 if (!SpecialTypes[I])
2784 SpecialTypes[I] = ID;
2785 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2786 // merge step?
2787 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 break;
2789
2790 case STATISTICS:
2791 TotalNumStatements += Record[0];
2792 TotalNumMacros += Record[1];
2793 TotalLexicalDeclContexts += Record[2];
2794 TotalVisibleDeclContexts += Record[3];
2795 break;
2796
2797 case UNUSED_FILESCOPED_DECLS:
2798 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2799 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2800 break;
2801
2802 case DELEGATING_CTORS:
2803 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2804 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2805 break;
2806
2807 case WEAK_UNDECLARED_IDENTIFIERS:
2808 if (Record.size() % 4 != 0) {
2809 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002810 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002811 }
2812
2813 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2814 // files. This isn't the way to do it :)
2815 WeakUndeclaredIdentifiers.clear();
2816
2817 // Translate the weak, undeclared identifiers into global IDs.
2818 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2819 WeakUndeclaredIdentifiers.push_back(
2820 getGlobalIdentifierID(F, Record[I++]));
2821 WeakUndeclaredIdentifiers.push_back(
2822 getGlobalIdentifierID(F, Record[I++]));
2823 WeakUndeclaredIdentifiers.push_back(
2824 ReadSourceLocation(F, Record, I).getRawEncoding());
2825 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2826 }
2827 break;
2828
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002830 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 F.LocalNumSelectors = Record[0];
2832 unsigned LocalBaseSelectorID = Record[1];
2833 F.BaseSelectorID = getTotalNumSelectors();
2834
2835 if (F.LocalNumSelectors > 0) {
2836 // Introduce the global -> local mapping for selectors within this
2837 // module.
2838 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2839
2840 // Introduce the local -> global mapping for selectors within this
2841 // module.
2842 F.SelectorRemap.insertOrReplace(
2843 std::make_pair(LocalBaseSelectorID,
2844 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002845
2846 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 }
2848 break;
2849 }
2850
2851 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002852 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 if (Record[0])
2854 F.SelectorLookupTable
2855 = ASTSelectorLookupTable::Create(
2856 F.SelectorLookupTableData + Record[0],
2857 F.SelectorLookupTableData,
2858 ASTSelectorLookupTrait(*this, F));
2859 TotalNumMethodPoolEntries += Record[1];
2860 break;
2861
2862 case REFERENCED_SELECTOR_POOL:
2863 if (!Record.empty()) {
2864 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2865 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2866 Record[Idx++]));
2867 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2868 getRawEncoding());
2869 }
2870 }
2871 break;
2872
2873 case PP_COUNTER_VALUE:
2874 if (!Record.empty() && Listener)
2875 Listener->ReadCounter(F, Record[0]);
2876 break;
2877
2878 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002879 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 F.NumFileSortedDecls = Record[0];
2881 break;
2882
2883 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002884 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002885 F.LocalNumSLocEntries = Record[0];
2886 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002887 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002888 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002889 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002890 if (!F.SLocEntryBaseID) {
2891 Error("ran out of source locations");
2892 break;
2893 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002894 // Make our entry in the range map. BaseID is negative and growing, so
2895 // we invert it. Because we invert it, though, we need the other end of
2896 // the range.
2897 unsigned RangeStart =
2898 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2899 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2900 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2901
2902 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2903 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2904 GlobalSLocOffsetMap.insert(
2905 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2906 - SLocSpaceSize,&F));
2907
2908 // Initialize the remapping table.
2909 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002910 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002912 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2914
2915 TotalNumSLocEntries += F.LocalNumSLocEntries;
2916 break;
2917 }
2918
2919 case MODULE_OFFSET_MAP: {
2920 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002921 const unsigned char *Data = (const unsigned char*)Blob.data();
2922 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002923
2924 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2925 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2926 F.SLocRemap.insert(std::make_pair(0U, 0));
2927 F.SLocRemap.insert(std::make_pair(2U, 1));
2928 }
2929
Guy Benyei11169dd2012-12-18 14:30:41 +00002930 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002931 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2932 RemapBuilder;
2933 RemapBuilder SLocRemap(F.SLocRemap);
2934 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2935 RemapBuilder MacroRemap(F.MacroRemap);
2936 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2937 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2938 RemapBuilder SelectorRemap(F.SelectorRemap);
2939 RemapBuilder DeclRemap(F.DeclRemap);
2940 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002941
Richard Smithd8879c82015-08-24 21:59:32 +00002942 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002943 using namespace llvm::support;
2944 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 StringRef Name = StringRef((const char*)Data, Len);
2946 Data += Len;
2947 ModuleFile *OM = ModuleMgr.lookup(Name);
2948 if (!OM) {
2949 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002950 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 }
2952
Justin Bogner57ba0b22014-03-28 22:03:24 +00002953 uint32_t SLocOffset =
2954 endian::readNext<uint32_t, little, unaligned>(Data);
2955 uint32_t IdentifierIDOffset =
2956 endian::readNext<uint32_t, little, unaligned>(Data);
2957 uint32_t MacroIDOffset =
2958 endian::readNext<uint32_t, little, unaligned>(Data);
2959 uint32_t PreprocessedEntityIDOffset =
2960 endian::readNext<uint32_t, little, unaligned>(Data);
2961 uint32_t SubmoduleIDOffset =
2962 endian::readNext<uint32_t, little, unaligned>(Data);
2963 uint32_t SelectorIDOffset =
2964 endian::readNext<uint32_t, little, unaligned>(Data);
2965 uint32_t DeclIDOffset =
2966 endian::readNext<uint32_t, little, unaligned>(Data);
2967 uint32_t TypeIndexOffset =
2968 endian::readNext<uint32_t, little, unaligned>(Data);
2969
Ben Langmuir785180e2014-10-20 16:27:30 +00002970 uint32_t None = std::numeric_limits<uint32_t>::max();
2971
2972 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2973 RemapBuilder &Remap) {
2974 if (Offset != None)
2975 Remap.insert(std::make_pair(Offset,
2976 static_cast<int>(BaseOffset - Offset)));
2977 };
2978 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2979 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2980 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2981 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2982 PreprocessedEntityRemap);
2983 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2984 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2985 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2986 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002987
2988 // Global -> local mappings.
2989 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2990 }
2991 break;
2992 }
2993
2994 case SOURCE_MANAGER_LINE_TABLE:
2995 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002996 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002997 break;
2998
2999 case SOURCE_LOCATION_PRELOADS: {
3000 // Need to transform from the local view (1-based IDs) to the global view,
3001 // which is based off F.SLocEntryBaseID.
3002 if (!F.PreloadSLocEntries.empty()) {
3003 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003004 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003005 }
3006
3007 F.PreloadSLocEntries.swap(Record);
3008 break;
3009 }
3010
3011 case EXT_VECTOR_DECLS:
3012 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3013 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3014 break;
3015
3016 case VTABLE_USES:
3017 if (Record.size() % 3 != 0) {
3018 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003019 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 }
3021
3022 // Later tables overwrite earlier ones.
3023 // FIXME: Modules will have some trouble with this. This is clearly not
3024 // the right way to do this.
3025 VTableUses.clear();
3026
3027 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3028 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3029 VTableUses.push_back(
3030 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3031 VTableUses.push_back(Record[Idx++]);
3032 }
3033 break;
3034
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 case PENDING_IMPLICIT_INSTANTIATIONS:
3036 if (PendingInstantiations.size() % 2 != 0) {
3037 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003038 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 }
3040
3041 if (Record.size() % 2 != 0) {
3042 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003043 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003044 }
3045
3046 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3047 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3048 PendingInstantiations.push_back(
3049 ReadSourceLocation(F, Record, I).getRawEncoding());
3050 }
3051 break;
3052
3053 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003054 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003055 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003056 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003057 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3059 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3060 break;
3061
3062 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003063 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3064 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3065 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003066
3067 unsigned LocalBasePreprocessedEntityID = Record[0];
3068
3069 unsigned StartingID;
3070 if (!PP.getPreprocessingRecord())
3071 PP.createPreprocessingRecord();
3072 if (!PP.getPreprocessingRecord()->getExternalSource())
3073 PP.getPreprocessingRecord()->SetExternalSource(*this);
3074 StartingID
3075 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003076 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003077 F.BasePreprocessedEntityID = StartingID;
3078
3079 if (F.NumPreprocessedEntities > 0) {
3080 // Introduce the global -> local mapping for preprocessed entities in
3081 // this module.
3082 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3083
3084 // Introduce the local -> global mapping for preprocessed entities in
3085 // this module.
3086 F.PreprocessedEntityRemap.insertOrReplace(
3087 std::make_pair(LocalBasePreprocessedEntityID,
3088 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3089 }
3090
3091 break;
3092 }
3093
3094 case DECL_UPDATE_OFFSETS: {
3095 if (Record.size() % 2 != 0) {
3096 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003097 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003098 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003099 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3100 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3101 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3102
3103 // If we've already loaded the decl, perform the updates when we finish
3104 // loading this block.
3105 if (Decl *D = GetExistingDecl(ID))
3106 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3107 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 break;
3109 }
3110
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 case OBJC_CATEGORIES_MAP: {
3112 if (F.LocalNumObjCCategoriesInMap != 0) {
3113 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003114 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 }
3116
3117 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003118 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003119 break;
3120 }
3121
3122 case OBJC_CATEGORIES:
3123 F.ObjCCategories.swap(Record);
3124 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003125
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 case DIAG_PRAGMA_MAPPINGS:
3127 if (F.PragmaDiagMappings.empty())
3128 F.PragmaDiagMappings.swap(Record);
3129 else
3130 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3131 Record.begin(), Record.end());
3132 break;
3133
3134 case CUDA_SPECIAL_DECL_REFS:
3135 // Later tables overwrite earlier ones.
3136 // FIXME: Modules will have trouble with this.
3137 CUDASpecialDeclRefs.clear();
3138 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3139 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3140 break;
3141
3142 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003143 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 if (Record[0]) {
3146 F.HeaderFileInfoTable
3147 = HeaderFileInfoLookupTable::Create(
3148 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3149 (const unsigned char *)F.HeaderFileInfoTableData,
3150 HeaderFileInfoTrait(*this, F,
3151 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003152 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003153
3154 PP.getHeaderSearchInfo().SetExternalSource(this);
3155 if (!PP.getHeaderSearchInfo().getExternalLookup())
3156 PP.getHeaderSearchInfo().SetExternalLookup(this);
3157 }
3158 break;
3159 }
3160
3161 case FP_PRAGMA_OPTIONS:
3162 // Later tables overwrite earlier ones.
3163 FPPragmaOptions.swap(Record);
3164 break;
3165
3166 case OPENCL_EXTENSIONS:
3167 // Later tables overwrite earlier ones.
3168 OpenCLExtensions.swap(Record);
3169 break;
3170
3171 case TENTATIVE_DEFINITIONS:
3172 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3173 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3174 break;
3175
3176 case KNOWN_NAMESPACES:
3177 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3178 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3179 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003180
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003181 case UNDEFINED_BUT_USED:
3182 if (UndefinedButUsed.size() % 2 != 0) {
3183 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003184 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003185 }
3186
3187 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003188 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003189 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003190 }
3191 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003192 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3193 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003194 ReadSourceLocation(F, Record, I).getRawEncoding());
3195 }
3196 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003197 case DELETE_EXPRS_TO_ANALYZE:
3198 for (unsigned I = 0, N = Record.size(); I != N;) {
3199 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3200 const uint64_t Count = Record[I++];
3201 DelayedDeleteExprs.push_back(Count);
3202 for (uint64_t C = 0; C < Count; ++C) {
3203 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3204 bool IsArrayForm = Record[I++] == 1;
3205 DelayedDeleteExprs.push_back(IsArrayForm);
3206 }
3207 }
3208 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003209
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003211 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 // If we aren't loading a module (which has its own exports), make
3213 // all of the imported modules visible.
3214 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003215 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3216 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3217 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3218 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003219 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003220 }
3221 }
3222 break;
3223 }
3224
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 case MACRO_OFFSET: {
3226 if (F.LocalNumMacros != 0) {
3227 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003228 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003230 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 F.LocalNumMacros = Record[0];
3232 unsigned LocalBaseMacroID = Record[1];
3233 F.BaseMacroID = getTotalNumMacros();
3234
3235 if (F.LocalNumMacros > 0) {
3236 // Introduce the global -> local mapping for macros within this module.
3237 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3238
3239 // Introduce the local -> global mapping for macros within this module.
3240 F.MacroRemap.insertOrReplace(
3241 std::make_pair(LocalBaseMacroID,
3242 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003243
3244 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 }
3246 break;
3247 }
3248
Richard Smithe40f2ba2013-08-07 21:41:30 +00003249 case LATE_PARSED_TEMPLATE: {
3250 LateParsedTemplates.append(Record.begin(), Record.end());
3251 break;
3252 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003253
3254 case OPTIMIZE_PRAGMA_OPTIONS:
3255 if (Record.size() != 1) {
3256 Error("invalid pragma optimize record");
3257 return Failure;
3258 }
3259 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3260 break;
Nico Weber72889432014-09-06 01:25:55 +00003261
Nico Weber779355f2016-03-02 23:22:00 +00003262 case MSSTRUCT_PRAGMA_OPTIONS:
3263 if (Record.size() != 1) {
3264 Error("invalid pragma ms_struct record");
3265 return Failure;
3266 }
3267 PragmaMSStructState = Record[0];
3268 break;
3269
Nico Weber42932312016-03-03 00:17:35 +00003270 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3271 if (Record.size() != 2) {
3272 Error("invalid pragma ms_struct record");
3273 return Failure;
3274 }
3275 PragmaMSPointersToMembersState = Record[0];
3276 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3277 break;
3278
Nico Weber72889432014-09-06 01:25:55 +00003279 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3280 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3281 UnusedLocalTypedefNameCandidates.push_back(
3282 getGlobalDeclID(F, Record[I]));
3283 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003284
3285 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3286 if (Record.size() != 1) {
3287 Error("invalid cuda pragma options record");
3288 return Failure;
3289 }
3290 ForceCUDAHostDeviceDepth = Record[0];
3291 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003292 }
3293 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003294}
3295
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003296ASTReader::ASTReadResult
3297ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3298 const ModuleFile *ImportedBy,
3299 unsigned ClientLoadCapabilities) {
3300 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003301 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003302
Manman Ren11f2a472016-08-18 17:42:15 +00003303 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003304 // For an explicitly-loaded module, we don't care whether the original
3305 // module map file exists or matches.
3306 return Success;
3307 }
3308
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003309 // Try to resolve ModuleName in the current header search context and
3310 // verify that it is found in the same module map file as we saved. If the
3311 // top-level AST file is a main file, skip this check because there is no
3312 // usable header search context.
3313 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003314 "MODULE_NAME should come before MODULE_MAP_FILE");
3315 if (F.Kind == MK_ImplicitModule &&
3316 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3317 // An implicitly-loaded module file should have its module listed in some
3318 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003319 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003320 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3321 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3322 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003323 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003324 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3325 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3326 // This module was defined by an imported (explicit) module.
3327 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3328 << ASTFE->getName();
3329 else
3330 // This module was built with a different module map.
3331 Diag(diag::err_imported_module_not_found)
3332 << F.ModuleName << F.FileName << ImportedBy->FileName
3333 << F.ModuleMapPath;
3334 }
3335 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003336 }
3337
Richard Smithe842a472014-10-22 02:05:46 +00003338 assert(M->Name == F.ModuleName && "found module with different name");
3339
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003340 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003341 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003342 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3343 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003344 assert(ImportedBy && "top-level import should be verified");
3345 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3346 Diag(diag::err_imported_module_modmap_changed)
3347 << F.ModuleName << ImportedBy->FileName
3348 << ModMap->getName() << F.ModuleMapPath;
3349 return OutOfDate;
3350 }
3351
3352 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3353 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3354 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003355 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003356 const FileEntry *F =
3357 FileMgr.getFile(Filename, false, false);
3358 if (F == nullptr) {
3359 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3360 Error("could not find file '" + Filename +"' referenced by AST file");
3361 return OutOfDate;
3362 }
3363 AdditionalStoredMaps.insert(F);
3364 }
3365
3366 // Check any additional module map files (e.g. module.private.modulemap)
3367 // that are not in the pcm.
3368 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3369 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3370 // Remove files that match
3371 // Note: SmallPtrSet::erase is really remove
3372 if (!AdditionalStoredMaps.erase(ModMap)) {
3373 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3374 Diag(diag::err_module_different_modmap)
3375 << F.ModuleName << /*new*/0 << ModMap->getName();
3376 return OutOfDate;
3377 }
3378 }
3379 }
3380
3381 // Check any additional module map files that are in the pcm, but not
3382 // found in header search. Cases that match are already removed.
3383 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3384 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3385 Diag(diag::err_module_different_modmap)
3386 << F.ModuleName << /*not new*/1 << ModMap->getName();
3387 return OutOfDate;
3388 }
3389 }
3390
3391 if (Listener)
3392 Listener->ReadModuleMapFile(F.ModuleMapPath);
3393 return Success;
3394}
3395
3396
Douglas Gregorc1489562013-02-12 23:36:21 +00003397/// \brief Move the given method to the back of the global list of methods.
3398static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3399 // Find the entry for this selector in the method pool.
3400 Sema::GlobalMethodPool::iterator Known
3401 = S.MethodPool.find(Method->getSelector());
3402 if (Known == S.MethodPool.end())
3403 return;
3404
3405 // Retrieve the appropriate method list.
3406 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3407 : Known->second.second;
3408 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003409 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003410 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003411 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003412 Found = true;
3413 } else {
3414 // Keep searching.
3415 continue;
3416 }
3417 }
3418
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003419 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003420 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003421 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003422 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003423 }
3424}
3425
Richard Smithde711422015-04-23 21:20:19 +00003426void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003427 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003428 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003429 bool wasHidden = D->Hidden;
3430 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003431
Richard Smith49f906a2014-03-01 00:08:04 +00003432 if (wasHidden && SemaObj) {
3433 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3434 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003435 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003436 }
3437 }
3438}
3439
Richard Smith49f906a2014-03-01 00:08:04 +00003440void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003441 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003442 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003443 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003444 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003445 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003446 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003447 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003448
3449 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003450 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003451 // there is nothing more to do.
3452 continue;
3453 }
Richard Smith49f906a2014-03-01 00:08:04 +00003454
Guy Benyei11169dd2012-12-18 14:30:41 +00003455 if (!Mod->isAvailable()) {
3456 // Modules that aren't available cannot be made visible.
3457 continue;
3458 }
3459
3460 // Update the module's name visibility.
3461 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003462
Guy Benyei11169dd2012-12-18 14:30:41 +00003463 // If we've already deserialized any names from this module,
3464 // mark them as visible.
3465 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3466 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003467 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003468 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003469 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003470 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3471 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003472 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003473
Guy Benyei11169dd2012-12-18 14:30:41 +00003474 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003475 SmallVector<Module *, 16> Exports;
3476 Mod->getExportedModules(Exports);
3477 for (SmallVectorImpl<Module *>::iterator
3478 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3479 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003480 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003481 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 }
3483 }
3484}
3485
Richard Smith6561f922016-09-12 21:06:40 +00003486/// We've merged the definition \p MergedDef into the existing definition
3487/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3488/// visible.
3489void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3490 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003491 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3492 // in modules other than its owning module. We should instead give the
3493 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003494 if (Def->isHidden()) {
3495 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003496 if (!MergedDef->isHidden())
3497 Def->Hidden = false;
3498 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3499 getContext().mergeDefinitionIntoModule(
3500 Def, MergedDef->getImportedOwningModule(),
3501 /*NotifyListeners*/ false);
3502 PendingMergedDefinitionsToDeduplicate.insert(Def);
3503 } else {
3504 auto SubmoduleID = MergedDef->getOwningModuleID();
3505 assert(SubmoduleID && "hidden definition in no module");
3506 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3507 }
Richard Smith6561f922016-09-12 21:06:40 +00003508 }
3509}
3510
Douglas Gregore060e572013-01-25 01:03:03 +00003511bool ASTReader::loadGlobalIndex() {
3512 if (GlobalIndex)
3513 return false;
3514
3515 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3516 !Context.getLangOpts().Modules)
3517 return true;
3518
3519 // Try to load the global index.
3520 TriedLoadingGlobalIndex = true;
3521 StringRef ModuleCachePath
3522 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3523 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003524 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003525 if (!Result.first)
3526 return true;
3527
3528 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003529 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003530 return false;
3531}
3532
3533bool ASTReader::isGlobalIndexUnavailable() const {
3534 return Context.getLangOpts().Modules && UseGlobalIndex &&
3535 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3536}
3537
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003538static void updateModuleTimestamp(ModuleFile &MF) {
3539 // Overwrite the timestamp file contents so that file's mtime changes.
3540 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003541 std::error_code EC;
3542 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3543 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003544 return;
3545 OS << "Timestamp file\n";
3546}
3547
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003548/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3549/// cursor into the start of the given block ID, returning false on success and
3550/// true on failure.
3551static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003552 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003553 llvm::BitstreamEntry Entry = Cursor.advance();
3554 switch (Entry.Kind) {
3555 case llvm::BitstreamEntry::Error:
3556 case llvm::BitstreamEntry::EndBlock:
3557 return true;
3558
3559 case llvm::BitstreamEntry::Record:
3560 // Ignore top-level records.
3561 Cursor.skipRecord(Entry.ID);
3562 break;
3563
3564 case llvm::BitstreamEntry::SubBlock:
3565 if (Entry.ID == BlockID) {
3566 if (Cursor.EnterSubBlock(BlockID))
3567 return true;
3568 // Found it!
3569 return false;
3570 }
3571
3572 if (Cursor.SkipBlock())
3573 return true;
3574 }
3575 }
3576}
3577
Benjamin Kramer0772c422016-02-13 13:42:54 +00003578ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 ModuleKind Type,
3580 SourceLocation ImportLoc,
3581 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003582 llvm::SaveAndRestore<SourceLocation>
3583 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3584
Richard Smithd1c46742014-04-30 02:24:17 +00003585 // Defer any pending actions until we get to the end of reading the AST file.
3586 Deserializing AnASTFile(this);
3587
Guy Benyei11169dd2012-12-18 14:30:41 +00003588 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003589 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003590
3591 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003592 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003593 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003594 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003595 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003596 ClientLoadCapabilities)) {
3597 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003598 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003599 case OutOfDate:
3600 case VersionMismatch:
3601 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003602 case HadErrors: {
3603 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3604 for (const ImportedModule &IM : Loaded)
3605 LoadedSet.insert(IM.Mod);
3606
Douglas Gregor7029ce12013-03-19 00:28:20 +00003607 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003608 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003609 Context.getLangOpts().Modules
3610 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003611 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003612
3613 // If we find that any modules are unusable, the global index is going
3614 // to be out-of-date. Just remove it.
3615 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003616 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003617 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003618 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003619 case Success:
3620 break;
3621 }
3622
3623 // Here comes stuff that we only do once the entire chain is loaded.
3624
3625 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003626 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3627 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003628 M != MEnd; ++M) {
3629 ModuleFile &F = *M->Mod;
3630
3631 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003632 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3633 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003634
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003635 // Read the extension blocks.
3636 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3637 if (ASTReadResult Result = ReadExtensionBlock(F))
3638 return Result;
3639 }
3640
Guy Benyei11169dd2012-12-18 14:30:41 +00003641 // Once read, set the ModuleFile bit base offset and update the size in
3642 // bits of all files we've seen.
3643 F.GlobalBitOffset = TotalModulesSizeInBits;
3644 TotalModulesSizeInBits += F.SizeInBits;
3645 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3646
3647 // Preload SLocEntries.
3648 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3649 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3650 // Load it through the SourceManager and don't call ReadSLocEntry()
3651 // directly because the entry may have already been loaded in which case
3652 // calling ReadSLocEntry() directly would trigger an assertion in
3653 // SourceManager.
3654 SourceMgr.getLoadedSLocEntryByID(Index);
3655 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003656
3657 // Preload all the pending interesting identifiers by marking them out of
3658 // date.
3659 for (auto Offset : F.PreloadIdentifierOffsets) {
3660 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3661 F.IdentifierTableData + Offset);
3662
3663 ASTIdentifierLookupTrait Trait(*this, F);
3664 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3665 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003666 auto &II = PP.getIdentifierTable().getOwn(Key);
3667 II.setOutOfDate(true);
3668
3669 // Mark this identifier as being from an AST file so that we can track
3670 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003671 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003672
3673 // Associate the ID with the identifier so that the writer can reuse it.
3674 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3675 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003676 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003677 }
3678
Douglas Gregor603cd862013-03-22 18:50:14 +00003679 // Setup the import locations and notify the module manager that we've
3680 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003681 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3682 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003683 M != MEnd; ++M) {
3684 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003685
3686 ModuleMgr.moduleFileAccepted(&F);
3687
3688 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003689 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003690 // FIXME: We assume that locations from PCH / preamble do not need
3691 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003692 if (!M->ImportedBy)
3693 F.ImportLoc = M->ImportLoc;
3694 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003695 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003696 }
3697
Richard Smith33e0f7e2015-07-22 02:08:40 +00003698 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003699 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3700 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003701 // Mark all of the identifiers in the identifier table as being out of date,
3702 // so that various accessors know to check the loaded modules when the
3703 // identifier is used.
3704 //
3705 // For C++ modules, we don't need information on many identifiers (just
3706 // those that provide macros or are poisoned), so we mark all of
3707 // the interesting ones via PreloadIdentifierOffsets.
3708 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3709 IdEnd = PP.getIdentifierTable().end();
3710 Id != IdEnd; ++Id)
3711 Id->second->setOutOfDate(true);
3712 }
Manman Rena0f31a02016-04-29 19:04:05 +00003713 // Mark selectors as out of date.
3714 for (auto Sel : SelectorGeneration)
3715 SelectorOutOfDate[Sel.first] = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003716
3717 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003718 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3719 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003720 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3721 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003722
3723 switch (Unresolved.Kind) {
3724 case UnresolvedModuleRef::Conflict:
3725 if (ResolvedMod) {
3726 Module::Conflict Conflict;
3727 Conflict.Other = ResolvedMod;
3728 Conflict.Message = Unresolved.String.str();
3729 Unresolved.Mod->Conflicts.push_back(Conflict);
3730 }
3731 continue;
3732
3733 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003734 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003735 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003736 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003737
Douglas Gregorfb912652013-03-20 21:10:35 +00003738 case UnresolvedModuleRef::Export:
3739 if (ResolvedMod || Unresolved.IsWildcard)
3740 Unresolved.Mod->Exports.push_back(
3741 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3742 continue;
3743 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003744 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003745 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003746
3747 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3748 // Might be unnecessary as use declarations are only used to build the
3749 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003750
3751 InitializeContext();
3752
Richard Smith3d8e97e2013-10-18 06:54:39 +00003753 if (SemaObj)
3754 UpdateSema();
3755
Guy Benyei11169dd2012-12-18 14:30:41 +00003756 if (DeserializationListener)
3757 DeserializationListener->ReaderInitialized(this);
3758
3759 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003760 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 PrimaryModule.OriginalSourceFileID
3762 = FileID::get(PrimaryModule.SLocEntryBaseID
3763 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3764
3765 // If this AST file is a precompiled preamble, then set the
3766 // preamble file ID of the source manager to the file source file
3767 // from which the preamble was built.
3768 if (Type == MK_Preamble) {
3769 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3770 } else if (Type == MK_MainFile) {
3771 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3772 }
3773 }
3774
3775 // For any Objective-C class definitions we have already loaded, make sure
3776 // that we load any additional categories.
3777 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3778 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3779 ObjCClassesLoaded[I],
3780 PreviousGeneration);
3781 }
Douglas Gregore060e572013-01-25 01:03:03 +00003782
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003783 if (PP.getHeaderSearchInfo()
3784 .getHeaderSearchOpts()
3785 .ModulesValidateOncePerBuildSession) {
3786 // Now we are certain that the module and all modules it depends on are
3787 // up to date. Create or update timestamp files for modules that are
3788 // located in the module cache (not for PCH files that could be anywhere
3789 // in the filesystem).
3790 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3791 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003792 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003793 updateModuleTimestamp(*M.Mod);
3794 }
3795 }
3796 }
3797
Guy Benyei11169dd2012-12-18 14:30:41 +00003798 return Success;
3799}
3800
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003801static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003802
Ben Langmuir70a1b812015-03-24 04:43:52 +00003803/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3804static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003805 return Stream.canSkipToPos(4) &&
3806 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003807 Stream.Read(8) == 'P' &&
3808 Stream.Read(8) == 'C' &&
3809 Stream.Read(8) == 'H';
3810}
3811
Richard Smith0f99d6a2015-08-09 08:48:41 +00003812static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3813 switch (Kind) {
3814 case MK_PCH:
3815 return 0; // PCH
3816 case MK_ImplicitModule:
3817 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003818 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003819 return 1; // module
3820 case MK_MainFile:
3821 case MK_Preamble:
3822 return 2; // main source file
3823 }
3824 llvm_unreachable("unknown module kind");
3825}
3826
Guy Benyei11169dd2012-12-18 14:30:41 +00003827ASTReader::ASTReadResult
3828ASTReader::ReadASTCore(StringRef FileName,
3829 ModuleKind Type,
3830 SourceLocation ImportLoc,
3831 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003832 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003833 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003834 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003835 unsigned ClientLoadCapabilities) {
3836 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003837 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003838 ModuleManager::AddModuleResult AddResult
3839 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003840 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003841 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003842 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003843
Douglas Gregor7029ce12013-03-19 00:28:20 +00003844 switch (AddResult) {
3845 case ModuleManager::AlreadyLoaded:
3846 return Success;
3847
3848 case ModuleManager::NewlyLoaded:
3849 // Load module file below.
3850 break;
3851
3852 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003853 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003854 // it.
3855 if (ClientLoadCapabilities & ARR_Missing)
3856 return Missing;
3857
3858 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003859 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003860 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003861 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003862 return Failure;
3863
3864 case ModuleManager::OutOfDate:
3865 // We couldn't load the module file because it is out-of-date. If the
3866 // client can handle out-of-date, return it.
3867 if (ClientLoadCapabilities & ARR_OutOfDate)
3868 return OutOfDate;
3869
3870 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003871 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003872 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003873 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003874 return Failure;
3875 }
3876
Douglas Gregor7029ce12013-03-19 00:28:20 +00003877 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003878
3879 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3880 // module?
3881 if (FileName != "-") {
3882 CurrentDir = llvm::sys::path::parent_path(FileName);
3883 if (CurrentDir.empty()) CurrentDir = ".";
3884 }
3885
3886 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003887 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003888 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003889 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3890
Guy Benyei11169dd2012-12-18 14:30:41 +00003891 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003892 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003893 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3894 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003895 return Failure;
3896 }
3897
3898 // This is used for compatibility with older PCH formats.
3899 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003900 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003901 llvm::BitstreamEntry Entry = Stream.advance();
3902
3903 switch (Entry.Kind) {
3904 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003905 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003906 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003907 Error("invalid record at top-level of AST file");
3908 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003909
3910 case llvm::BitstreamEntry::SubBlock:
3911 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003912 }
3913
Chris Lattnerefa77172013-01-20 00:00:22 +00003914 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003915 case CONTROL_BLOCK_ID:
3916 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003917 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003918 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003919 // Check that we didn't try to load a non-module AST file as a module.
3920 //
3921 // FIXME: Should we also perform the converse check? Loading a module as
3922 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00003923 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3924 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00003925 F.ModuleName.empty()) {
3926 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3927 if (Result != OutOfDate ||
3928 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3929 Diag(diag::err_module_file_not_module) << FileName;
3930 return Result;
3931 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 break;
3933
3934 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003935 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 case OutOfDate: return OutOfDate;
3937 case VersionMismatch: return VersionMismatch;
3938 case ConfigurationMismatch: return ConfigurationMismatch;
3939 case HadErrors: return HadErrors;
3940 }
3941 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003942
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 case AST_BLOCK_ID:
3944 if (!HaveReadControlBlock) {
3945 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003946 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003947 return VersionMismatch;
3948 }
3949
3950 // Record that we've loaded this module.
3951 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3952 return Success;
3953
3954 default:
3955 if (Stream.SkipBlock()) {
3956 Error("malformed block record in AST file");
3957 return Failure;
3958 }
3959 break;
3960 }
3961 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003962
3963 return Success;
3964}
3965
3966/// Parse a record and blob containing module file extension metadata.
3967static bool parseModuleFileExtensionMetadata(
3968 const SmallVectorImpl<uint64_t> &Record,
3969 StringRef Blob,
3970 ModuleFileExtensionMetadata &Metadata) {
3971 if (Record.size() < 4) return true;
3972
3973 Metadata.MajorVersion = Record[0];
3974 Metadata.MinorVersion = Record[1];
3975
3976 unsigned BlockNameLen = Record[2];
3977 unsigned UserInfoLen = Record[3];
3978
3979 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3980
3981 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3982 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3983 Blob.data() + BlockNameLen + UserInfoLen);
3984 return false;
3985}
3986
3987ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3988 BitstreamCursor &Stream = F.Stream;
3989
3990 RecordData Record;
3991 while (true) {
3992 llvm::BitstreamEntry Entry = Stream.advance();
3993 switch (Entry.Kind) {
3994 case llvm::BitstreamEntry::SubBlock:
3995 if (Stream.SkipBlock())
3996 return Failure;
3997
3998 continue;
3999
4000 case llvm::BitstreamEntry::EndBlock:
4001 return Success;
4002
4003 case llvm::BitstreamEntry::Error:
4004 return HadErrors;
4005
4006 case llvm::BitstreamEntry::Record:
4007 break;
4008 }
4009
4010 Record.clear();
4011 StringRef Blob;
4012 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4013 switch (RecCode) {
4014 case EXTENSION_METADATA: {
4015 ModuleFileExtensionMetadata Metadata;
4016 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4017 return Failure;
4018
4019 // Find a module file extension with this block name.
4020 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4021 if (Known == ModuleFileExtensions.end()) break;
4022
4023 // Form a reader.
4024 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4025 F, Stream)) {
4026 F.ExtensionReaders.push_back(std::move(Reader));
4027 }
4028
4029 break;
4030 }
4031 }
4032 }
4033
4034 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004035}
4036
Richard Smitha7e2cc62015-05-01 01:53:09 +00004037void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 // If there's a listener, notify them that we "read" the translation unit.
4039 if (DeserializationListener)
4040 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4041 Context.getTranslationUnitDecl());
4042
Guy Benyei11169dd2012-12-18 14:30:41 +00004043 // FIXME: Find a better way to deal with collisions between these
4044 // built-in types. Right now, we just ignore the problem.
4045
4046 // Load the special types.
4047 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4048 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4049 if (!Context.CFConstantStringTypeDecl)
4050 Context.setCFConstantStringType(GetType(String));
4051 }
4052
4053 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4054 QualType FileType = GetType(File);
4055 if (FileType.isNull()) {
4056 Error("FILE type is NULL");
4057 return;
4058 }
4059
4060 if (!Context.FILEDecl) {
4061 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4062 Context.setFILEDecl(Typedef->getDecl());
4063 else {
4064 const TagType *Tag = FileType->getAs<TagType>();
4065 if (!Tag) {
4066 Error("Invalid FILE type in AST file");
4067 return;
4068 }
4069 Context.setFILEDecl(Tag->getDecl());
4070 }
4071 }
4072 }
4073
4074 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4075 QualType Jmp_bufType = GetType(Jmp_buf);
4076 if (Jmp_bufType.isNull()) {
4077 Error("jmp_buf type is NULL");
4078 return;
4079 }
4080
4081 if (!Context.jmp_bufDecl) {
4082 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4083 Context.setjmp_bufDecl(Typedef->getDecl());
4084 else {
4085 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4086 if (!Tag) {
4087 Error("Invalid jmp_buf type in AST file");
4088 return;
4089 }
4090 Context.setjmp_bufDecl(Tag->getDecl());
4091 }
4092 }
4093 }
4094
4095 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4096 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4097 if (Sigjmp_bufType.isNull()) {
4098 Error("sigjmp_buf type is NULL");
4099 return;
4100 }
4101
4102 if (!Context.sigjmp_bufDecl) {
4103 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4104 Context.setsigjmp_bufDecl(Typedef->getDecl());
4105 else {
4106 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4107 assert(Tag && "Invalid sigjmp_buf type in AST file");
4108 Context.setsigjmp_bufDecl(Tag->getDecl());
4109 }
4110 }
4111 }
4112
4113 if (unsigned ObjCIdRedef
4114 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4115 if (Context.ObjCIdRedefinitionType.isNull())
4116 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4117 }
4118
4119 if (unsigned ObjCClassRedef
4120 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4121 if (Context.ObjCClassRedefinitionType.isNull())
4122 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4123 }
4124
4125 if (unsigned ObjCSelRedef
4126 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4127 if (Context.ObjCSelRedefinitionType.isNull())
4128 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4129 }
4130
4131 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4132 QualType Ucontext_tType = GetType(Ucontext_t);
4133 if (Ucontext_tType.isNull()) {
4134 Error("ucontext_t type is NULL");
4135 return;
4136 }
4137
4138 if (!Context.ucontext_tDecl) {
4139 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4140 Context.setucontext_tDecl(Typedef->getDecl());
4141 else {
4142 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4143 assert(Tag && "Invalid ucontext_t type in AST file");
4144 Context.setucontext_tDecl(Tag->getDecl());
4145 }
4146 }
4147 }
4148 }
4149
4150 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4151
4152 // If there were any CUDA special declarations, deserialize them.
4153 if (!CUDASpecialDeclRefs.empty()) {
4154 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4155 Context.setcudaConfigureCallDecl(
4156 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4157 }
Richard Smith56be7542014-03-21 00:33:59 +00004158
Guy Benyei11169dd2012-12-18 14:30:41 +00004159 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004160 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004161 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004162 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004163 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004164 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004165 if (Import.ImportLoc.isValid())
4166 PP.makeModuleVisible(Imported, Import.ImportLoc);
4167 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004168 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004169 }
4170 ImportedModules.clear();
4171}
4172
4173void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004174 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004175}
4176
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004177/// \brief Reads and return the signature record from \p PCH's control block, or
4178/// else returns 0.
4179static ASTFileSignature readASTFileSignature(StringRef PCH) {
4180 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004181 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004182 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004183
4184 // Scan for the CONTROL_BLOCK_ID block.
4185 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4186 return 0;
4187
4188 // Scan for SIGNATURE inside the control block.
4189 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004190 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004191 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004192 if (Entry.Kind != llvm::BitstreamEntry::Record)
Ben Langmuir487ea142014-10-23 18:05:36 +00004193 return 0;
4194
4195 Record.clear();
4196 StringRef Blob;
4197 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4198 return Record[0];
4199 }
4200}
4201
Guy Benyei11169dd2012-12-18 14:30:41 +00004202/// \brief Retrieve the name of the original source file name
4203/// directly from the AST file, without actually loading the AST
4204/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004205std::string ASTReader::getOriginalSourceFile(
4206 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004207 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004209 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004210 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004211 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4212 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 return std::string();
4214 }
4215
4216 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004217 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004218
4219 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004220 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4222 return std::string();
4223 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004224
Chris Lattnere7b154b2013-01-19 21:39:22 +00004225 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004226 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004227 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4228 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004229 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004230
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004231 // Scan for ORIGINAL_FILE inside the control block.
4232 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004233 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004234 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004235 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4236 return std::string();
4237
4238 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4239 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4240 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004242
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004244 StringRef Blob;
4245 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4246 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004247 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004248}
4249
4250namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004251
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 class SimplePCHValidator : public ASTReaderListener {
4253 const LangOptions &ExistingLangOpts;
4254 const TargetOptions &ExistingTargetOpts;
4255 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004256 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004258
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 public:
4260 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4261 const TargetOptions &ExistingTargetOpts,
4262 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004263 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 FileManager &FileMgr)
4265 : ExistingLangOpts(ExistingLangOpts),
4266 ExistingTargetOpts(ExistingTargetOpts),
4267 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004268 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 FileMgr(FileMgr)
4270 {
4271 }
4272
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004273 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4274 bool AllowCompatibleDifferences) override {
4275 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4276 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004278
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004279 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4280 bool AllowCompatibleDifferences) override {
4281 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4282 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004284
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004285 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4286 StringRef SpecificModuleCachePath,
4287 bool Complain) override {
4288 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4289 ExistingModuleCachePath,
4290 nullptr, ExistingLangOpts);
4291 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004292
Craig Topper3e89dfe2014-03-13 02:13:41 +00004293 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4294 bool Complain,
4295 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004296 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004297 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 }
4299 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004300
4301} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004302
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004303bool ASTReader::readASTFileControlBlock(
4304 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004305 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004306 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004307 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004309 // FIXME: This allows use of the VFS; we do not allow use of the
4310 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004311 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 if (!Buffer) {
4313 return true;
4314 }
4315
4316 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004317 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004318
4319 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004320 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004322
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004323 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004324 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004325 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004326
4327 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004328 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004329 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004330 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004331
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004333 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004334 bool DoneWithControlBlock = false;
4335 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004336 llvm::BitstreamEntry Entry = Stream.advance();
4337
4338 switch (Entry.Kind) {
4339 case llvm::BitstreamEntry::SubBlock: {
4340 switch (Entry.ID) {
4341 case OPTIONS_BLOCK_ID: {
4342 std::string IgnoredSuggestedPredefines;
4343 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4344 /*AllowCompatibleConfigurationMismatch*/ false,
Manman Ren47a44452016-07-26 17:12:17 +00004345 Listener, IgnoredSuggestedPredefines,
4346 ValidateDiagnosticOptions) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004347 return true;
4348 break;
4349 }
4350
4351 case INPUT_FILES_BLOCK_ID:
4352 InputFilesCursor = Stream;
4353 if (Stream.SkipBlock() ||
4354 (NeedsInputFiles &&
4355 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4356 return true;
4357 break;
4358
4359 default:
4360 if (Stream.SkipBlock())
4361 return true;
4362 break;
4363 }
4364
4365 continue;
4366 }
4367
4368 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004369 DoneWithControlBlock = true;
4370 break;
Richard Smith0516b182015-09-08 19:40:14 +00004371
4372 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004373 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004374
4375 case llvm::BitstreamEntry::Record:
4376 break;
4377 }
4378
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004379 if (DoneWithControlBlock) break;
4380
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004382 StringRef Blob;
4383 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004384 switch ((ControlRecordTypes)RecCode) {
4385 case METADATA: {
4386 if (Record[0] != VERSION_MAJOR)
4387 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004388
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004389 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004390 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004391
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004392 break;
4393 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004394 case MODULE_NAME:
4395 Listener.ReadModuleName(Blob);
4396 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004397 case MODULE_DIRECTORY:
4398 ModuleDir = Blob;
4399 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004400 case MODULE_MAP_FILE: {
4401 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004402 auto Path = ReadString(Record, Idx);
4403 ResolveImportedPath(Path, ModuleDir);
4404 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004405 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004406 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004407 case INPUT_FILE_OFFSETS: {
4408 if (!NeedsInputFiles)
4409 break;
4410
4411 unsigned NumInputFiles = Record[0];
4412 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004413 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004414 for (unsigned I = 0; I != NumInputFiles; ++I) {
4415 // Go find this input file.
4416 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004417
4418 if (isSystemFile && !NeedsSystemInputFiles)
4419 break; // the rest are system input files
4420
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004421 BitstreamCursor &Cursor = InputFilesCursor;
4422 SavedStreamPosition SavedPosition(Cursor);
4423 Cursor.JumpToBit(InputFileOffs[I]);
4424
4425 unsigned Code = Cursor.ReadCode();
4426 RecordData Record;
4427 StringRef Blob;
4428 bool shouldContinue = false;
4429 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4430 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004431 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004432 std::string Filename = Blob;
4433 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004434 shouldContinue = Listener.visitInputFile(
4435 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004436 break;
4437 }
4438 if (!shouldContinue)
4439 break;
4440 }
4441 break;
4442 }
4443
Richard Smithd4b230b2014-10-27 23:01:16 +00004444 case IMPORTS: {
4445 if (!NeedsImports)
4446 break;
4447
4448 unsigned Idx = 0, N = Record.size();
4449 while (Idx < N) {
4450 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004451 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004452 std::string Filename = ReadString(Record, Idx);
4453 ResolveImportedPath(Filename, ModuleDir);
4454 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004455 }
4456 break;
4457 }
4458
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004459 default:
4460 // No other validation to perform.
4461 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 }
4463 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004464
4465 // Look for module file extension blocks, if requested.
4466 if (FindModuleFileExtensions) {
4467 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4468 bool DoneWithExtensionBlock = false;
4469 while (!DoneWithExtensionBlock) {
4470 llvm::BitstreamEntry Entry = Stream.advance();
4471
4472 switch (Entry.Kind) {
4473 case llvm::BitstreamEntry::SubBlock:
4474 if (Stream.SkipBlock())
4475 return true;
4476
4477 continue;
4478
4479 case llvm::BitstreamEntry::EndBlock:
4480 DoneWithExtensionBlock = true;
4481 continue;
4482
4483 case llvm::BitstreamEntry::Error:
4484 return true;
4485
4486 case llvm::BitstreamEntry::Record:
4487 break;
4488 }
4489
4490 Record.clear();
4491 StringRef Blob;
4492 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4493 switch (RecCode) {
4494 case EXTENSION_METADATA: {
4495 ModuleFileExtensionMetadata Metadata;
4496 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4497 return true;
4498
4499 Listener.readModuleFileExtension(Metadata);
4500 break;
4501 }
4502 }
4503 }
4504 }
4505 }
4506
4507 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004508}
4509
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004510bool ASTReader::isAcceptableASTFile(
4511 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004512 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004513 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4514 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004515 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4516 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004517 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004518 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004519 validator,
4520 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004521}
4522
Ben Langmuir2c9af442014-04-10 17:57:43 +00004523ASTReader::ASTReadResult
4524ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 // Enter the submodule block.
4526 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4527 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004528 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 }
4530
4531 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4532 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004533 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 RecordData Record;
4535 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004536 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4537
4538 switch (Entry.Kind) {
4539 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4540 case llvm::BitstreamEntry::Error:
4541 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004542 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004543 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004544 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004545 case llvm::BitstreamEntry::Record:
4546 // The interesting case.
4547 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004549
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004551 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004552 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004553 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4554
4555 if ((Kind == SUBMODULE_METADATA) != First) {
4556 Error("submodule metadata record should be at beginning of block");
4557 return Failure;
4558 }
4559 First = false;
4560
4561 // Submodule information is only valid if we have a current module.
4562 // FIXME: Should we error on these cases?
4563 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4564 Kind != SUBMODULE_DEFINITION)
4565 continue;
4566
4567 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 default: // Default behavior: ignore.
4569 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004570
Richard Smith03478d92014-10-23 22:12:14 +00004571 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004572 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004574 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 }
Richard Smith03478d92014-10-23 22:12:14 +00004576
Chris Lattner0e6c9402013-01-20 02:38:54 +00004577 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004578 unsigned Idx = 0;
4579 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4580 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4581 bool IsFramework = Record[Idx++];
4582 bool IsExplicit = Record[Idx++];
4583 bool IsSystem = Record[Idx++];
4584 bool IsExternC = Record[Idx++];
4585 bool InferSubmodules = Record[Idx++];
4586 bool InferExplicitSubmodules = Record[Idx++];
4587 bool InferExportWildcard = Record[Idx++];
4588 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004589
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004590 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004591 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004592 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004593
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 // Retrieve this (sub)module from the module map, creating it if
4595 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004596 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004598
4599 // FIXME: set the definition loc for CurrentModule, or call
4600 // ModMap.setInferredModuleAllowedBy()
4601
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4603 if (GlobalIndex >= SubmodulesLoaded.size() ||
4604 SubmodulesLoaded[GlobalIndex]) {
4605 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004606 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004608
Douglas Gregor7029ce12013-03-19 00:28:20 +00004609 if (!ParentModule) {
4610 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4611 if (CurFile != F.File) {
4612 if (!Diags.isDiagnosticInFlight()) {
4613 Diag(diag::err_module_file_conflict)
4614 << CurrentModule->getTopLevelModuleName()
4615 << CurFile->getName()
4616 << F.File->getName();
4617 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004618 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004619 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004620 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004621
4622 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004623 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004624
Adrian Prantl15bcf702015-06-30 17:39:43 +00004625 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 CurrentModule->IsFromModuleFile = true;
4627 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004628 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 CurrentModule->InferSubmodules = InferSubmodules;
4630 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4631 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004632 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 if (DeserializationListener)
4634 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4635
4636 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004637
Richard Smith8a3e39a2016-03-28 21:31:09 +00004638 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004639 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004640 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004641 CurrentModule->UnresolvedConflicts.clear();
4642 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004643
4644 // The module is available unless it's missing a requirement; relevant
4645 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4646 // Missing headers that were present when the module was built do not
4647 // make it unavailable -- if we got this far, this must be an explicitly
4648 // imported module file.
4649 CurrentModule->Requirements.clear();
4650 CurrentModule->MissingHeaders.clear();
4651 CurrentModule->IsMissingRequirement =
4652 ParentModule && ParentModule->IsMissingRequirement;
4653 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004654 break;
4655 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004656
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004658 std::string Filename = Blob;
4659 ResolveImportedPath(F, Filename);
4660 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004662 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4663 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004664 // This can be a spurious difference caused by changing the VFS to
4665 // point to a different copy of the file, and it is too late to
4666 // to rebuild safely.
4667 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4668 // after input file validation only real problems would remain and we
4669 // could just error. For now, assume it's okay.
4670 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 }
4672 }
4673 break;
4674 }
4675
Richard Smith202210b2014-10-24 20:23:01 +00004676 case SUBMODULE_HEADER:
4677 case SUBMODULE_EXCLUDED_HEADER:
4678 case SUBMODULE_PRIVATE_HEADER:
4679 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004680 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4681 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004682 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004683
Richard Smith202210b2014-10-24 20:23:01 +00004684 case SUBMODULE_TEXTUAL_HEADER:
4685 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4686 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4687 // them here.
4688 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004689
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004691 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004692 break;
4693 }
4694
4695 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004696 std::string Dirname = Blob;
4697 ResolveImportedPath(F, Dirname);
4698 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004699 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004700 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4701 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004702 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4703 Error("mismatched umbrella directories in submodule");
4704 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 }
4706 }
4707 break;
4708 }
4709
4710 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 F.BaseSubmoduleID = getTotalNumSubmodules();
4712 F.LocalNumSubmodules = Record[0];
4713 unsigned LocalBaseSubmoduleID = Record[1];
4714 if (F.LocalNumSubmodules > 0) {
4715 // Introduce the global -> local mapping for submodules within this
4716 // module.
4717 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4718
4719 // Introduce the local -> global mapping for submodules within this
4720 // module.
4721 F.SubmoduleRemap.insertOrReplace(
4722 std::make_pair(LocalBaseSubmoduleID,
4723 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004724
Ben Langmuir52ca6782014-10-20 16:27:32 +00004725 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4726 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 break;
4728 }
4729
4730 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004732 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 Unresolved.File = &F;
4734 Unresolved.Mod = CurrentModule;
4735 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004736 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004738 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 }
4740 break;
4741 }
4742
4743 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004744 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004745 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004746 Unresolved.File = &F;
4747 Unresolved.Mod = CurrentModule;
4748 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004749 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004751 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 }
4753
4754 // Once we've loaded the set of exports, there's no reason to keep
4755 // the parsed, unresolved exports around.
4756 CurrentModule->UnresolvedExports.clear();
4757 break;
4758 }
4759 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004760 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 Context.getTargetInfo());
4762 break;
4763 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004764
4765 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004766 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004767 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004768 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004769
4770 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004771 CurrentModule->ConfigMacros.push_back(Blob.str());
4772 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004773
4774 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004775 UnresolvedModuleRef Unresolved;
4776 Unresolved.File = &F;
4777 Unresolved.Mod = CurrentModule;
4778 Unresolved.ID = Record[0];
4779 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4780 Unresolved.IsWildcard = false;
4781 Unresolved.String = Blob;
4782 UnresolvedModuleRefs.push_back(Unresolved);
4783 break;
4784 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004785
4786 case SUBMODULE_INITIALIZERS:
4787 SmallVector<uint32_t, 16> Inits;
4788 for (auto &ID : Record)
4789 Inits.push_back(getGlobalDeclID(F, ID));
4790 Context.addLazyModuleInitializers(CurrentModule, Inits);
4791 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 }
4793 }
4794}
4795
4796/// \brief Parse the record that corresponds to a LangOptions data
4797/// structure.
4798///
4799/// This routine parses the language options from the AST file and then gives
4800/// them to the AST listener if one is set.
4801///
4802/// \returns true if the listener deems the file unacceptable, false otherwise.
4803bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4804 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004805 ASTReaderListener &Listener,
4806 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 LangOptions LangOpts;
4808 unsigned Idx = 0;
4809#define LANGOPT(Name, Bits, Default, Description) \
4810 LangOpts.Name = Record[Idx++];
4811#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4812 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4813#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004814#define SANITIZER(NAME, ID) \
4815 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004816#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004817
Ben Langmuircd98cb72015-06-23 18:20:18 +00004818 for (unsigned N = Record[Idx++]; N; --N)
4819 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4820
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4822 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4823 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004824
Ben Langmuird4a667a2015-06-23 18:20:23 +00004825 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004826
4827 // Comment options.
4828 for (unsigned N = Record[Idx++]; N; --N) {
4829 LangOpts.CommentOpts.BlockCommandNames.push_back(
4830 ReadString(Record, Idx));
4831 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004832 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004833
Samuel Antaoee8fb302016-01-06 13:42:12 +00004834 // OpenMP offloading options.
4835 for (unsigned N = Record[Idx++]; N; --N) {
4836 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4837 }
4838
4839 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4840
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004841 return Listener.ReadLanguageOptions(LangOpts, Complain,
4842 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004843}
4844
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004845bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4846 ASTReaderListener &Listener,
4847 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004848 unsigned Idx = 0;
4849 TargetOptions TargetOpts;
4850 TargetOpts.Triple = ReadString(Record, Idx);
4851 TargetOpts.CPU = ReadString(Record, Idx);
4852 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 for (unsigned N = Record[Idx++]; N; --N) {
4854 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4855 }
4856 for (unsigned N = Record[Idx++]; N; --N) {
4857 TargetOpts.Features.push_back(ReadString(Record, Idx));
4858 }
4859
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004860 return Listener.ReadTargetOptions(TargetOpts, Complain,
4861 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004862}
4863
4864bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4865 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004866 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004868#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004869#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004870 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004871#include "clang/Basic/DiagnosticOptions.def"
4872
Richard Smith3be1cb22014-08-07 00:24:21 +00004873 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004874 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004875 for (unsigned N = Record[Idx++]; N; --N)
4876 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004877
4878 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4879}
4880
4881bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4882 ASTReaderListener &Listener) {
4883 FileSystemOptions FSOpts;
4884 unsigned Idx = 0;
4885 FSOpts.WorkingDir = ReadString(Record, Idx);
4886 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4887}
4888
4889bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4890 bool Complain,
4891 ASTReaderListener &Listener) {
4892 HeaderSearchOptions HSOpts;
4893 unsigned Idx = 0;
4894 HSOpts.Sysroot = ReadString(Record, Idx);
4895
4896 // Include entries.
4897 for (unsigned N = Record[Idx++]; N; --N) {
4898 std::string Path = ReadString(Record, Idx);
4899 frontend::IncludeDirGroup Group
4900 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004901 bool IsFramework = Record[Idx++];
4902 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004903 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4904 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004905 }
4906
4907 // System header prefixes.
4908 for (unsigned N = Record[Idx++]; N; --N) {
4909 std::string Prefix = ReadString(Record, Idx);
4910 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004911 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004912 }
4913
4914 HSOpts.ResourceDir = ReadString(Record, Idx);
4915 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004916 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004917 HSOpts.DisableModuleHash = Record[Idx++];
4918 HSOpts.UseBuiltinIncludes = Record[Idx++];
4919 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4920 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4921 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004922 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004923
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004924 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4925 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004926}
4927
4928bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4929 bool Complain,
4930 ASTReaderListener &Listener,
4931 std::string &SuggestedPredefines) {
4932 PreprocessorOptions PPOpts;
4933 unsigned Idx = 0;
4934
4935 // Macro definitions/undefs
4936 for (unsigned N = Record[Idx++]; N; --N) {
4937 std::string Macro = ReadString(Record, Idx);
4938 bool IsUndef = Record[Idx++];
4939 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4940 }
4941
4942 // Includes
4943 for (unsigned N = Record[Idx++]; N; --N) {
4944 PPOpts.Includes.push_back(ReadString(Record, Idx));
4945 }
4946
4947 // Macro Includes
4948 for (unsigned N = Record[Idx++]; N; --N) {
4949 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4950 }
4951
4952 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004953 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004954 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4955 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4956 PPOpts.ObjCXXARCStandardLibrary =
4957 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4958 SuggestedPredefines.clear();
4959 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4960 SuggestedPredefines);
4961}
4962
4963std::pair<ModuleFile *, unsigned>
4964ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4965 GlobalPreprocessedEntityMapType::iterator
4966 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4967 assert(I != GlobalPreprocessedEntityMap.end() &&
4968 "Corrupted global preprocessed entity map");
4969 ModuleFile *M = I->second;
4970 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4971 return std::make_pair(M, LocalIndex);
4972}
4973
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004974llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004975ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4976 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4977 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4978 Mod.NumPreprocessedEntities);
4979
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004980 return llvm::make_range(PreprocessingRecord::iterator(),
4981 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004982}
4983
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004984llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004985ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004986 return llvm::make_range(
4987 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4988 ModuleDeclIterator(this, &Mod,
4989 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004990}
4991
4992PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4993 PreprocessedEntityID PPID = Index+1;
4994 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4995 ModuleFile &M = *PPInfo.first;
4996 unsigned LocalIndex = PPInfo.second;
4997 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4998
Guy Benyei11169dd2012-12-18 14:30:41 +00004999 if (!PP.getPreprocessingRecord()) {
5000 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005001 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005002 }
5003
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005004 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
5005 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5006
5007 llvm::BitstreamEntry Entry =
5008 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5009 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005010 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005011
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005013 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5014 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005016 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 RecordData Record;
5018 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005019 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5020 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 switch (RecType) {
5022 case PPD_MACRO_EXPANSION: {
5023 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005024 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005025 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 if (isBuiltin)
5027 Name = getLocalIdentifier(M, Record[1]);
5028 else {
Richard Smith66a81862015-05-04 02:25:31 +00005029 PreprocessedEntityID GlobalID =
5030 getGlobalPreprocessedEntityID(M, Record[1]);
5031 Def = cast<MacroDefinitionRecord>(
5032 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 }
5034
5035 MacroExpansion *ME;
5036 if (isBuiltin)
5037 ME = new (PPRec) MacroExpansion(Name, Range);
5038 else
5039 ME = new (PPRec) MacroExpansion(Def, Range);
5040
5041 return ME;
5042 }
5043
5044 case PPD_MACRO_DEFINITION: {
5045 // Decode the identifier info and then check again; if the macro is
5046 // still defined and associated with the identifier,
5047 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005048 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005049
5050 if (DeserializationListener)
5051 DeserializationListener->MacroDefinitionRead(PPID, MD);
5052
5053 return MD;
5054 }
5055
5056 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005057 const char *FullFileNameStart = Blob.data() + Record[0];
5058 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005059 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 if (!FullFileName.empty())
5061 File = PP.getFileManager().getFile(FullFileName);
5062
5063 // FIXME: Stable encoding
5064 InclusionDirective::InclusionKind Kind
5065 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5066 InclusionDirective *ID
5067 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005068 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 Record[1], Record[3],
5070 File,
5071 Range);
5072 return ID;
5073 }
5074 }
5075
5076 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5077}
5078
5079/// \brief \arg SLocMapI points at a chunk of a module that contains no
5080/// preprocessed entities or the entities it contains are not the ones we are
5081/// looking for. Find the next module that contains entities and return the ID
5082/// of the first entry.
5083PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5084 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5085 ++SLocMapI;
5086 for (GlobalSLocOffsetMapType::const_iterator
5087 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5088 ModuleFile &M = *SLocMapI->second;
5089 if (M.NumPreprocessedEntities)
5090 return M.BasePreprocessedEntityID;
5091 }
5092
5093 return getTotalNumPreprocessedEntities();
5094}
5095
5096namespace {
5097
Guy Benyei11169dd2012-12-18 14:30:41 +00005098struct PPEntityComp {
5099 const ASTReader &Reader;
5100 ModuleFile &M;
5101
5102 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5103
5104 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5105 SourceLocation LHS = getLoc(L);
5106 SourceLocation RHS = getLoc(R);
5107 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5108 }
5109
5110 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5111 SourceLocation LHS = getLoc(L);
5112 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5113 }
5114
5115 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5116 SourceLocation RHS = getLoc(R);
5117 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5118 }
5119
5120 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005121 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 }
5123};
5124
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005125} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005126
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005127PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5128 bool EndsAfter) const {
5129 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 return getTotalNumPreprocessedEntities();
5131
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005132 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5133 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5135 "Corrupted global sloc offset map");
5136
5137 if (SLocMapI->second->NumPreprocessedEntities == 0)
5138 return findNextPreprocessedEntity(SLocMapI);
5139
5140 ModuleFile &M = *SLocMapI->second;
5141 typedef const PPEntityOffset *pp_iterator;
5142 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5143 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5144
5145 size_t Count = M.NumPreprocessedEntities;
5146 size_t Half;
5147 pp_iterator First = pp_begin;
5148 pp_iterator PPI;
5149
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005150 if (EndsAfter) {
5151 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005152 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005153 } else {
5154 // Do a binary search manually instead of using std::lower_bound because
5155 // The end locations of entities may be unordered (when a macro expansion
5156 // is inside another macro argument), but for this case it is not important
5157 // whether we get the first macro expansion or its containing macro.
5158 while (Count > 0) {
5159 Half = Count / 2;
5160 PPI = First;
5161 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005162 if (SourceMgr.isBeforeInTranslationUnit(
5163 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005164 First = PPI;
5165 ++First;
5166 Count = Count - Half - 1;
5167 } else
5168 Count = Half;
5169 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 }
5171
5172 if (PPI == pp_end)
5173 return findNextPreprocessedEntity(SLocMapI);
5174
5175 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5176}
5177
Guy Benyei11169dd2012-12-18 14:30:41 +00005178/// \brief Returns a pair of [Begin, End) indices of preallocated
5179/// preprocessed entities that \arg Range encompasses.
5180std::pair<unsigned, unsigned>
5181 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5182 if (Range.isInvalid())
5183 return std::make_pair(0,0);
5184 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5185
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005186 PreprocessedEntityID BeginID =
5187 findPreprocessedEntity(Range.getBegin(), false);
5188 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 return std::make_pair(BeginID, EndID);
5190}
5191
5192/// \brief Optionally returns true or false if the preallocated preprocessed
5193/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005194Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 FileID FID) {
5196 if (FID.isInvalid())
5197 return false;
5198
5199 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5200 ModuleFile &M = *PPInfo.first;
5201 unsigned LocalIndex = PPInfo.second;
5202 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5203
Richard Smithcb34bd32016-03-27 07:28:06 +00005204 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 if (Loc.isInvalid())
5206 return false;
5207
5208 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5209 return true;
5210 else
5211 return false;
5212}
5213
5214namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005215
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 /// \brief Visitor used to search for information about a header file.
5217 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 const FileEntry *FE;
5219
David Blaikie05785d12013-02-20 22:23:23 +00005220 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005221
5222 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005223 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5224 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005225
5226 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 HeaderFileInfoLookupTable *Table
5228 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5229 if (!Table)
5230 return false;
5231
5232 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005233 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 if (Pos == Table->end())
5235 return false;
5236
Richard Smithbdf2d932015-07-30 03:37:16 +00005237 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 return true;
5239 }
5240
David Blaikie05785d12013-02-20 22:23:23 +00005241 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005243
5244} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005245
5246HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005247 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005248 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005249 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005251
5252 return HeaderFileInfo();
5253}
5254
5255void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5256 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005257 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5259 ModuleFile &F = *(*I);
5260 unsigned Idx = 0;
5261 DiagStates.clear();
5262 assert(!Diag.DiagStates.empty());
5263 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5264 while (Idx < F.PragmaDiagMappings.size()) {
5265 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5266 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5267 if (DiagStateID != 0) {
5268 Diag.DiagStatePoints.push_back(
5269 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5270 FullSourceLoc(Loc, SourceMgr)));
5271 continue;
5272 }
5273
5274 assert(DiagStateID == 0);
5275 // A new DiagState was created here.
5276 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5277 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5278 DiagStates.push_back(NewState);
5279 Diag.DiagStatePoints.push_back(
5280 DiagnosticsEngine::DiagStatePoint(NewState,
5281 FullSourceLoc(Loc, SourceMgr)));
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005282 while (true) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 assert(Idx < F.PragmaDiagMappings.size() &&
5284 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5285 if (Idx >= F.PragmaDiagMappings.size()) {
5286 break; // Something is messed up but at least avoid infinite loop in
5287 // release build.
5288 }
5289 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5290 if (DiagID == (unsigned)-1) {
5291 break; // no more diag/map pairs for this location.
5292 }
Alp Tokerc726c362014-06-10 09:31:37 +00005293 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5294 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5295 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 }
5297 }
5298 }
5299}
5300
5301/// \brief Get the correct cursor and offset for loading a type.
5302ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5303 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5304 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5305 ModuleFile *M = I->second;
5306 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5307}
5308
5309/// \brief Read and return the type with the given index..
5310///
5311/// The index is the type ID, shifted and minus the number of predefs. This
5312/// routine actually reads the record corresponding to the type at the given
5313/// location. It is a helper routine for GetType, which deals with reading type
5314/// IDs.
5315QualType ASTReader::readTypeRecord(unsigned Index) {
5316 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005317 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005318
5319 // Keep track of where we are in the stream, then jump back there
5320 // after reading this type.
5321 SavedStreamPosition SavedPosition(DeclsCursor);
5322
5323 ReadingKindTracker ReadingKind(Read_Type, *this);
5324
5325 // Note that we are loading a type record.
5326 Deserializing AType(this);
5327
5328 unsigned Idx = 0;
5329 DeclsCursor.JumpToBit(Loc.Offset);
5330 RecordData Record;
5331 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005332 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 case TYPE_EXT_QUAL: {
5334 if (Record.size() != 2) {
5335 Error("Incorrect encoding of extended qualifier type");
5336 return QualType();
5337 }
5338 QualType Base = readType(*Loc.F, Record, Idx);
5339 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5340 return Context.getQualifiedType(Base, Quals);
5341 }
5342
5343 case TYPE_COMPLEX: {
5344 if (Record.size() != 1) {
5345 Error("Incorrect encoding of complex type");
5346 return QualType();
5347 }
5348 QualType ElemType = readType(*Loc.F, Record, Idx);
5349 return Context.getComplexType(ElemType);
5350 }
5351
5352 case TYPE_POINTER: {
5353 if (Record.size() != 1) {
5354 Error("Incorrect encoding of pointer type");
5355 return QualType();
5356 }
5357 QualType PointeeType = readType(*Loc.F, Record, Idx);
5358 return Context.getPointerType(PointeeType);
5359 }
5360
Reid Kleckner8a365022013-06-24 17:51:48 +00005361 case TYPE_DECAYED: {
5362 if (Record.size() != 1) {
5363 Error("Incorrect encoding of decayed type");
5364 return QualType();
5365 }
5366 QualType OriginalType = readType(*Loc.F, Record, Idx);
5367 QualType DT = Context.getAdjustedParameterType(OriginalType);
5368 if (!isa<DecayedType>(DT))
5369 Error("Decayed type does not decay");
5370 return DT;
5371 }
5372
Reid Kleckner0503a872013-12-05 01:23:43 +00005373 case TYPE_ADJUSTED: {
5374 if (Record.size() != 2) {
5375 Error("Incorrect encoding of adjusted type");
5376 return QualType();
5377 }
5378 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5379 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5380 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5381 }
5382
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 case TYPE_BLOCK_POINTER: {
5384 if (Record.size() != 1) {
5385 Error("Incorrect encoding of block pointer type");
5386 return QualType();
5387 }
5388 QualType PointeeType = readType(*Loc.F, Record, Idx);
5389 return Context.getBlockPointerType(PointeeType);
5390 }
5391
5392 case TYPE_LVALUE_REFERENCE: {
5393 if (Record.size() != 2) {
5394 Error("Incorrect encoding of lvalue reference type");
5395 return QualType();
5396 }
5397 QualType PointeeType = readType(*Loc.F, Record, Idx);
5398 return Context.getLValueReferenceType(PointeeType, Record[1]);
5399 }
5400
5401 case TYPE_RVALUE_REFERENCE: {
5402 if (Record.size() != 1) {
5403 Error("Incorrect encoding of rvalue reference type");
5404 return QualType();
5405 }
5406 QualType PointeeType = readType(*Loc.F, Record, Idx);
5407 return Context.getRValueReferenceType(PointeeType);
5408 }
5409
5410 case TYPE_MEMBER_POINTER: {
5411 if (Record.size() != 2) {
5412 Error("Incorrect encoding of member pointer type");
5413 return QualType();
5414 }
5415 QualType PointeeType = readType(*Loc.F, Record, Idx);
5416 QualType ClassType = readType(*Loc.F, Record, Idx);
5417 if (PointeeType.isNull() || ClassType.isNull())
5418 return QualType();
5419
5420 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5421 }
5422
5423 case TYPE_CONSTANT_ARRAY: {
5424 QualType ElementType = readType(*Loc.F, Record, Idx);
5425 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5426 unsigned IndexTypeQuals = Record[2];
5427 unsigned Idx = 3;
5428 llvm::APInt Size = ReadAPInt(Record, Idx);
5429 return Context.getConstantArrayType(ElementType, Size,
5430 ASM, IndexTypeQuals);
5431 }
5432
5433 case TYPE_INCOMPLETE_ARRAY: {
5434 QualType ElementType = readType(*Loc.F, Record, Idx);
5435 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5436 unsigned IndexTypeQuals = Record[2];
5437 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5438 }
5439
5440 case TYPE_VARIABLE_ARRAY: {
5441 QualType ElementType = readType(*Loc.F, Record, Idx);
5442 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5443 unsigned IndexTypeQuals = Record[2];
5444 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5445 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5446 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5447 ASM, IndexTypeQuals,
5448 SourceRange(LBLoc, RBLoc));
5449 }
5450
5451 case TYPE_VECTOR: {
5452 if (Record.size() != 3) {
5453 Error("incorrect encoding of vector type in AST file");
5454 return QualType();
5455 }
5456
5457 QualType ElementType = readType(*Loc.F, Record, Idx);
5458 unsigned NumElements = Record[1];
5459 unsigned VecKind = Record[2];
5460 return Context.getVectorType(ElementType, NumElements,
5461 (VectorType::VectorKind)VecKind);
5462 }
5463
5464 case TYPE_EXT_VECTOR: {
5465 if (Record.size() != 3) {
5466 Error("incorrect encoding of extended vector type in AST file");
5467 return QualType();
5468 }
5469
5470 QualType ElementType = readType(*Loc.F, Record, Idx);
5471 unsigned NumElements = Record[1];
5472 return Context.getExtVectorType(ElementType, NumElements);
5473 }
5474
5475 case TYPE_FUNCTION_NO_PROTO: {
5476 if (Record.size() != 6) {
5477 Error("incorrect encoding of no-proto function type");
5478 return QualType();
5479 }
5480 QualType ResultType = readType(*Loc.F, Record, Idx);
5481 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5482 (CallingConv)Record[4], Record[5]);
5483 return Context.getFunctionNoProtoType(ResultType, Info);
5484 }
5485
5486 case TYPE_FUNCTION_PROTO: {
5487 QualType ResultType = readType(*Loc.F, Record, Idx);
5488
5489 FunctionProtoType::ExtProtoInfo EPI;
5490 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5491 /*hasregparm*/ Record[2],
5492 /*regparm*/ Record[3],
5493 static_cast<CallingConv>(Record[4]),
5494 /*produces*/ Record[5]);
5495
5496 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005497
5498 EPI.Variadic = Record[Idx++];
5499 EPI.HasTrailingReturn = Record[Idx++];
5500 EPI.TypeQuals = Record[Idx++];
5501 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005502 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005503 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005504
5505 unsigned NumParams = Record[Idx++];
5506 SmallVector<QualType, 16> ParamTypes;
5507 for (unsigned I = 0; I != NumParams; ++I)
5508 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5509
John McCall18afab72016-03-01 00:49:02 +00005510 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5511 if (Idx != Record.size()) {
5512 for (unsigned I = 0; I != NumParams; ++I)
5513 ExtParameterInfos.push_back(
5514 FunctionProtoType::ExtParameterInfo
5515 ::getFromOpaqueValue(Record[Idx++]));
5516 EPI.ExtParameterInfos = ExtParameterInfos.data();
5517 }
5518
5519 assert(Idx == Record.size());
5520
Jordan Rose5c382722013-03-08 21:51:21 +00005521 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005522 }
5523
5524 case TYPE_UNRESOLVED_USING: {
5525 unsigned Idx = 0;
5526 return Context.getTypeDeclType(
5527 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5528 }
5529
5530 case TYPE_TYPEDEF: {
5531 if (Record.size() != 2) {
5532 Error("incorrect encoding of typedef type");
5533 return QualType();
5534 }
5535 unsigned Idx = 0;
5536 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5537 QualType Canonical = readType(*Loc.F, Record, Idx);
5538 if (!Canonical.isNull())
5539 Canonical = Context.getCanonicalType(Canonical);
5540 return Context.getTypedefType(Decl, Canonical);
5541 }
5542
5543 case TYPE_TYPEOF_EXPR:
5544 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5545
5546 case TYPE_TYPEOF: {
5547 if (Record.size() != 1) {
5548 Error("incorrect encoding of typeof(type) in AST file");
5549 return QualType();
5550 }
5551 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5552 return Context.getTypeOfType(UnderlyingType);
5553 }
5554
5555 case TYPE_DECLTYPE: {
5556 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5557 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5558 }
5559
5560 case TYPE_UNARY_TRANSFORM: {
5561 QualType BaseType = readType(*Loc.F, Record, Idx);
5562 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5563 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5564 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5565 }
5566
Richard Smith74aeef52013-04-26 16:15:35 +00005567 case TYPE_AUTO: {
5568 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005569 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005570 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005571 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005572 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005573
5574 case TYPE_RECORD: {
5575 if (Record.size() != 2) {
5576 Error("incorrect encoding of record type");
5577 return QualType();
5578 }
5579 unsigned Idx = 0;
5580 bool IsDependent = Record[Idx++];
5581 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5582 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5583 QualType T = Context.getRecordType(RD);
5584 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5585 return T;
5586 }
5587
5588 case TYPE_ENUM: {
5589 if (Record.size() != 2) {
5590 Error("incorrect encoding of enum type");
5591 return QualType();
5592 }
5593 unsigned Idx = 0;
5594 bool IsDependent = Record[Idx++];
5595 QualType T
5596 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5597 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5598 return T;
5599 }
5600
5601 case TYPE_ATTRIBUTED: {
5602 if (Record.size() != 3) {
5603 Error("incorrect encoding of attributed type");
5604 return QualType();
5605 }
5606 QualType modifiedType = readType(*Loc.F, Record, Idx);
5607 QualType equivalentType = readType(*Loc.F, Record, Idx);
5608 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5609 return Context.getAttributedType(kind, modifiedType, equivalentType);
5610 }
5611
5612 case TYPE_PAREN: {
5613 if (Record.size() != 1) {
5614 Error("incorrect encoding of paren type");
5615 return QualType();
5616 }
5617 QualType InnerType = readType(*Loc.F, Record, Idx);
5618 return Context.getParenType(InnerType);
5619 }
5620
5621 case TYPE_PACK_EXPANSION: {
5622 if (Record.size() != 2) {
5623 Error("incorrect encoding of pack expansion type");
5624 return QualType();
5625 }
5626 QualType Pattern = readType(*Loc.F, Record, Idx);
5627 if (Pattern.isNull())
5628 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005629 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005630 if (Record[1])
5631 NumExpansions = Record[1] - 1;
5632 return Context.getPackExpansionType(Pattern, NumExpansions);
5633 }
5634
5635 case TYPE_ELABORATED: {
5636 unsigned Idx = 0;
5637 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5638 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5639 QualType NamedType = readType(*Loc.F, Record, Idx);
5640 return Context.getElaboratedType(Keyword, NNS, NamedType);
5641 }
5642
5643 case TYPE_OBJC_INTERFACE: {
5644 unsigned Idx = 0;
5645 ObjCInterfaceDecl *ItfD
5646 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5647 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5648 }
5649
Manman Rene6be26c2016-09-13 17:25:08 +00005650 case TYPE_OBJC_TYPE_PARAM: {
5651 unsigned Idx = 0;
5652 ObjCTypeParamDecl *Decl
5653 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5654 unsigned NumProtos = Record[Idx++];
5655 SmallVector<ObjCProtocolDecl*, 4> Protos;
5656 for (unsigned I = 0; I != NumProtos; ++I)
5657 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5658 return Context.getObjCTypeParamType(Decl, Protos);
5659 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005660 case TYPE_OBJC_OBJECT: {
5661 unsigned Idx = 0;
5662 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005663 unsigned NumTypeArgs = Record[Idx++];
5664 SmallVector<QualType, 4> TypeArgs;
5665 for (unsigned I = 0; I != NumTypeArgs; ++I)
5666 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005667 unsigned NumProtos = Record[Idx++];
5668 SmallVector<ObjCProtocolDecl*, 4> Protos;
5669 for (unsigned I = 0; I != NumProtos; ++I)
5670 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005671 bool IsKindOf = Record[Idx++];
5672 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005673 }
5674
5675 case TYPE_OBJC_OBJECT_POINTER: {
5676 unsigned Idx = 0;
5677 QualType Pointee = readType(*Loc.F, Record, Idx);
5678 return Context.getObjCObjectPointerType(Pointee);
5679 }
5680
5681 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5682 unsigned Idx = 0;
5683 QualType Parm = readType(*Loc.F, Record, Idx);
5684 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005685 return Context.getSubstTemplateTypeParmType(
5686 cast<TemplateTypeParmType>(Parm),
5687 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005688 }
5689
5690 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5691 unsigned Idx = 0;
5692 QualType Parm = readType(*Loc.F, Record, Idx);
5693 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5694 return Context.getSubstTemplateTypeParmPackType(
5695 cast<TemplateTypeParmType>(Parm),
5696 ArgPack);
5697 }
5698
5699 case TYPE_INJECTED_CLASS_NAME: {
5700 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5701 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5702 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5703 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005704 const Type *T = nullptr;
5705 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5706 if (const Type *Existing = DI->getTypeForDecl()) {
5707 T = Existing;
5708 break;
5709 }
5710 }
5711 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005712 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005713 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5714 DI->setTypeForDecl(T);
5715 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005716 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005717 }
5718
5719 case TYPE_TEMPLATE_TYPE_PARM: {
5720 unsigned Idx = 0;
5721 unsigned Depth = Record[Idx++];
5722 unsigned Index = Record[Idx++];
5723 bool Pack = Record[Idx++];
5724 TemplateTypeParmDecl *D
5725 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5726 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5727 }
5728
5729 case TYPE_DEPENDENT_NAME: {
5730 unsigned Idx = 0;
5731 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5732 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005733 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 QualType Canon = readType(*Loc.F, Record, Idx);
5735 if (!Canon.isNull())
5736 Canon = Context.getCanonicalType(Canon);
5737 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5738 }
5739
5740 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5741 unsigned Idx = 0;
5742 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5743 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005744 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005745 unsigned NumArgs = Record[Idx++];
5746 SmallVector<TemplateArgument, 8> Args;
5747 Args.reserve(NumArgs);
5748 while (NumArgs--)
5749 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5750 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005751 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005752 }
5753
5754 case TYPE_DEPENDENT_SIZED_ARRAY: {
5755 unsigned Idx = 0;
5756
5757 // ArrayType
5758 QualType ElementType = readType(*Loc.F, Record, Idx);
5759 ArrayType::ArraySizeModifier ASM
5760 = (ArrayType::ArraySizeModifier)Record[Idx++];
5761 unsigned IndexTypeQuals = Record[Idx++];
5762
5763 // DependentSizedArrayType
5764 Expr *NumElts = ReadExpr(*Loc.F);
5765 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5766
5767 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5768 IndexTypeQuals, Brackets);
5769 }
5770
5771 case TYPE_TEMPLATE_SPECIALIZATION: {
5772 unsigned Idx = 0;
5773 bool IsDependent = Record[Idx++];
5774 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5775 SmallVector<TemplateArgument, 8> Args;
5776 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5777 QualType Underlying = readType(*Loc.F, Record, Idx);
5778 QualType T;
5779 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00005780 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005781 else
David Majnemer6fbeee32016-07-07 04:43:07 +00005782 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00005783 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5784 return T;
5785 }
5786
5787 case TYPE_ATOMIC: {
5788 if (Record.size() != 1) {
5789 Error("Incorrect encoding of atomic type");
5790 return QualType();
5791 }
5792 QualType ValueType = readType(*Loc.F, Record, Idx);
5793 return Context.getAtomicType(ValueType);
5794 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005795
Joey Goulye3c85de2016-12-01 11:30:49 +00005796 case TYPE_PIPE: {
5797 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00005798 Error("Incorrect encoding of pipe type");
5799 return QualType();
5800 }
5801
5802 // Reading the pipe element type.
5803 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00005804 unsigned ReadOnly = Record[1];
5805 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00005806 }
5807
Guy Benyei11169dd2012-12-18 14:30:41 +00005808 }
5809 llvm_unreachable("Invalid TypeCode!");
5810}
5811
Richard Smith564417a2014-03-20 21:47:22 +00005812void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5813 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005814 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005815 const RecordData &Record, unsigned &Idx) {
5816 ExceptionSpecificationType EST =
5817 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005818 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005819 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005820 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005821 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005822 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005823 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005824 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005825 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005826 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5827 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005828 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005829 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005830 }
5831}
5832
Guy Benyei11169dd2012-12-18 14:30:41 +00005833class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5834 ASTReader &Reader;
5835 ModuleFile &F;
5836 const ASTReader::RecordData &Record;
5837 unsigned &Idx;
5838
5839 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5840 unsigned &I) {
5841 return Reader.ReadSourceLocation(F, R, I);
5842 }
5843
5844 template<typename T>
5845 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5846 return Reader.ReadDeclAs<T>(F, Record, Idx);
5847 }
5848
5849public:
5850 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5851 const ASTReader::RecordData &Record, unsigned &Idx)
5852 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5853 { }
5854
5855 // We want compile-time assurance that we've enumerated all of
5856 // these, so unfortunately we have to declare them first, then
5857 // define them out-of-line.
5858#define ABSTRACT_TYPELOC(CLASS, PARENT)
5859#define TYPELOC(CLASS, PARENT) \
5860 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5861#include "clang/AST/TypeLocNodes.def"
5862
5863 void VisitFunctionTypeLoc(FunctionTypeLoc);
5864 void VisitArrayTypeLoc(ArrayTypeLoc);
5865};
5866
5867void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5868 // nothing to do
5869}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005870
Guy Benyei11169dd2012-12-18 14:30:41 +00005871void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5872 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5873 if (TL.needsExtraLocalData()) {
5874 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5875 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5876 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5877 TL.setModeAttr(Record[Idx++]);
5878 }
5879}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005880
Guy Benyei11169dd2012-12-18 14:30:41 +00005881void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5882 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5883}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005884
Guy Benyei11169dd2012-12-18 14:30:41 +00005885void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5886 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5887}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005888
Reid Kleckner8a365022013-06-24 17:51:48 +00005889void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5890 // nothing to do
5891}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005892
Reid Kleckner0503a872013-12-05 01:23:43 +00005893void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5894 // nothing to do
5895}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005896
Guy Benyei11169dd2012-12-18 14:30:41 +00005897void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5898 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5899}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005900
Guy Benyei11169dd2012-12-18 14:30:41 +00005901void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5902 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5903}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005904
Guy Benyei11169dd2012-12-18 14:30:41 +00005905void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5906 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5907}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005908
Guy Benyei11169dd2012-12-18 14:30:41 +00005909void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5910 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5911 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5912}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005913
Guy Benyei11169dd2012-12-18 14:30:41 +00005914void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5915 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5916 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5917 if (Record[Idx++])
5918 TL.setSizeExpr(Reader.ReadExpr(F));
5919 else
Craig Toppera13603a2014-05-22 05:54:18 +00005920 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005921}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005922
Guy Benyei11169dd2012-12-18 14:30:41 +00005923void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5924 VisitArrayTypeLoc(TL);
5925}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005926
Guy Benyei11169dd2012-12-18 14:30:41 +00005927void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5928 VisitArrayTypeLoc(TL);
5929}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005930
Guy Benyei11169dd2012-12-18 14:30:41 +00005931void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5932 VisitArrayTypeLoc(TL);
5933}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005934
Guy Benyei11169dd2012-12-18 14:30:41 +00005935void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5936 DependentSizedArrayTypeLoc TL) {
5937 VisitArrayTypeLoc(TL);
5938}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005939
Guy Benyei11169dd2012-12-18 14:30:41 +00005940void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5941 DependentSizedExtVectorTypeLoc TL) {
5942 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5943}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005944
Guy Benyei11169dd2012-12-18 14:30:41 +00005945void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5946 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5947}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005948
Guy Benyei11169dd2012-12-18 14:30:41 +00005949void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5950 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5951}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005952
Guy Benyei11169dd2012-12-18 14:30:41 +00005953void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5954 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5955 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5956 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5957 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005958 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5959 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005960 }
5961}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005962
Guy Benyei11169dd2012-12-18 14:30:41 +00005963void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5964 VisitFunctionTypeLoc(TL);
5965}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005966
Guy Benyei11169dd2012-12-18 14:30:41 +00005967void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5968 VisitFunctionTypeLoc(TL);
5969}
5970void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5971 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5972}
5973void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5974 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5975}
5976void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5977 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5978 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5979 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5980}
5981void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5982 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5983 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5984 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5985 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5986}
5987void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5988 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5989}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005990
Guy Benyei11169dd2012-12-18 14:30:41 +00005991void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5992 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5993 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5994 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5995 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5996}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005997
Guy Benyei11169dd2012-12-18 14:30:41 +00005998void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5999 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6000}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006001
Guy Benyei11169dd2012-12-18 14:30:41 +00006002void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6003 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6004}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006005
Guy Benyei11169dd2012-12-18 14:30:41 +00006006void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6007 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6008}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006009
Guy Benyei11169dd2012-12-18 14:30:41 +00006010void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6011 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
6012 if (TL.hasAttrOperand()) {
6013 SourceRange range;
6014 range.setBegin(ReadSourceLocation(Record, Idx));
6015 range.setEnd(ReadSourceLocation(Record, Idx));
6016 TL.setAttrOperandParensRange(range);
6017 }
6018 if (TL.hasAttrExprOperand()) {
6019 if (Record[Idx++])
6020 TL.setAttrExprOperand(Reader.ReadExpr(F));
6021 else
Craig Toppera13603a2014-05-22 05:54:18 +00006022 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006023 } else if (TL.hasAttrEnumOperand())
6024 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
6025}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006026
Guy Benyei11169dd2012-12-18 14:30:41 +00006027void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6028 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6029}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006030
Guy Benyei11169dd2012-12-18 14:30:41 +00006031void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6032 SubstTemplateTypeParmTypeLoc TL) {
6033 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6034}
6035void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6036 SubstTemplateTypeParmPackTypeLoc TL) {
6037 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6038}
6039void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6040 TemplateSpecializationTypeLoc TL) {
6041 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
6042 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
6043 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
6044 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
6045 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6046 TL.setArgLocInfo(i,
6047 Reader.GetTemplateArgumentLocInfo(F,
6048 TL.getTypePtr()->getArg(i).getKind(),
6049 Record, Idx));
6050}
6051void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6052 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
6053 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
6054}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006055
Guy Benyei11169dd2012-12-18 14:30:41 +00006056void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6057 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
6058 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
6059}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006060
Guy Benyei11169dd2012-12-18 14:30:41 +00006061void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6062 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6063}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006064
Guy Benyei11169dd2012-12-18 14:30:41 +00006065void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6066 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
6067 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
6068 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6069}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006070
Guy Benyei11169dd2012-12-18 14:30:41 +00006071void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6072 DependentTemplateSpecializationTypeLoc TL) {
6073 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
6074 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
6075 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
6076 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
6077 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
6078 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
6079 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6080 TL.setArgLocInfo(I,
6081 Reader.GetTemplateArgumentLocInfo(F,
6082 TL.getTypePtr()->getArg(I).getKind(),
6083 Record, Idx));
6084}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006085
Guy Benyei11169dd2012-12-18 14:30:41 +00006086void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6087 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
6088}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006089
Guy Benyei11169dd2012-12-18 14:30:41 +00006090void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6091 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6092}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006093
Manman Rene6be26c2016-09-13 17:25:08 +00006094void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6095 if (TL.getNumProtocols()) {
6096 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
6097 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
6098 }
6099 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6100 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
6101}
6102
Guy Benyei11169dd2012-12-18 14:30:41 +00006103void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6104 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006105 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
6106 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
6107 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6108 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
6109 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
6110 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006111 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6112 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
6113}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006114
Guy Benyei11169dd2012-12-18 14:30:41 +00006115void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6116 TL.setStarLoc(ReadSourceLocation(Record, Idx));
6117}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006118
Guy Benyei11169dd2012-12-18 14:30:41 +00006119void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6120 TL.setKWLoc(ReadSourceLocation(Record, Idx));
6121 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
6122 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
6123}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006124
Xiuli Pan9c14e282016-01-09 12:53:17 +00006125void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6126 TL.setKWLoc(ReadSourceLocation(Record, Idx));
6127}
Guy Benyei11169dd2012-12-18 14:30:41 +00006128
6129TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
6130 const RecordData &Record,
6131 unsigned &Idx) {
6132 QualType InfoTy = readType(F, Record, Idx);
6133 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006134 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006135
6136 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6137 TypeLocReader TLR(*this, F, Record, Idx);
6138 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6139 TLR.Visit(TL);
6140 return TInfo;
6141}
6142
6143QualType ASTReader::GetType(TypeID ID) {
6144 unsigned FastQuals = ID & Qualifiers::FastMask;
6145 unsigned Index = ID >> Qualifiers::FastWidth;
6146
6147 if (Index < NUM_PREDEF_TYPE_IDS) {
6148 QualType T;
6149 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006150 case PREDEF_TYPE_NULL_ID:
6151 return QualType();
6152 case PREDEF_TYPE_VOID_ID:
6153 T = Context.VoidTy;
6154 break;
6155 case PREDEF_TYPE_BOOL_ID:
6156 T = Context.BoolTy;
6157 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006158
6159 case PREDEF_TYPE_CHAR_U_ID:
6160 case PREDEF_TYPE_CHAR_S_ID:
6161 // FIXME: Check that the signedness of CharTy is correct!
6162 T = Context.CharTy;
6163 break;
6164
Alexey Baderbdf7c842015-09-15 12:18:29 +00006165 case PREDEF_TYPE_UCHAR_ID:
6166 T = Context.UnsignedCharTy;
6167 break;
6168 case PREDEF_TYPE_USHORT_ID:
6169 T = Context.UnsignedShortTy;
6170 break;
6171 case PREDEF_TYPE_UINT_ID:
6172 T = Context.UnsignedIntTy;
6173 break;
6174 case PREDEF_TYPE_ULONG_ID:
6175 T = Context.UnsignedLongTy;
6176 break;
6177 case PREDEF_TYPE_ULONGLONG_ID:
6178 T = Context.UnsignedLongLongTy;
6179 break;
6180 case PREDEF_TYPE_UINT128_ID:
6181 T = Context.UnsignedInt128Ty;
6182 break;
6183 case PREDEF_TYPE_SCHAR_ID:
6184 T = Context.SignedCharTy;
6185 break;
6186 case PREDEF_TYPE_WCHAR_ID:
6187 T = Context.WCharTy;
6188 break;
6189 case PREDEF_TYPE_SHORT_ID:
6190 T = Context.ShortTy;
6191 break;
6192 case PREDEF_TYPE_INT_ID:
6193 T = Context.IntTy;
6194 break;
6195 case PREDEF_TYPE_LONG_ID:
6196 T = Context.LongTy;
6197 break;
6198 case PREDEF_TYPE_LONGLONG_ID:
6199 T = Context.LongLongTy;
6200 break;
6201 case PREDEF_TYPE_INT128_ID:
6202 T = Context.Int128Ty;
6203 break;
6204 case PREDEF_TYPE_HALF_ID:
6205 T = Context.HalfTy;
6206 break;
6207 case PREDEF_TYPE_FLOAT_ID:
6208 T = Context.FloatTy;
6209 break;
6210 case PREDEF_TYPE_DOUBLE_ID:
6211 T = Context.DoubleTy;
6212 break;
6213 case PREDEF_TYPE_LONGDOUBLE_ID:
6214 T = Context.LongDoubleTy;
6215 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006216 case PREDEF_TYPE_FLOAT128_ID:
6217 T = Context.Float128Ty;
6218 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006219 case PREDEF_TYPE_OVERLOAD_ID:
6220 T = Context.OverloadTy;
6221 break;
6222 case PREDEF_TYPE_BOUND_MEMBER:
6223 T = Context.BoundMemberTy;
6224 break;
6225 case PREDEF_TYPE_PSEUDO_OBJECT:
6226 T = Context.PseudoObjectTy;
6227 break;
6228 case PREDEF_TYPE_DEPENDENT_ID:
6229 T = Context.DependentTy;
6230 break;
6231 case PREDEF_TYPE_UNKNOWN_ANY:
6232 T = Context.UnknownAnyTy;
6233 break;
6234 case PREDEF_TYPE_NULLPTR_ID:
6235 T = Context.NullPtrTy;
6236 break;
6237 case PREDEF_TYPE_CHAR16_ID:
6238 T = Context.Char16Ty;
6239 break;
6240 case PREDEF_TYPE_CHAR32_ID:
6241 T = Context.Char32Ty;
6242 break;
6243 case PREDEF_TYPE_OBJC_ID:
6244 T = Context.ObjCBuiltinIdTy;
6245 break;
6246 case PREDEF_TYPE_OBJC_CLASS:
6247 T = Context.ObjCBuiltinClassTy;
6248 break;
6249 case PREDEF_TYPE_OBJC_SEL:
6250 T = Context.ObjCBuiltinSelTy;
6251 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006252#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6253 case PREDEF_TYPE_##Id##_ID: \
6254 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006255 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006256#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006257 case PREDEF_TYPE_SAMPLER_ID:
6258 T = Context.OCLSamplerTy;
6259 break;
6260 case PREDEF_TYPE_EVENT_ID:
6261 T = Context.OCLEventTy;
6262 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006263 case PREDEF_TYPE_CLK_EVENT_ID:
6264 T = Context.OCLClkEventTy;
6265 break;
6266 case PREDEF_TYPE_QUEUE_ID:
6267 T = Context.OCLQueueTy;
6268 break;
6269 case PREDEF_TYPE_NDRANGE_ID:
6270 T = Context.OCLNDRangeTy;
6271 break;
6272 case PREDEF_TYPE_RESERVE_ID_ID:
6273 T = Context.OCLReserveIDTy;
6274 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006275 case PREDEF_TYPE_AUTO_DEDUCT:
6276 T = Context.getAutoDeductType();
6277 break;
6278
6279 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6280 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006281 break;
6282
6283 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6284 T = Context.ARCUnbridgedCastTy;
6285 break;
6286
Guy Benyei11169dd2012-12-18 14:30:41 +00006287 case PREDEF_TYPE_BUILTIN_FN:
6288 T = Context.BuiltinFnTy;
6289 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006290
6291 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6292 T = Context.OMPArraySectionTy;
6293 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 }
6295
6296 assert(!T.isNull() && "Unknown predefined type");
6297 return T.withFastQualifiers(FastQuals);
6298 }
6299
6300 Index -= NUM_PREDEF_TYPE_IDS;
6301 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6302 if (TypesLoaded[Index].isNull()) {
6303 TypesLoaded[Index] = readTypeRecord(Index);
6304 if (TypesLoaded[Index].isNull())
6305 return QualType();
6306
6307 TypesLoaded[Index]->setFromAST();
6308 if (DeserializationListener)
6309 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6310 TypesLoaded[Index]);
6311 }
6312
6313 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6314}
6315
6316QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6317 return GetType(getGlobalTypeID(F, LocalID));
6318}
6319
6320serialization::TypeID
6321ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6322 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6323 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6324
6325 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6326 return LocalID;
6327
6328 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6329 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6330 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6331
6332 unsigned GlobalIndex = LocalIndex + I->second;
6333 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6334}
6335
6336TemplateArgumentLocInfo
6337ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6338 TemplateArgument::ArgKind Kind,
6339 const RecordData &Record,
6340 unsigned &Index) {
6341 switch (Kind) {
6342 case TemplateArgument::Expression:
6343 return ReadExpr(F);
6344 case TemplateArgument::Type:
6345 return GetTypeSourceInfo(F, Record, Index);
6346 case TemplateArgument::Template: {
6347 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6348 Index);
6349 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6350 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6351 SourceLocation());
6352 }
6353 case TemplateArgument::TemplateExpansion: {
6354 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6355 Index);
6356 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6357 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6358 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6359 EllipsisLoc);
6360 }
6361 case TemplateArgument::Null:
6362 case TemplateArgument::Integral:
6363 case TemplateArgument::Declaration:
6364 case TemplateArgument::NullPtr:
6365 case TemplateArgument::Pack:
6366 // FIXME: Is this right?
6367 return TemplateArgumentLocInfo();
6368 }
6369 llvm_unreachable("unexpected template argument loc");
6370}
6371
6372TemplateArgumentLoc
6373ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6374 const RecordData &Record, unsigned &Index) {
6375 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6376
6377 if (Arg.getKind() == TemplateArgument::Expression) {
6378 if (Record[Index++]) // bool InfoHasSameExpr.
6379 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6380 }
6381 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6382 Record, Index));
6383}
6384
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006385const ASTTemplateArgumentListInfo*
6386ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6387 const RecordData &Record,
6388 unsigned &Index) {
6389 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6390 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6391 unsigned NumArgsAsWritten = Record[Index++];
6392 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6393 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6394 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6395 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6396}
6397
Guy Benyei11169dd2012-12-18 14:30:41 +00006398Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6399 return GetDecl(ID);
6400}
6401
Richard Smith50895422015-01-31 03:04:55 +00006402template<typename TemplateSpecializationDecl>
6403static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6404 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6405 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6406}
6407
Richard Smith053f6c62014-05-16 23:01:30 +00006408void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006409 if (NumCurrentElementsDeserializing) {
6410 // We arrange to not care about the complete redeclaration chain while we're
6411 // deserializing. Just remember that the AST has marked this one as complete
6412 // but that it's not actually complete yet, so we know we still need to
6413 // complete it later.
6414 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6415 return;
6416 }
6417
Richard Smith053f6c62014-05-16 23:01:30 +00006418 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6419
Richard Smith053f6c62014-05-16 23:01:30 +00006420 // If this is a named declaration, complete it by looking it up
6421 // within its context.
6422 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006423 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006424 // all mergeable entities within it.
6425 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6426 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6427 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006428 if (!getContext().getLangOpts().CPlusPlus &&
6429 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006430 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006431 // the identifier instead. (For C++ modules, we don't store decls
6432 // in the serialized identifier table, so we do the lookup in the TU.)
6433 auto *II = Name.getAsIdentifierInfo();
6434 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006435 if (II->isOutOfDate())
6436 updateOutOfDateIdentifier(*II);
6437 } else
6438 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006439 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006440 // Find all declarations of this kind from the relevant context.
6441 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6442 auto *DC = cast<DeclContext>(DCDecl);
6443 SmallVector<Decl*, 8> Decls;
6444 FindExternalLexicalDecls(
6445 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6446 }
Richard Smith053f6c62014-05-16 23:01:30 +00006447 }
6448 }
Richard Smith50895422015-01-31 03:04:55 +00006449
6450 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6451 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6452 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6453 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6454 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6455 if (auto *Template = FD->getPrimaryTemplate())
6456 Template->LoadLazySpecializations();
6457 }
Richard Smith053f6c62014-05-16 23:01:30 +00006458}
6459
Richard Smithc2bb8182015-03-24 06:36:48 +00006460CXXCtorInitializer **
6461ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6462 RecordLocation Loc = getLocalBitOffset(Offset);
6463 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6464 SavedStreamPosition SavedPosition(Cursor);
6465 Cursor.JumpToBit(Loc.Offset);
6466 ReadingKindTracker ReadingKind(Read_Decl, *this);
6467
6468 RecordData Record;
6469 unsigned Code = Cursor.ReadCode();
6470 unsigned RecCode = Cursor.readRecord(Code, Record);
6471 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6472 Error("malformed AST file: missing C++ ctor initializers");
6473 return nullptr;
6474 }
6475
6476 unsigned Idx = 0;
6477 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6478}
6479
Guy Benyei11169dd2012-12-18 14:30:41 +00006480CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6481 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006482 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006483 SavedStreamPosition SavedPosition(Cursor);
6484 Cursor.JumpToBit(Loc.Offset);
6485 ReadingKindTracker ReadingKind(Read_Decl, *this);
6486 RecordData Record;
6487 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006488 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006489 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006490 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006491 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006492 }
6493
6494 unsigned Idx = 0;
6495 unsigned NumBases = Record[Idx++];
6496 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6497 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6498 for (unsigned I = 0; I != NumBases; ++I)
6499 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6500 return Bases;
6501}
6502
6503serialization::DeclID
6504ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6505 if (LocalID < NUM_PREDEF_DECL_IDS)
6506 return LocalID;
6507
6508 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6509 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6510 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6511
6512 return LocalID + I->second;
6513}
6514
6515bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6516 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006517 // Predefined decls aren't from any module.
6518 if (ID < NUM_PREDEF_DECL_IDS)
6519 return false;
6520
Richard Smithbcda1a92015-07-12 23:51:20 +00006521 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6522 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006523}
6524
Douglas Gregor9f782892013-01-21 15:25:38 +00006525ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006526 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006527 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006528 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6529 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6530 return I->second;
6531}
6532
6533SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6534 if (ID < NUM_PREDEF_DECL_IDS)
6535 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006536
Guy Benyei11169dd2012-12-18 14:30:41 +00006537 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6538
6539 if (Index > DeclsLoaded.size()) {
6540 Error("declaration ID out-of-range for AST file");
6541 return SourceLocation();
6542 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006543
Guy Benyei11169dd2012-12-18 14:30:41 +00006544 if (Decl *D = DeclsLoaded[Index])
6545 return D->getLocation();
6546
Richard Smithcb34bd32016-03-27 07:28:06 +00006547 SourceLocation Loc;
6548 DeclCursorForID(ID, Loc);
6549 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006550}
6551
Richard Smithfe620d22015-03-05 23:24:12 +00006552static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6553 switch (ID) {
6554 case PREDEF_DECL_NULL_ID:
6555 return nullptr;
6556
6557 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6558 return Context.getTranslationUnitDecl();
6559
6560 case PREDEF_DECL_OBJC_ID_ID:
6561 return Context.getObjCIdDecl();
6562
6563 case PREDEF_DECL_OBJC_SEL_ID:
6564 return Context.getObjCSelDecl();
6565
6566 case PREDEF_DECL_OBJC_CLASS_ID:
6567 return Context.getObjCClassDecl();
6568
6569 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6570 return Context.getObjCProtocolDecl();
6571
6572 case PREDEF_DECL_INT_128_ID:
6573 return Context.getInt128Decl();
6574
6575 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6576 return Context.getUInt128Decl();
6577
6578 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6579 return Context.getObjCInstanceTypeDecl();
6580
6581 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6582 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006583
Richard Smith9b88a4c2015-07-27 05:40:23 +00006584 case PREDEF_DECL_VA_LIST_TAG:
6585 return Context.getVaListTagDecl();
6586
Charles Davisc7d5c942015-09-17 20:55:33 +00006587 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6588 return Context.getBuiltinMSVaListDecl();
6589
Richard Smithf19e1272015-03-07 00:04:49 +00006590 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6591 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006592
6593 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6594 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006595
6596 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6597 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006598
6599 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6600 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006601
6602 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6603 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006604 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006605 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006606}
6607
Richard Smithcd45dbc2014-04-19 03:48:30 +00006608Decl *ASTReader::GetExistingDecl(DeclID ID) {
6609 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006610 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6611 if (D) {
6612 // Track that we have merged the declaration with ID \p ID into the
6613 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006614 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006615 if (Merged.empty())
6616 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006617 }
Richard Smithfe620d22015-03-05 23:24:12 +00006618 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006619 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006620
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6622
6623 if (Index >= DeclsLoaded.size()) {
6624 assert(0 && "declaration ID out-of-range for AST file");
6625 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006626 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006627 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006628
6629 return DeclsLoaded[Index];
6630}
6631
6632Decl *ASTReader::GetDecl(DeclID ID) {
6633 if (ID < NUM_PREDEF_DECL_IDS)
6634 return GetExistingDecl(ID);
6635
6636 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6637
6638 if (Index >= DeclsLoaded.size()) {
6639 assert(0 && "declaration ID out-of-range for AST file");
6640 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006641 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006642 }
6643
Guy Benyei11169dd2012-12-18 14:30:41 +00006644 if (!DeclsLoaded[Index]) {
6645 ReadDeclRecord(ID);
6646 if (DeserializationListener)
6647 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6648 }
6649
6650 return DeclsLoaded[Index];
6651}
6652
6653DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6654 DeclID GlobalID) {
6655 if (GlobalID < NUM_PREDEF_DECL_IDS)
6656 return GlobalID;
6657
6658 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6659 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6660 ModuleFile *Owner = I->second;
6661
6662 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6663 = M.GlobalToLocalDeclIDs.find(Owner);
6664 if (Pos == M.GlobalToLocalDeclIDs.end())
6665 return 0;
6666
6667 return GlobalID - Owner->BaseDeclID + Pos->second;
6668}
6669
6670serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6671 const RecordData &Record,
6672 unsigned &Idx) {
6673 if (Idx >= Record.size()) {
6674 Error("Corrupted AST file");
6675 return 0;
6676 }
6677
6678 return getGlobalDeclID(F, Record[Idx++]);
6679}
6680
6681/// \brief Resolve the offset of a statement into a statement.
6682///
6683/// This operation will read a new statement from the external
6684/// source each time it is called, and is meant to be used via a
6685/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6686Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6687 // Switch case IDs are per Decl.
6688 ClearSwitchCaseIDs();
6689
6690 // Offset here is a global offset across the entire chain.
6691 RecordLocation Loc = getLocalBitOffset(Offset);
6692 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6693 return ReadStmtFromStream(*Loc.F);
6694}
6695
Richard Smith3cb15722015-08-05 22:41:45 +00006696void ASTReader::FindExternalLexicalDecls(
6697 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6698 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006699 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6700
Richard Smith9ccdd932015-08-06 22:14:12 +00006701 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006702 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6703 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6704 auto K = (Decl::Kind)+LexicalDecls[I];
6705 if (!IsKindWeWant(K))
6706 continue;
6707
6708 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6709
6710 // Don't add predefined declarations to the lexical context more
6711 // than once.
6712 if (ID < NUM_PREDEF_DECL_IDS) {
6713 if (PredefsVisited[ID])
6714 continue;
6715
6716 PredefsVisited[ID] = true;
6717 }
6718
6719 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006720 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006721 if (!DC->isDeclInLexicalTraversal(D))
6722 Decls.push_back(D);
6723 }
6724 }
6725 };
6726
6727 if (isa<TranslationUnitDecl>(DC)) {
6728 for (auto Lexical : TULexicalDecls)
6729 Visit(Lexical.first, Lexical.second);
6730 } else {
6731 auto I = LexicalDecls.find(DC);
6732 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006733 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006734 }
6735
Guy Benyei11169dd2012-12-18 14:30:41 +00006736 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006737}
6738
6739namespace {
6740
6741class DeclIDComp {
6742 ASTReader &Reader;
6743 ModuleFile &Mod;
6744
6745public:
6746 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6747
6748 bool operator()(LocalDeclID L, LocalDeclID R) const {
6749 SourceLocation LHS = getLocation(L);
6750 SourceLocation RHS = getLocation(R);
6751 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6752 }
6753
6754 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6755 SourceLocation RHS = getLocation(R);
6756 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6757 }
6758
6759 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6760 SourceLocation LHS = getLocation(L);
6761 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6762 }
6763
6764 SourceLocation getLocation(LocalDeclID ID) const {
6765 return Reader.getSourceManager().getFileLoc(
6766 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6767 }
6768};
6769
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006770} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006771
6772void ASTReader::FindFileRegionDecls(FileID File,
6773 unsigned Offset, unsigned Length,
6774 SmallVectorImpl<Decl *> &Decls) {
6775 SourceManager &SM = getSourceManager();
6776
6777 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6778 if (I == FileDeclIDs.end())
6779 return;
6780
6781 FileDeclsInfo &DInfo = I->second;
6782 if (DInfo.Decls.empty())
6783 return;
6784
6785 SourceLocation
6786 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6787 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6788
6789 DeclIDComp DIDComp(*this, *DInfo.Mod);
6790 ArrayRef<serialization::LocalDeclID>::iterator
6791 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6792 BeginLoc, DIDComp);
6793 if (BeginIt != DInfo.Decls.begin())
6794 --BeginIt;
6795
6796 // If we are pointing at a top-level decl inside an objc container, we need
6797 // to backtrack until we find it otherwise we will fail to report that the
6798 // region overlaps with an objc container.
6799 while (BeginIt != DInfo.Decls.begin() &&
6800 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6801 ->isTopLevelDeclInObjCContainer())
6802 --BeginIt;
6803
6804 ArrayRef<serialization::LocalDeclID>::iterator
6805 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6806 EndLoc, DIDComp);
6807 if (EndIt != DInfo.Decls.end())
6808 ++EndIt;
6809
6810 for (ArrayRef<serialization::LocalDeclID>::iterator
6811 DIt = BeginIt; DIt != EndIt; ++DIt)
6812 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6813}
6814
Richard Smith9ce12e32013-02-07 03:30:24 +00006815bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006816ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6817 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006818 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006819 "DeclContext has no visible decls in storage");
6820 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006821 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006822
Richard Smithd88a7f12015-09-01 20:35:42 +00006823 auto It = Lookups.find(DC);
6824 if (It == Lookups.end())
6825 return false;
6826
Richard Smith8c913ec2014-08-14 02:21:01 +00006827 Deserializing LookupResults(this);
6828
Richard Smithd88a7f12015-09-01 20:35:42 +00006829 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006830 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006831 for (DeclID ID : It->second.Table.find(Name)) {
6832 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6833 if (ND->getDeclName() == Name)
6834 Decls.push_back(ND);
6835 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006836
Guy Benyei11169dd2012-12-18 14:30:41 +00006837 ++NumVisibleDeclContextsRead;
6838 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006839 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006840}
6841
Guy Benyei11169dd2012-12-18 14:30:41 +00006842void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6843 if (!DC->hasExternalVisibleStorage())
6844 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006845
6846 auto It = Lookups.find(DC);
6847 assert(It != Lookups.end() &&
6848 "have external visible storage but no lookup tables");
6849
Craig Topper79be4cd2013-07-05 04:33:53 +00006850 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006851
Richard Smithd88a7f12015-09-01 20:35:42 +00006852 for (DeclID ID : It->second.Table.findAll()) {
6853 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6854 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 }
6856
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 ++NumVisibleDeclContextsRead;
6858
Craig Topper79be4cd2013-07-05 04:33:53 +00006859 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6861 }
6862 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6863}
6864
Richard Smithd88a7f12015-09-01 20:35:42 +00006865const serialization::reader::DeclContextLookupTable *
6866ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6867 auto I = Lookups.find(Primary);
6868 return I == Lookups.end() ? nullptr : &I->second;
6869}
6870
Guy Benyei11169dd2012-12-18 14:30:41 +00006871/// \brief Under non-PCH compilation the consumer receives the objc methods
6872/// before receiving the implementation, and codegen depends on this.
6873/// We simulate this by deserializing and passing to consumer the methods of the
6874/// implementation before passing the deserialized implementation decl.
6875static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6876 ASTConsumer *Consumer) {
6877 assert(ImplD && Consumer);
6878
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006879 for (auto *I : ImplD->methods())
6880 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006881
6882 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6883}
6884
6885void ASTReader::PassInterestingDeclsToConsumer() {
6886 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006887
6888 if (PassingDeclsToConsumer)
6889 return;
6890
6891 // Guard variable to avoid recursively redoing the process of passing
6892 // decls to consumer.
6893 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6894 true);
6895
Richard Smith9e2341d2015-03-23 03:25:59 +00006896 // Ensure that we've loaded all potentially-interesting declarations
6897 // that need to be eagerly loaded.
6898 for (auto ID : EagerlyDeserializedDecls)
6899 GetDecl(ID);
6900 EagerlyDeserializedDecls.clear();
6901
Guy Benyei11169dd2012-12-18 14:30:41 +00006902 while (!InterestingDecls.empty()) {
6903 Decl *D = InterestingDecls.front();
6904 InterestingDecls.pop_front();
6905
6906 PassInterestingDeclToConsumer(D);
6907 }
6908}
6909
6910void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6911 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6912 PassObjCImplDeclToConsumer(ImplD, Consumer);
6913 else
6914 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6915}
6916
6917void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6918 this->Consumer = Consumer;
6919
Richard Smith9e2341d2015-03-23 03:25:59 +00006920 if (Consumer)
6921 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006922
6923 if (DeserializationListener)
6924 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006925}
6926
6927void ASTReader::PrintStats() {
6928 std::fprintf(stderr, "*** AST File Statistics:\n");
6929
6930 unsigned NumTypesLoaded
6931 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6932 QualType());
6933 unsigned NumDeclsLoaded
6934 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006935 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006936 unsigned NumIdentifiersLoaded
6937 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6938 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006939 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 unsigned NumMacrosLoaded
6941 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6942 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006943 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 unsigned NumSelectorsLoaded
6945 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6946 SelectorsLoaded.end(),
6947 Selector());
6948
6949 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6950 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6951 NumSLocEntriesRead, TotalNumSLocEntries,
6952 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6953 if (!TypesLoaded.empty())
6954 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6955 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6956 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6957 if (!DeclsLoaded.empty())
6958 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6959 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6960 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6961 if (!IdentifiersLoaded.empty())
6962 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6963 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6964 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6965 if (!MacrosLoaded.empty())
6966 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6967 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6968 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6969 if (!SelectorsLoaded.empty())
6970 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6971 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6972 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6973 if (TotalNumStatements)
6974 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6975 NumStatementsRead, TotalNumStatements,
6976 ((float)NumStatementsRead/TotalNumStatements * 100));
6977 if (TotalNumMacros)
6978 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6979 NumMacrosRead, TotalNumMacros,
6980 ((float)NumMacrosRead/TotalNumMacros * 100));
6981 if (TotalLexicalDeclContexts)
6982 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6983 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6984 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6985 * 100));
6986 if (TotalVisibleDeclContexts)
6987 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6988 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6989 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6990 * 100));
6991 if (TotalNumMethodPoolEntries) {
6992 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6993 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6994 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6995 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006996 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006997 if (NumMethodPoolLookups) {
6998 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6999 NumMethodPoolHits, NumMethodPoolLookups,
7000 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7001 }
7002 if (NumMethodPoolTableLookups) {
7003 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7004 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7005 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7006 * 100.0));
7007 }
7008
Douglas Gregor00a50f72013-01-25 00:38:33 +00007009 if (NumIdentifierLookupHits) {
7010 std::fprintf(stderr,
7011 " %u / %u identifier table lookups succeeded (%f%%)\n",
7012 NumIdentifierLookupHits, NumIdentifierLookups,
7013 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7014 }
7015
Douglas Gregore060e572013-01-25 01:03:03 +00007016 if (GlobalIndex) {
7017 std::fprintf(stderr, "\n");
7018 GlobalIndex->printStats();
7019 }
7020
Guy Benyei11169dd2012-12-18 14:30:41 +00007021 std::fprintf(stderr, "\n");
7022 dump();
7023 std::fprintf(stderr, "\n");
7024}
7025
7026template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7027static void
7028dumpModuleIDMap(StringRef Name,
7029 const ContinuousRangeMap<Key, ModuleFile *,
7030 InitialCapacity> &Map) {
7031 if (Map.begin() == Map.end())
7032 return;
7033
7034 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7035 llvm::errs() << Name << ":\n";
7036 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7037 I != IEnd; ++I) {
7038 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7039 << "\n";
7040 }
7041}
7042
Yaron Kerencdae9412016-01-29 19:38:18 +00007043LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007044 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7045 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7046 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7047 dumpModuleIDMap("Global type map", GlobalTypeMap);
7048 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7049 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7050 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7051 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7052 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7053 dumpModuleIDMap("Global preprocessed entity map",
7054 GlobalPreprocessedEntityMap);
7055
7056 llvm::errs() << "\n*** PCH/Modules Loaded:";
7057 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
7058 MEnd = ModuleMgr.end();
7059 M != MEnd; ++M)
7060 (*M)->dump();
7061}
7062
7063/// Return the amount of memory used by memory buffers, breaking down
7064/// by heap-backed versus mmap'ed memory.
7065void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7066 for (ModuleConstIterator I = ModuleMgr.begin(),
7067 E = ModuleMgr.end(); I != E; ++I) {
7068 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
7069 size_t bytes = buf->getBufferSize();
7070 switch (buf->getBufferKind()) {
7071 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7072 sizes.malloc_bytes += bytes;
7073 break;
7074 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7075 sizes.mmap_bytes += bytes;
7076 break;
7077 }
7078 }
7079 }
7080}
7081
7082void ASTReader::InitializeSema(Sema &S) {
7083 SemaObj = &S;
7084 S.addExternalSource(this);
7085
7086 // Makes sure any declarations that were deserialized "too early"
7087 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007088 for (uint64_t ID : PreloadedDeclIDs) {
7089 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7090 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007091 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007092 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007093
Richard Smith3d8e97e2013-10-18 06:54:39 +00007094 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007095 if (!FPPragmaOptions.empty()) {
7096 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7097 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7098 }
7099
Richard Smith3d8e97e2013-10-18 06:54:39 +00007100 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007101 if (!OpenCLExtensions.empty()) {
7102 unsigned I = 0;
7103#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
7104#include "clang/Basic/OpenCLExtensions.def"
7105
7106 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
7107 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00007108
7109 UpdateSema();
7110}
7111
7112void ASTReader::UpdateSema() {
7113 assert(SemaObj && "no Sema to update");
7114
7115 // Load the offsets of the declarations that Sema references.
7116 // They will be lazily deserialized when needed.
7117 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007118 assert(SemaDeclRefs.size() % 3 == 0);
7119 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007120 if (!SemaObj->StdNamespace)
7121 SemaObj->StdNamespace = SemaDeclRefs[I];
7122 if (!SemaObj->StdBadAlloc)
7123 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007124 if (!SemaObj->StdAlignValT)
7125 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007126 }
7127 SemaDeclRefs.clear();
7128 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007129
Nico Weber779355f2016-03-02 23:22:00 +00007130 // Update the state of pragmas. Use the same API as if we had encountered the
7131 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007132 if(OptimizeOffPragmaLocation.isValid())
7133 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007134 if (PragmaMSStructState != -1)
7135 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007136 if (PointersToMembersPragmaLocation.isValid()) {
7137 SemaObj->ActOnPragmaMSPointersToMembers(
7138 (LangOptions::PragmaMSPointersToMembersKind)
7139 PragmaMSPointersToMembersState,
7140 PointersToMembersPragmaLocation);
7141 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007142 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Guy Benyei11169dd2012-12-18 14:30:41 +00007143}
7144
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007145IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007146 // Note that we are loading an identifier.
7147 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007148
Douglas Gregor7211ac12013-01-25 23:32:03 +00007149 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007150 NumIdentifierLookups,
7151 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007152
7153 // We don't need to do identifier table lookups in C++ modules (we preload
7154 // all interesting declarations, and don't need to use the scope for name
7155 // lookups). Perform the lookup in PCH files, though, since we don't build
7156 // a complete initial identifier table if we're carrying on from a PCH.
7157 if (Context.getLangOpts().CPlusPlus) {
7158 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007159 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007160 break;
7161 } else {
7162 // If there is a global index, look there first to determine which modules
7163 // provably do not have any results for this identifier.
7164 GlobalModuleIndex::HitSet Hits;
7165 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7166 if (!loadGlobalIndex()) {
7167 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7168 HitsPtr = &Hits;
7169 }
7170 }
7171
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007172 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007173 }
7174
Guy Benyei11169dd2012-12-18 14:30:41 +00007175 IdentifierInfo *II = Visitor.getIdentifierInfo();
7176 markIdentifierUpToDate(II);
7177 return II;
7178}
7179
7180namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007181
Guy Benyei11169dd2012-12-18 14:30:41 +00007182 /// \brief An identifier-lookup iterator that enumerates all of the
7183 /// identifiers stored within a set of AST files.
7184 class ASTIdentifierIterator : public IdentifierIterator {
7185 /// \brief The AST reader whose identifiers are being enumerated.
7186 const ASTReader &Reader;
7187
7188 /// \brief The current index into the chain of AST files stored in
7189 /// the AST reader.
7190 unsigned Index;
7191
7192 /// \brief The current position within the identifier lookup table
7193 /// of the current AST file.
7194 ASTIdentifierLookupTable::key_iterator Current;
7195
7196 /// \brief The end position within the identifier lookup table of
7197 /// the current AST file.
7198 ASTIdentifierLookupTable::key_iterator End;
7199
Ben Langmuir537c5b52016-05-04 00:53:13 +00007200 /// \brief Whether to skip any modules in the ASTReader.
7201 bool SkipModules;
7202
Guy Benyei11169dd2012-12-18 14:30:41 +00007203 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007204 explicit ASTIdentifierIterator(const ASTReader &Reader,
7205 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007206
Craig Topper3e89dfe2014-03-13 02:13:41 +00007207 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007208 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007209
7210} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007211
Ben Langmuir537c5b52016-05-04 00:53:13 +00007212ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7213 bool SkipModules)
7214 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007215}
7216
7217StringRef ASTIdentifierIterator::Next() {
7218 while (Current == End) {
7219 // If we have exhausted all of our AST files, we're done.
7220 if (Index == 0)
7221 return StringRef();
7222
7223 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007224 ModuleFile &F = Reader.ModuleMgr[Index];
7225 if (SkipModules && F.isModule())
7226 continue;
7227
7228 ASTIdentifierLookupTable *IdTable =
7229 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007230 Current = IdTable->key_begin();
7231 End = IdTable->key_end();
7232 }
7233
7234 // We have any identifiers remaining in the current AST file; return
7235 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007236 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007237 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007238 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007239}
7240
Ben Langmuir537c5b52016-05-04 00:53:13 +00007241namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007242
Ben Langmuir537c5b52016-05-04 00:53:13 +00007243/// A utility for appending two IdentifierIterators.
7244class ChainedIdentifierIterator : public IdentifierIterator {
7245 std::unique_ptr<IdentifierIterator> Current;
7246 std::unique_ptr<IdentifierIterator> Queued;
7247
7248public:
7249 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7250 std::unique_ptr<IdentifierIterator> Second)
7251 : Current(std::move(First)), Queued(std::move(Second)) {}
7252
7253 StringRef Next() override {
7254 if (!Current)
7255 return StringRef();
7256
7257 StringRef result = Current->Next();
7258 if (!result.empty())
7259 return result;
7260
7261 // Try the queued iterator, which may itself be empty.
7262 Current.reset();
7263 std::swap(Current, Queued);
7264 return Next();
7265 }
7266};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007267
Ben Langmuir537c5b52016-05-04 00:53:13 +00007268} // end anonymous namespace.
7269
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007270IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007271 if (!loadGlobalIndex()) {
7272 std::unique_ptr<IdentifierIterator> ReaderIter(
7273 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7274 std::unique_ptr<IdentifierIterator> ModulesIter(
7275 GlobalIndex->createIdentifierIterator());
7276 return new ChainedIdentifierIterator(std::move(ReaderIter),
7277 std::move(ModulesIter));
7278 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007279
Guy Benyei11169dd2012-12-18 14:30:41 +00007280 return new ASTIdentifierIterator(*this);
7281}
7282
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007283namespace clang {
7284namespace serialization {
7285
Guy Benyei11169dd2012-12-18 14:30:41 +00007286 class ReadMethodPoolVisitor {
7287 ASTReader &Reader;
7288 Selector Sel;
7289 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007290 unsigned InstanceBits;
7291 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007292 bool InstanceHasMoreThanOneDecl;
7293 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007294 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7295 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007296
7297 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007298 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007299 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007300 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007301 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7302 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007303
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007304 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007305 if (!M.SelectorLookupTable)
7306 return false;
7307
7308 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007309 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 return true;
7311
Richard Smithbdf2d932015-07-30 03:37:16 +00007312 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007313 ASTSelectorLookupTable *PoolTable
7314 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007315 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007316 if (Pos == PoolTable->end())
7317 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007318
Richard Smithbdf2d932015-07-30 03:37:16 +00007319 ++Reader.NumMethodPoolTableHits;
7320 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007321 // FIXME: Not quite happy with the statistics here. We probably should
7322 // disable this tracking when called via LoadSelector.
7323 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007324 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007325 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007326 if (Reader.DeserializationListener)
7327 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007328
Richard Smithbdf2d932015-07-30 03:37:16 +00007329 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7330 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7331 InstanceBits = Data.InstanceBits;
7332 FactoryBits = Data.FactoryBits;
7333 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7334 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007335 return true;
7336 }
7337
7338 /// \brief Retrieve the instance methods found by this visitor.
7339 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7340 return InstanceMethods;
7341 }
7342
7343 /// \brief Retrieve the instance methods found by this visitor.
7344 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7345 return FactoryMethods;
7346 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007347
7348 unsigned getInstanceBits() const { return InstanceBits; }
7349 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007350 bool instanceHasMoreThanOneDecl() const {
7351 return InstanceHasMoreThanOneDecl;
7352 }
7353 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007354 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007355
7356} // end namespace serialization
7357} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007358
7359/// \brief Add the given set of methods to the method list.
7360static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7361 ObjCMethodList &List) {
7362 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7363 S.addMethodToGlobalList(&List, Methods[I]);
7364 }
7365}
7366
7367void ASTReader::ReadMethodPool(Selector Sel) {
7368 // Get the selector generation and update it to the current generation.
7369 unsigned &Generation = SelectorGeneration[Sel];
7370 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007371 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007372 SelectorOutOfDate[Sel] = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007373
7374 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007375 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007376 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007377 ModuleMgr.visit(Visitor);
7378
Guy Benyei11169dd2012-12-18 14:30:41 +00007379 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007380 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007381 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007382
7383 ++NumMethodPoolHits;
7384
Guy Benyei11169dd2012-12-18 14:30:41 +00007385 if (!getSema())
7386 return;
7387
7388 Sema &S = *getSema();
7389 Sema::GlobalMethodPool::iterator Pos
7390 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007391
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007392 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007393 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007394 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007395 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007396
7397 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7398 // when building a module we keep every method individually and may need to
7399 // update hasMoreThanOneDecl as we add the methods.
7400 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7401 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007402}
7403
Manman Rena0f31a02016-04-29 19:04:05 +00007404void ASTReader::updateOutOfDateSelector(Selector Sel) {
7405 if (SelectorOutOfDate[Sel])
7406 ReadMethodPool(Sel);
7407}
7408
Guy Benyei11169dd2012-12-18 14:30:41 +00007409void ASTReader::ReadKnownNamespaces(
7410 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7411 Namespaces.clear();
7412
7413 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7414 if (NamespaceDecl *Namespace
7415 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7416 Namespaces.push_back(Namespace);
7417 }
7418}
7419
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007420void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007421 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007422 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7423 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007424 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007425 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007426 Undefined.insert(std::make_pair(D, Loc));
7427 }
7428}
Nick Lewycky8334af82013-01-26 00:35:08 +00007429
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007430void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7431 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7432 Exprs) {
7433 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7434 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7435 uint64_t Count = DelayedDeleteExprs[Idx++];
7436 for (uint64_t C = 0; C < Count; ++C) {
7437 SourceLocation DeleteLoc =
7438 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7439 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7440 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7441 }
7442 }
7443}
7444
Guy Benyei11169dd2012-12-18 14:30:41 +00007445void ASTReader::ReadTentativeDefinitions(
7446 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7447 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7448 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7449 if (Var)
7450 TentativeDefs.push_back(Var);
7451 }
7452 TentativeDefinitions.clear();
7453}
7454
7455void ASTReader::ReadUnusedFileScopedDecls(
7456 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7457 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7458 DeclaratorDecl *D
7459 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7460 if (D)
7461 Decls.push_back(D);
7462 }
7463 UnusedFileScopedDecls.clear();
7464}
7465
7466void ASTReader::ReadDelegatingConstructors(
7467 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7468 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7469 CXXConstructorDecl *D
7470 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7471 if (D)
7472 Decls.push_back(D);
7473 }
7474 DelegatingCtorDecls.clear();
7475}
7476
7477void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7478 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7479 TypedefNameDecl *D
7480 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7481 if (D)
7482 Decls.push_back(D);
7483 }
7484 ExtVectorDecls.clear();
7485}
7486
Nico Weber72889432014-09-06 01:25:55 +00007487void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7488 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7489 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7490 ++I) {
7491 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7492 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7493 if (D)
7494 Decls.insert(D);
7495 }
7496 UnusedLocalTypedefNameCandidates.clear();
7497}
7498
Guy Benyei11169dd2012-12-18 14:30:41 +00007499void ASTReader::ReadReferencedSelectors(
7500 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7501 if (ReferencedSelectorsData.empty())
7502 return;
7503
7504 // If there are @selector references added them to its pool. This is for
7505 // implementation of -Wselector.
7506 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7507 unsigned I = 0;
7508 while (I < DataSize) {
7509 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7510 SourceLocation SelLoc
7511 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7512 Sels.push_back(std::make_pair(Sel, SelLoc));
7513 }
7514 ReferencedSelectorsData.clear();
7515}
7516
7517void ASTReader::ReadWeakUndeclaredIdentifiers(
7518 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7519 if (WeakUndeclaredIdentifiers.empty())
7520 return;
7521
7522 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7523 IdentifierInfo *WeakId
7524 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7525 IdentifierInfo *AliasId
7526 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7527 SourceLocation Loc
7528 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7529 bool Used = WeakUndeclaredIdentifiers[I++];
7530 WeakInfo WI(AliasId, Loc);
7531 WI.setUsed(Used);
7532 WeakIDs.push_back(std::make_pair(WeakId, WI));
7533 }
7534 WeakUndeclaredIdentifiers.clear();
7535}
7536
7537void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7538 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7539 ExternalVTableUse VT;
7540 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7541 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7542 VT.DefinitionRequired = VTableUses[Idx++];
7543 VTables.push_back(VT);
7544 }
7545
7546 VTableUses.clear();
7547}
7548
7549void ASTReader::ReadPendingInstantiations(
7550 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7551 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7552 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7553 SourceLocation Loc
7554 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7555
7556 Pending.push_back(std::make_pair(D, Loc));
7557 }
7558 PendingInstantiations.clear();
7559}
7560
Richard Smithe40f2ba2013-08-07 21:41:30 +00007561void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007562 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7563 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007564 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7565 /* In loop */) {
7566 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7567
Justin Lebar28f09c52016-10-10 16:26:08 +00007568 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007569 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7570
7571 ModuleFile *F = getOwningModuleFile(LT->D);
7572 assert(F && "No module");
7573
7574 unsigned TokN = LateParsedTemplates[Idx++];
7575 LT->Toks.reserve(TokN);
7576 for (unsigned T = 0; T < TokN; ++T)
7577 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7578
Justin Lebar28f09c52016-10-10 16:26:08 +00007579 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007580 }
7581
7582 LateParsedTemplates.clear();
7583}
7584
Guy Benyei11169dd2012-12-18 14:30:41 +00007585void ASTReader::LoadSelector(Selector Sel) {
7586 // It would be complicated to avoid reading the methods anyway. So don't.
7587 ReadMethodPool(Sel);
7588}
7589
7590void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7591 assert(ID && "Non-zero identifier ID required");
7592 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7593 IdentifiersLoaded[ID - 1] = II;
7594 if (DeserializationListener)
7595 DeserializationListener->IdentifierRead(ID, II);
7596}
7597
7598/// \brief Set the globally-visible declarations associated with the given
7599/// identifier.
7600///
7601/// If the AST reader is currently in a state where the given declaration IDs
7602/// cannot safely be resolved, they are queued until it is safe to resolve
7603/// them.
7604///
7605/// \param II an IdentifierInfo that refers to one or more globally-visible
7606/// declarations.
7607///
7608/// \param DeclIDs the set of declaration IDs with the name @p II that are
7609/// visible at global scope.
7610///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007611/// \param Decls if non-null, this vector will be populated with the set of
7612/// deserialized declarations. These declarations will not be pushed into
7613/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007614void
7615ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7616 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007617 SmallVectorImpl<Decl *> *Decls) {
7618 if (NumCurrentElementsDeserializing && !Decls) {
7619 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007620 return;
7621 }
7622
7623 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007624 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007625 // Queue this declaration so that it will be added to the
7626 // translation unit scope and identifier's declaration chain
7627 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007628 PreloadedDeclIDs.push_back(DeclIDs[I]);
7629 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007630 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007631
7632 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7633
7634 // If we're simply supposed to record the declarations, do so now.
7635 if (Decls) {
7636 Decls->push_back(D);
7637 continue;
7638 }
7639
7640 // Introduce this declaration into the translation-unit scope
7641 // and add it to the declaration chain for this identifier, so
7642 // that (unqualified) name lookup will find it.
7643 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007644 }
7645}
7646
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007647IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007648 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007649 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007650
7651 if (IdentifiersLoaded.empty()) {
7652 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007653 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007654 }
7655
7656 ID -= 1;
7657 if (!IdentifiersLoaded[ID]) {
7658 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7659 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7660 ModuleFile *M = I->second;
7661 unsigned Index = ID - M->BaseIdentifierID;
7662 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7663
7664 // All of the strings in the AST file are preceded by a 16-bit length.
7665 // Extract that 16-bit length to avoid having to execute strlen().
7666 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7667 // unsigned integers. This is important to avoid integer overflow when
7668 // we cast them to 'unsigned'.
7669 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7670 unsigned StrLen = (((unsigned) StrLenPtr[0])
7671 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007672 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7673 IdentifiersLoaded[ID] = &II;
7674 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007675 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007676 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007677 }
7678
7679 return IdentifiersLoaded[ID];
7680}
7681
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007682IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7683 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007684}
7685
7686IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7687 if (LocalID < NUM_PREDEF_IDENT_IDS)
7688 return LocalID;
7689
7690 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7691 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7692 assert(I != M.IdentifierRemap.end()
7693 && "Invalid index into identifier index remap");
7694
7695 return LocalID + I->second;
7696}
7697
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007698MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007699 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007700 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007701
7702 if (MacrosLoaded.empty()) {
7703 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007704 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007705 }
7706
7707 ID -= NUM_PREDEF_MACRO_IDS;
7708 if (!MacrosLoaded[ID]) {
7709 GlobalMacroMapType::iterator I
7710 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7711 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7712 ModuleFile *M = I->second;
7713 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007714 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7715
7716 if (DeserializationListener)
7717 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7718 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007719 }
7720
7721 return MacrosLoaded[ID];
7722}
7723
7724MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7725 if (LocalID < NUM_PREDEF_MACRO_IDS)
7726 return LocalID;
7727
7728 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7729 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7730 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7731
7732 return LocalID + I->second;
7733}
7734
7735serialization::SubmoduleID
7736ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7737 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7738 return LocalID;
7739
7740 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7741 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7742 assert(I != M.SubmoduleRemap.end()
7743 && "Invalid index into submodule index remap");
7744
7745 return LocalID + I->second;
7746}
7747
7748Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7749 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7750 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007751 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007752 }
7753
7754 if (GlobalID > SubmodulesLoaded.size()) {
7755 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007756 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007757 }
7758
7759 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7760}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007761
7762Module *ASTReader::getModule(unsigned ID) {
7763 return getSubmodule(ID);
7764}
7765
Richard Smithd88a7f12015-09-01 20:35:42 +00007766ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7767 if (ID & 1) {
7768 // It's a module, look it up by submodule ID.
7769 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7770 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7771 } else {
7772 // It's a prefix (preamble, PCH, ...). Look it up by index.
7773 unsigned IndexFromEnd = ID >> 1;
7774 assert(IndexFromEnd && "got reference to unknown module file");
7775 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7776 }
7777}
7778
7779unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7780 if (!F)
7781 return 1;
7782
7783 // For a file representing a module, use the submodule ID of the top-level
7784 // module as the file ID. For any other kind of file, the number of such
7785 // files loaded beforehand will be the same on reload.
7786 // FIXME: Is this true even if we have an explicit module file and a PCH?
7787 if (F->isModule())
7788 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7789
7790 auto PCHModules = getModuleManager().pch_modules();
7791 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7792 assert(I != PCHModules.end() && "emitting reference to unknown file");
7793 return (I - PCHModules.end()) << 1;
7794}
7795
Adrian Prantl15bcf702015-06-30 17:39:43 +00007796llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7797ASTReader::getSourceDescriptor(unsigned ID) {
7798 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007799 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007800
7801 // If there is only a single PCH, return it instead.
7802 // Chained PCH are not suported.
7803 if (ModuleMgr.size() == 1) {
7804 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007805 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00007806 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7807 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7808 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007809 }
7810 return None;
7811}
7812
Guy Benyei11169dd2012-12-18 14:30:41 +00007813Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7814 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7815}
7816
7817Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7818 if (ID == 0)
7819 return Selector();
7820
7821 if (ID > SelectorsLoaded.size()) {
7822 Error("selector ID out of range in AST file");
7823 return Selector();
7824 }
7825
Craig Toppera13603a2014-05-22 05:54:18 +00007826 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007827 // Load this selector from the selector table.
7828 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7829 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7830 ModuleFile &M = *I->second;
7831 ASTSelectorLookupTrait Trait(*this, M);
7832 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7833 SelectorsLoaded[ID - 1] =
7834 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7835 if (DeserializationListener)
7836 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7837 }
7838
7839 return SelectorsLoaded[ID - 1];
7840}
7841
7842Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7843 return DecodeSelector(ID);
7844}
7845
7846uint32_t ASTReader::GetNumExternalSelectors() {
7847 // ID 0 (the null selector) is considered an external selector.
7848 return getTotalNumSelectors() + 1;
7849}
7850
7851serialization::SelectorID
7852ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7853 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7854 return LocalID;
7855
7856 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7857 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7858 assert(I != M.SelectorRemap.end()
7859 && "Invalid index into selector index remap");
7860
7861 return LocalID + I->second;
7862}
7863
7864DeclarationName
7865ASTReader::ReadDeclarationName(ModuleFile &F,
7866 const RecordData &Record, unsigned &Idx) {
7867 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7868 switch (Kind) {
7869 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007870 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007871
7872 case DeclarationName::ObjCZeroArgSelector:
7873 case DeclarationName::ObjCOneArgSelector:
7874 case DeclarationName::ObjCMultiArgSelector:
7875 return DeclarationName(ReadSelector(F, Record, Idx));
7876
7877 case DeclarationName::CXXConstructorName:
7878 return Context.DeclarationNames.getCXXConstructorName(
7879 Context.getCanonicalType(readType(F, Record, Idx)));
7880
7881 case DeclarationName::CXXDestructorName:
7882 return Context.DeclarationNames.getCXXDestructorName(
7883 Context.getCanonicalType(readType(F, Record, Idx)));
7884
7885 case DeclarationName::CXXConversionFunctionName:
7886 return Context.DeclarationNames.getCXXConversionFunctionName(
7887 Context.getCanonicalType(readType(F, Record, Idx)));
7888
7889 case DeclarationName::CXXOperatorName:
7890 return Context.DeclarationNames.getCXXOperatorName(
7891 (OverloadedOperatorKind)Record[Idx++]);
7892
7893 case DeclarationName::CXXLiteralOperatorName:
7894 return Context.DeclarationNames.getCXXLiteralOperatorName(
7895 GetIdentifierInfo(F, Record, Idx));
7896
7897 case DeclarationName::CXXUsingDirective:
7898 return DeclarationName::getUsingDirectiveName();
7899 }
7900
7901 llvm_unreachable("Invalid NameKind!");
7902}
7903
7904void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7905 DeclarationNameLoc &DNLoc,
7906 DeclarationName Name,
7907 const RecordData &Record, unsigned &Idx) {
7908 switch (Name.getNameKind()) {
7909 case DeclarationName::CXXConstructorName:
7910 case DeclarationName::CXXDestructorName:
7911 case DeclarationName::CXXConversionFunctionName:
7912 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7913 break;
7914
7915 case DeclarationName::CXXOperatorName:
7916 DNLoc.CXXOperatorName.BeginOpNameLoc
7917 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7918 DNLoc.CXXOperatorName.EndOpNameLoc
7919 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7920 break;
7921
7922 case DeclarationName::CXXLiteralOperatorName:
7923 DNLoc.CXXLiteralOperatorName.OpNameLoc
7924 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7925 break;
7926
7927 case DeclarationName::Identifier:
7928 case DeclarationName::ObjCZeroArgSelector:
7929 case DeclarationName::ObjCOneArgSelector:
7930 case DeclarationName::ObjCMultiArgSelector:
7931 case DeclarationName::CXXUsingDirective:
7932 break;
7933 }
7934}
7935
7936void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7937 DeclarationNameInfo &NameInfo,
7938 const RecordData &Record, unsigned &Idx) {
7939 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7940 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7941 DeclarationNameLoc DNLoc;
7942 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7943 NameInfo.setInfo(DNLoc);
7944}
7945
7946void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7947 const RecordData &Record, unsigned &Idx) {
7948 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7949 unsigned NumTPLists = Record[Idx++];
7950 Info.NumTemplParamLists = NumTPLists;
7951 if (NumTPLists) {
7952 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007953 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00007954 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7955 }
7956}
7957
7958TemplateName
7959ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7960 unsigned &Idx) {
7961 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7962 switch (Kind) {
7963 case TemplateName::Template:
7964 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7965
7966 case TemplateName::OverloadedTemplate: {
7967 unsigned size = Record[Idx++];
7968 UnresolvedSet<8> Decls;
7969 while (size--)
7970 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7971
7972 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7973 }
7974
7975 case TemplateName::QualifiedTemplate: {
7976 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7977 bool hasTemplKeyword = Record[Idx++];
7978 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7979 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7980 }
7981
7982 case TemplateName::DependentTemplate: {
7983 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7984 if (Record[Idx++]) // isIdentifier
7985 return Context.getDependentTemplateName(NNS,
7986 GetIdentifierInfo(F, Record,
7987 Idx));
7988 return Context.getDependentTemplateName(NNS,
7989 (OverloadedOperatorKind)Record[Idx++]);
7990 }
7991
7992 case TemplateName::SubstTemplateTemplateParm: {
7993 TemplateTemplateParmDecl *param
7994 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7995 if (!param) return TemplateName();
7996 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7997 return Context.getSubstTemplateTemplateParm(param, replacement);
7998 }
7999
8000 case TemplateName::SubstTemplateTemplateParmPack: {
8001 TemplateTemplateParmDecl *Param
8002 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8003 if (!Param)
8004 return TemplateName();
8005
8006 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8007 if (ArgPack.getKind() != TemplateArgument::Pack)
8008 return TemplateName();
8009
8010 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8011 }
8012 }
8013
8014 llvm_unreachable("Unhandled template name kind!");
8015}
8016
Richard Smith2bb3c342015-08-09 01:05:31 +00008017TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8018 const RecordData &Record,
8019 unsigned &Idx,
8020 bool Canonicalize) {
8021 if (Canonicalize) {
8022 // The caller wants a canonical template argument. Sometimes the AST only
8023 // wants template arguments in canonical form (particularly as the template
8024 // argument lists of template specializations) so ensure we preserve that
8025 // canonical form across serialization.
8026 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8027 return Context.getCanonicalTemplateArgument(Arg);
8028 }
8029
Guy Benyei11169dd2012-12-18 14:30:41 +00008030 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8031 switch (Kind) {
8032 case TemplateArgument::Null:
8033 return TemplateArgument();
8034 case TemplateArgument::Type:
8035 return TemplateArgument(readType(F, Record, Idx));
8036 case TemplateArgument::Declaration: {
8037 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008038 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008039 }
8040 case TemplateArgument::NullPtr:
8041 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8042 case TemplateArgument::Integral: {
8043 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8044 QualType T = readType(F, Record, Idx);
8045 return TemplateArgument(Context, Value, T);
8046 }
8047 case TemplateArgument::Template:
8048 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8049 case TemplateArgument::TemplateExpansion: {
8050 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008051 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008052 if (unsigned NumExpansions = Record[Idx++])
8053 NumTemplateExpansions = NumExpansions - 1;
8054 return TemplateArgument(Name, NumTemplateExpansions);
8055 }
8056 case TemplateArgument::Expression:
8057 return TemplateArgument(ReadExpr(F));
8058 case TemplateArgument::Pack: {
8059 unsigned NumArgs = Record[Idx++];
8060 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8061 for (unsigned I = 0; I != NumArgs; ++I)
8062 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008063 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 }
8065 }
8066
8067 llvm_unreachable("Unhandled template argument kind!");
8068}
8069
8070TemplateParameterList *
8071ASTReader::ReadTemplateParameterList(ModuleFile &F,
8072 const RecordData &Record, unsigned &Idx) {
8073 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8074 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8075 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8076
8077 unsigned NumParams = Record[Idx++];
8078 SmallVector<NamedDecl *, 16> Params;
8079 Params.reserve(NumParams);
8080 while (NumParams--)
8081 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8082
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008083 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008084 TemplateParameterList* TemplateParams =
8085 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008086 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008087 return TemplateParams;
8088}
8089
8090void
8091ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008092ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008093 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008094 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008095 unsigned NumTemplateArgs = Record[Idx++];
8096 TemplArgs.reserve(NumTemplateArgs);
8097 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008098 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008099}
8100
8101/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008102void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008103 const RecordData &Record, unsigned &Idx) {
8104 unsigned NumDecls = Record[Idx++];
8105 Set.reserve(Context, NumDecls);
8106 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008107 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008108 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008109 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008110 }
8111}
8112
8113CXXBaseSpecifier
8114ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8115 const RecordData &Record, unsigned &Idx) {
8116 bool isVirtual = static_cast<bool>(Record[Idx++]);
8117 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8118 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8119 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8120 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8121 SourceRange Range = ReadSourceRange(F, Record, Idx);
8122 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
8123 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8124 EllipsisLoc);
8125 Result.setInheritConstructors(inheritConstructors);
8126 return Result;
8127}
8128
Richard Smithc2bb8182015-03-24 06:36:48 +00008129CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008130ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8131 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008132 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008133 assert(NumInitializers && "wrote ctor initializers but have no inits");
8134 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8135 for (unsigned i = 0; i != NumInitializers; ++i) {
8136 TypeSourceInfo *TInfo = nullptr;
8137 bool IsBaseVirtual = false;
8138 FieldDecl *Member = nullptr;
8139 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008140
Richard Smithc2bb8182015-03-24 06:36:48 +00008141 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8142 switch (Type) {
8143 case CTOR_INITIALIZER_BASE:
8144 TInfo = GetTypeSourceInfo(F, Record, Idx);
8145 IsBaseVirtual = Record[Idx++];
8146 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008147
Richard Smithc2bb8182015-03-24 06:36:48 +00008148 case CTOR_INITIALIZER_DELEGATING:
8149 TInfo = GetTypeSourceInfo(F, Record, Idx);
8150 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008151
Richard Smithc2bb8182015-03-24 06:36:48 +00008152 case CTOR_INITIALIZER_MEMBER:
8153 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8154 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008155
Richard Smithc2bb8182015-03-24 06:36:48 +00008156 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8157 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8158 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008159 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008160
8161 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8162 Expr *Init = ReadExpr(F);
8163 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8164 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
8165 bool IsWritten = Record[Idx++];
8166 unsigned SourceOrderOrNumArrayIndices;
8167 SmallVector<VarDecl *, 8> Indices;
8168 if (IsWritten) {
8169 SourceOrderOrNumArrayIndices = Record[Idx++];
8170 } else {
8171 SourceOrderOrNumArrayIndices = Record[Idx++];
8172 Indices.reserve(SourceOrderOrNumArrayIndices);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008173 for (unsigned i = 0; i != SourceOrderOrNumArrayIndices; ++i)
Richard Smithc2bb8182015-03-24 06:36:48 +00008174 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
8175 }
8176
8177 CXXCtorInitializer *BOMInit;
8178 if (Type == CTOR_INITIALIZER_BASE) {
8179 BOMInit = new (Context)
8180 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8181 RParenLoc, MemberOrEllipsisLoc);
8182 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
8183 BOMInit = new (Context)
8184 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8185 } else if (IsWritten) {
8186 if (Member)
8187 BOMInit = new (Context) CXXCtorInitializer(
8188 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
8189 else
8190 BOMInit = new (Context)
8191 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8192 LParenLoc, Init, RParenLoc);
8193 } else {
8194 if (IndirectMember) {
8195 assert(Indices.empty() && "Indirect field improperly initialized");
8196 BOMInit = new (Context)
8197 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8198 LParenLoc, Init, RParenLoc);
8199 } else {
8200 BOMInit = CXXCtorInitializer::Create(
8201 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
8202 Indices.data(), Indices.size());
8203 }
8204 }
8205
8206 if (IsWritten)
8207 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
8208 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008209 }
8210
Richard Smithc2bb8182015-03-24 06:36:48 +00008211 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008212}
8213
8214NestedNameSpecifier *
8215ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8216 const RecordData &Record, unsigned &Idx) {
8217 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008218 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008219 for (unsigned I = 0; I != N; ++I) {
8220 NestedNameSpecifier::SpecifierKind Kind
8221 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8222 switch (Kind) {
8223 case NestedNameSpecifier::Identifier: {
8224 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8225 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8226 break;
8227 }
8228
8229 case NestedNameSpecifier::Namespace: {
8230 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8231 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8232 break;
8233 }
8234
8235 case NestedNameSpecifier::NamespaceAlias: {
8236 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8237 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8238 break;
8239 }
8240
8241 case NestedNameSpecifier::TypeSpec:
8242 case NestedNameSpecifier::TypeSpecWithTemplate: {
8243 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8244 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008245 return nullptr;
8246
Guy Benyei11169dd2012-12-18 14:30:41 +00008247 bool Template = Record[Idx++];
8248 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8249 break;
8250 }
8251
8252 case NestedNameSpecifier::Global: {
8253 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8254 // No associated value, and there can't be a prefix.
8255 break;
8256 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008257
8258 case NestedNameSpecifier::Super: {
8259 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8260 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8261 break;
8262 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008263 }
8264 Prev = NNS;
8265 }
8266 return NNS;
8267}
8268
8269NestedNameSpecifierLoc
8270ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8271 unsigned &Idx) {
8272 unsigned N = Record[Idx++];
8273 NestedNameSpecifierLocBuilder Builder;
8274 for (unsigned I = 0; I != N; ++I) {
8275 NestedNameSpecifier::SpecifierKind Kind
8276 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8277 switch (Kind) {
8278 case NestedNameSpecifier::Identifier: {
8279 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8280 SourceRange Range = ReadSourceRange(F, Record, Idx);
8281 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8282 break;
8283 }
8284
8285 case NestedNameSpecifier::Namespace: {
8286 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8287 SourceRange Range = ReadSourceRange(F, Record, Idx);
8288 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8289 break;
8290 }
8291
8292 case NestedNameSpecifier::NamespaceAlias: {
8293 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8294 SourceRange Range = ReadSourceRange(F, Record, Idx);
8295 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8296 break;
8297 }
8298
8299 case NestedNameSpecifier::TypeSpec:
8300 case NestedNameSpecifier::TypeSpecWithTemplate: {
8301 bool Template = Record[Idx++];
8302 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8303 if (!T)
8304 return NestedNameSpecifierLoc();
8305 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8306
8307 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8308 Builder.Extend(Context,
8309 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8310 T->getTypeLoc(), ColonColonLoc);
8311 break;
8312 }
8313
8314 case NestedNameSpecifier::Global: {
8315 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8316 Builder.MakeGlobal(Context, ColonColonLoc);
8317 break;
8318 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008319
8320 case NestedNameSpecifier::Super: {
8321 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8322 SourceRange Range = ReadSourceRange(F, Record, Idx);
8323 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8324 break;
8325 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008326 }
8327 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008328
Guy Benyei11169dd2012-12-18 14:30:41 +00008329 return Builder.getWithLocInContext(Context);
8330}
8331
8332SourceRange
8333ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8334 unsigned &Idx) {
8335 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8336 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8337 return SourceRange(beg, end);
8338}
8339
8340/// \brief Read an integral value
8341llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8342 unsigned BitWidth = Record[Idx++];
8343 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8344 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8345 Idx += NumWords;
8346 return Result;
8347}
8348
8349/// \brief Read a signed integral value
8350llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8351 bool isUnsigned = Record[Idx++];
8352 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8353}
8354
8355/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008356llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8357 const llvm::fltSemantics &Sem,
8358 unsigned &Idx) {
8359 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008360}
8361
8362// \brief Read a string
8363std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8364 unsigned Len = Record[Idx++];
8365 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8366 Idx += Len;
8367 return Result;
8368}
8369
Richard Smith7ed1bc92014-12-05 22:42:13 +00008370std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8371 unsigned &Idx) {
8372 std::string Filename = ReadString(Record, Idx);
8373 ResolveImportedPath(F, Filename);
8374 return Filename;
8375}
8376
Guy Benyei11169dd2012-12-18 14:30:41 +00008377VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8378 unsigned &Idx) {
8379 unsigned Major = Record[Idx++];
8380 unsigned Minor = Record[Idx++];
8381 unsigned Subminor = Record[Idx++];
8382 if (Minor == 0)
8383 return VersionTuple(Major);
8384 if (Subminor == 0)
8385 return VersionTuple(Major, Minor - 1);
8386 return VersionTuple(Major, Minor - 1, Subminor - 1);
8387}
8388
8389CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8390 const RecordData &Record,
8391 unsigned &Idx) {
8392 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8393 return CXXTemporary::Create(Context, Decl);
8394}
8395
8396DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008397 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008398}
8399
8400DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8401 return Diags.Report(Loc, DiagID);
8402}
8403
8404/// \brief Retrieve the identifier table associated with the
8405/// preprocessor.
8406IdentifierTable &ASTReader::getIdentifierTable() {
8407 return PP.getIdentifierTable();
8408}
8409
8410/// \brief Record that the given ID maps to the given switch-case
8411/// statement.
8412void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008413 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008414 "Already have a SwitchCase with this ID");
8415 (*CurrSwitchCaseStmts)[ID] = SC;
8416}
8417
8418/// \brief Retrieve the switch-case statement with the given ID.
8419SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008420 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008421 return (*CurrSwitchCaseStmts)[ID];
8422}
8423
8424void ASTReader::ClearSwitchCaseIDs() {
8425 CurrSwitchCaseStmts->clear();
8426}
8427
8428void ASTReader::ReadComments() {
8429 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008430 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008431 serialization::ModuleFile *> >::iterator
8432 I = CommentsCursors.begin(),
8433 E = CommentsCursors.end();
8434 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008435 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008436 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008437 serialization::ModuleFile &F = *I->second;
8438 SavedStreamPosition SavedPosition(Cursor);
8439
8440 RecordData Record;
8441 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008442 llvm::BitstreamEntry Entry =
8443 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008444
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008445 switch (Entry.Kind) {
8446 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8447 case llvm::BitstreamEntry::Error:
8448 Error("malformed block record in AST file");
8449 return;
8450 case llvm::BitstreamEntry::EndBlock:
8451 goto NextCursor;
8452 case llvm::BitstreamEntry::Record:
8453 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008454 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008455 }
8456
8457 // Read a record.
8458 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008459 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008460 case COMMENTS_RAW_COMMENT: {
8461 unsigned Idx = 0;
8462 SourceRange SR = ReadSourceRange(F, Record, Idx);
8463 RawComment::CommentKind Kind =
8464 (RawComment::CommentKind) Record[Idx++];
8465 bool IsTrailingComment = Record[Idx++];
8466 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008467 Comments.push_back(new (Context) RawComment(
8468 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8469 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008470 break;
8471 }
8472 }
8473 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008474 NextCursor:
8475 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008476 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008477}
8478
Richard Smithcd45dbc2014-04-19 03:48:30 +00008479std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8480 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008481 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008482 return M->getFullModuleName();
8483
8484 // Otherwise, use the name of the top-level module the decl is within.
8485 if (ModuleFile *M = getOwningModuleFile(D))
8486 return M->ModuleName;
8487
8488 // Not from a module.
8489 return "";
8490}
8491
Guy Benyei11169dd2012-12-18 14:30:41 +00008492void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008493 while (!PendingIdentifierInfos.empty() ||
8494 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008495 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008496 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008497 // If any identifiers with corresponding top-level declarations have
8498 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008499 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8500 TopLevelDeclsMap;
8501 TopLevelDeclsMap TopLevelDecls;
8502
Guy Benyei11169dd2012-12-18 14:30:41 +00008503 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008504 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008505 SmallVector<uint32_t, 4> DeclIDs =
8506 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008507 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008508
8509 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008510 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008511
Richard Smith851072e2014-05-19 20:59:20 +00008512 // For each decl chain that we wanted to complete while deserializing, mark
8513 // it as "still needs to be completed".
8514 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8515 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8516 }
8517 PendingIncompleteDeclChains.clear();
8518
Guy Benyei11169dd2012-12-18 14:30:41 +00008519 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008520 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008521 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008522 PendingDeclChains.clear();
8523
Douglas Gregor6168bd22013-02-18 15:53:43 +00008524 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008525 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8526 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008527 IdentifierInfo *II = TLD->first;
8528 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008529 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008530 }
8531 }
8532
Guy Benyei11169dd2012-12-18 14:30:41 +00008533 // Load any pending macro definitions.
8534 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008535 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8536 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8537 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8538 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008539 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008540 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008541 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008542 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008543 resolvePendingMacro(II, Info);
8544 }
8545 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008546 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008547 ++IDIdx) {
8548 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008549 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008550 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008551 }
8552 }
8553 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008554
8555 // Wire up the DeclContexts for Decls that we delayed setting until
8556 // recursive loading is completed.
8557 while (!PendingDeclContextInfos.empty()) {
8558 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8559 PendingDeclContextInfos.pop_front();
8560 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8561 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8562 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8563 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008564
Richard Smithd1c46742014-04-30 02:24:17 +00008565 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008566 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008567 auto Update = PendingUpdateRecords.pop_back_val();
8568 ReadingKindTracker ReadingKind(Read_Decl, *this);
8569 loadDeclUpdateRecords(Update.first, Update.second);
8570 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008571 }
Richard Smith8a639892015-01-24 01:07:20 +00008572
8573 // At this point, all update records for loaded decls are in place, so any
8574 // fake class definitions should have become real.
8575 assert(PendingFakeDefinitionData.empty() &&
8576 "faked up a class definition but never saw the real one");
8577
Guy Benyei11169dd2012-12-18 14:30:41 +00008578 // If we deserialized any C++ or Objective-C class definitions, any
8579 // Objective-C protocol definitions, or any redeclarable templates, make sure
8580 // that all redeclarations point to the definitions. Note that this can only
8581 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008582 for (Decl *D : PendingDefinitions) {
8583 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008584 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008585 // Make sure that the TagType points at the definition.
8586 const_cast<TagType*>(TagT)->decl = TD;
8587 }
Richard Smith8ce51082015-03-11 01:44:51 +00008588
Craig Topperc6914d02014-08-25 04:15:02 +00008589 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008590 for (auto *R = getMostRecentExistingDecl(RD); R;
8591 R = R->getPreviousDecl()) {
8592 assert((R == D) ==
8593 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008594 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008595 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008596 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008597 }
8598
8599 continue;
8600 }
Richard Smith8ce51082015-03-11 01:44:51 +00008601
Craig Topperc6914d02014-08-25 04:15:02 +00008602 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008603 // Make sure that the ObjCInterfaceType points at the definition.
8604 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8605 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008606
8607 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8608 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8609
Guy Benyei11169dd2012-12-18 14:30:41 +00008610 continue;
8611 }
Richard Smith8ce51082015-03-11 01:44:51 +00008612
Craig Topperc6914d02014-08-25 04:15:02 +00008613 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008614 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8615 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8616
Guy Benyei11169dd2012-12-18 14:30:41 +00008617 continue;
8618 }
Richard Smith8ce51082015-03-11 01:44:51 +00008619
Craig Topperc6914d02014-08-25 04:15:02 +00008620 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008621 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8622 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008623 }
8624 PendingDefinitions.clear();
8625
8626 // Load the bodies of any functions or methods we've encountered. We do
8627 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008628 // have been fully wired up (hasBody relies on this).
8629 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008630 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8631 PBEnd = PendingBodies.end();
8632 PB != PBEnd; ++PB) {
8633 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8634 // FIXME: Check for =delete/=default?
8635 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008636 const FunctionDecl *Defn = nullptr;
8637 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008638 FD->setLazyBody(PB->second);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00008639 else
Richard Smith6561f922016-09-12 21:06:40 +00008640 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008641 continue;
8642 }
8643
8644 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8645 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8646 MD->setLazyBody(PB->second);
8647 }
8648 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008649
8650 // Do some cleanup.
8651 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8652 getContext().deduplicateMergedDefinitonsFor(ND);
8653 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008654}
8655
8656void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008657 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8658 return;
8659
Richard Smitha0ce9c42014-07-29 23:23:27 +00008660 // Trigger the import of the full definition of each class that had any
8661 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008662 // These updates may in turn find and diagnose some ODR failures, so take
8663 // ownership of the set first.
8664 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8665 PendingOdrMergeFailures.clear();
8666 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008667 Merge.first->buildLookup();
8668 Merge.first->decls_begin();
8669 Merge.first->bases_begin();
8670 Merge.first->vbases_begin();
8671 for (auto *RD : Merge.second) {
8672 RD->decls_begin();
8673 RD->bases_begin();
8674 RD->vbases_begin();
8675 }
8676 }
8677
8678 // For each declaration from a merged context, check that the canonical
8679 // definition of that context also contains a declaration of the same
8680 // entity.
8681 //
8682 // Caution: this loop does things that might invalidate iterators into
8683 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8684 while (!PendingOdrMergeChecks.empty()) {
8685 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8686
8687 // FIXME: Skip over implicit declarations for now. This matters for things
8688 // like implicitly-declared special member functions. This isn't entirely
8689 // correct; we can end up with multiple unmerged declarations of the same
8690 // implicit entity.
8691 if (D->isImplicit())
8692 continue;
8693
8694 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008695
8696 bool Found = false;
8697 const Decl *DCanon = D->getCanonicalDecl();
8698
Richard Smith01bdb7a2014-08-28 05:44:07 +00008699 for (auto RI : D->redecls()) {
8700 if (RI->getLexicalDeclContext() == CanonDef) {
8701 Found = true;
8702 break;
8703 }
8704 }
8705 if (Found)
8706 continue;
8707
Richard Smith0f4e2c42015-08-06 04:23:48 +00008708 // Quick check failed, time to do the slow thing. Note, we can't just
8709 // look up the name of D in CanonDef here, because the member that is
8710 // in CanonDef might not be found by name lookup (it might have been
8711 // replaced by a more recent declaration in the lookup table), and we
8712 // can't necessarily find it in the redeclaration chain because it might
8713 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008714 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008715 for (auto *CanonMember : CanonDef->decls()) {
8716 if (CanonMember->getCanonicalDecl() == DCanon) {
8717 // This can happen if the declaration is merely mergeable and not
8718 // actually redeclarable (we looked for redeclarations earlier).
8719 //
8720 // FIXME: We should be able to detect this more efficiently, without
8721 // pulling in all of the members of CanonDef.
8722 Found = true;
8723 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008724 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008725 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8726 if (ND->getDeclName() == D->getDeclName())
8727 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008728 }
8729
8730 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008731 // The AST doesn't like TagDecls becoming invalid after they've been
8732 // completed. We only really need to mark FieldDecls as invalid here.
8733 if (!isa<TagDecl>(D))
8734 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008735
8736 // Ensure we don't accidentally recursively enter deserialization while
8737 // we're producing our diagnostic.
8738 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008739
8740 std::string CanonDefModule =
8741 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8742 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8743 << D << getOwningModuleNameForDiagnostic(D)
8744 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8745
8746 if (Candidates.empty())
8747 Diag(cast<Decl>(CanonDef)->getLocation(),
8748 diag::note_module_odr_violation_no_possible_decls) << D;
8749 else {
8750 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8751 Diag(Candidates[I]->getLocation(),
8752 diag::note_module_odr_violation_possible_decl)
8753 << Candidates[I];
8754 }
8755
8756 DiagnosedOdrMergeFailures.insert(CanonDef);
8757 }
8758 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008759
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008760 if (OdrMergeFailures.empty())
8761 return;
8762
8763 // Ensure we don't accidentally recursively enter deserialization while
8764 // we're producing our diagnostics.
8765 Deserializing RecursionGuard(this);
8766
Richard Smithcd45dbc2014-04-19 03:48:30 +00008767 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008768 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008769 // If we've already pointed out a specific problem with this class, don't
8770 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008771 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008772 continue;
8773
8774 bool Diagnosed = false;
8775 for (auto *RD : Merge.second) {
8776 // Multiple different declarations got merged together; tell the user
8777 // where they came from.
8778 if (Merge.first != RD) {
8779 // FIXME: Walk the definition, figure out what's different,
8780 // and diagnose that.
8781 if (!Diagnosed) {
8782 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8783 Diag(Merge.first->getLocation(),
8784 diag::err_module_odr_violation_different_definitions)
8785 << Merge.first << Module.empty() << Module;
8786 Diagnosed = true;
8787 }
8788
8789 Diag(RD->getLocation(),
8790 diag::note_module_odr_violation_different_definitions)
8791 << getOwningModuleNameForDiagnostic(RD);
8792 }
8793 }
8794
8795 if (!Diagnosed) {
8796 // All definitions are updates to the same declaration. This happens if a
8797 // module instantiates the declaration of a class template specialization
8798 // and two or more other modules instantiate its definition.
8799 //
8800 // FIXME: Indicate which modules had instantiations of this definition.
8801 // FIXME: How can this even happen?
8802 Diag(Merge.first->getLocation(),
8803 diag::err_module_odr_violation_different_instantiations)
8804 << Merge.first;
8805 }
8806 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008807}
8808
Richard Smithce18a182015-07-14 00:26:00 +00008809void ASTReader::StartedDeserializing() {
8810 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8811 ReadTimer->startTimer();
8812}
8813
Guy Benyei11169dd2012-12-18 14:30:41 +00008814void ASTReader::FinishedDeserializing() {
8815 assert(NumCurrentElementsDeserializing &&
8816 "FinishedDeserializing not paired with StartedDeserializing");
8817 if (NumCurrentElementsDeserializing == 1) {
8818 // We decrease NumCurrentElementsDeserializing only after pending actions
8819 // are finished, to avoid recursively re-calling finishPendingActions().
8820 finishPendingActions();
8821 }
8822 --NumCurrentElementsDeserializing;
8823
Richard Smitha0ce9c42014-07-29 23:23:27 +00008824 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008825 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008826 while (!PendingExceptionSpecUpdates.empty()) {
8827 auto Updates = std::move(PendingExceptionSpecUpdates);
8828 PendingExceptionSpecUpdates.clear();
8829 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008830 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00008831 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008832 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008833 if (auto *Listener = Context.getASTMutationListener())
8834 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008835 for (auto *Redecl : Update.second->redecls())
8836 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008837 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008838 }
8839
Richard Smithce18a182015-07-14 00:26:00 +00008840 if (ReadTimer)
8841 ReadTimer->stopTimer();
8842
Richard Smith0f4e2c42015-08-06 04:23:48 +00008843 diagnoseOdrViolations();
8844
Richard Smith04d05b52014-03-23 00:27:18 +00008845 // We are not in recursive loading, so it's safe to pass the "interesting"
8846 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008847 if (Consumer)
8848 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008849 }
8850}
8851
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008852void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008853 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8854 // Remove any fake results before adding any real ones.
8855 auto It = PendingFakeLookupResults.find(II);
8856 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008857 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008858 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008859 // FIXME: this works around module+PCH performance issue.
8860 // Rather than erase the result from the map, which is O(n), just clear
8861 // the vector of NamedDecls.
8862 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008863 }
8864 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008865
8866 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8867 SemaObj->TUScope->AddDecl(D);
8868 } else if (SemaObj->TUScope) {
8869 // Adding the decl to IdResolver may have failed because it was already in
8870 // (even though it was not added in scope). If it is already in, make sure
8871 // it gets in the scope as well.
8872 if (std::find(SemaObj->IdResolver.begin(Name),
8873 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8874 SemaObj->TUScope->AddDecl(D);
8875 }
8876}
8877
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008878ASTReader::ASTReader(
8879 Preprocessor &PP, ASTContext &Context,
8880 const PCHContainerReader &PCHContainerRdr,
8881 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8882 StringRef isysroot, bool DisableValidation,
8883 bool AllowASTWithCompilerErrors,
8884 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8885 bool UseGlobalIndex,
8886 std::unique_ptr<llvm::Timer> ReadTimer)
Yaxun Liu43712e02016-09-07 18:40:20 +00008887 : Listener(DisableValidation ?
8888 cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) :
8889 cast<ASTReaderListener>(new PCHValidator(PP, *this))),
8890 DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008891 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008892 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008893 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008894 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smith10379092016-05-06 23:14:07 +00008895 DummyIdResolver(PP),
Richard Smithce18a182015-07-14 00:26:00 +00008896 ReadTimer(std::move(ReadTimer)),
Nico Weber779355f2016-03-02 23:22:00 +00008897 PragmaMSStructState(-1),
Nico Weber42932312016-03-03 00:17:35 +00008898 PragmaMSPointersToMembersState(-1),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008899 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008900 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8901 AllowConfigurationMismatch(AllowConfigurationMismatch),
8902 ValidateSystemInputs(ValidateSystemInputs),
8903 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008904 ProcessingUpdateRecords(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008905 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8906 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8907 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8908 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008909 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8910 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8911 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8912 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8913 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8914 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008915 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008916 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008917
8918 for (const auto &Ext : Extensions) {
8919 auto BlockName = Ext->getExtensionMetadata().BlockName;
8920 auto Known = ModuleFileExtensions.find(BlockName);
8921 if (Known != ModuleFileExtensions.end()) {
8922 Diags.Report(diag::warn_duplicate_module_file_extension)
8923 << BlockName;
8924 continue;
8925 }
8926
8927 ModuleFileExtensions.insert({BlockName, Ext});
8928 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008929}
8930
8931ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008932 if (OwnsDeserializationListener)
8933 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008934}
Richard Smith10379092016-05-06 23:14:07 +00008935
8936IdentifierResolver &ASTReader::getIdResolver() {
8937 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
8938}