blob: e659ff047d76b17196e690ec125e675f54ed0f20 [file] [log] [blame]
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner92ba5ff2009-04-27 05:14:47 +000013
Douglas Gregoref84c4b2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor55abb232009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar732ef8a2009-11-11 23:58:53 +000016#include "clang/Frontend/Utils.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000017#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor1a0d0b92009-04-14 00:24:19 +000018#include "clang/AST/ASTConsumer.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000022#include "clang/AST/TypeLocVisitor.h"
Chris Lattner34321bc2009-04-10 21:41:48 +000023#include "clang/Lex/MacroInfo.h"
Douglas Gregoraae92242010-03-19 21:51:54 +000024#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000026#include "clang/Lex/HeaderSearch.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000027#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000028#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000029#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000030#include "clang/Basic/FileManager.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000031#include "clang/Basic/TargetInfo.h"
Douglas Gregord54f3a12009-10-05 21:07:28 +000032#include "clang/Basic/Version.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000033#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000034#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000035#include "llvm/Support/MemoryBuffer.h"
John McCall0ad16662009-10-29 08:12:44 +000036#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +000037#include "llvm/System/Path.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000038#include <algorithm>
Douglas Gregorc379c072009-04-28 18:58:38 +000039#include <iterator>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000040#include <cstdio>
Douglas Gregorc5046832009-04-27 18:38:38 +000041#include <sys/stat.h>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000042using namespace clang;
43
44//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000045// PCH reader validator implementation
46//===----------------------------------------------------------------------===//
47
48PCHReaderListener::~PCHReaderListener() {}
49
50bool
51PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
52 const LangOptions &PPLangOpts = PP.getLangOptions();
53#define PARSE_LANGOPT_BENIGN(Option)
54#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
55 if (PPLangOpts.Option != LangOpts.Option) { \
56 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
57 return true; \
58 }
59
60 PARSE_LANGOPT_BENIGN(Trigraphs);
61 PARSE_LANGOPT_BENIGN(BCPLComment);
62 PARSE_LANGOPT_BENIGN(DollarIdents);
63 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
64 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
65 PARSE_LANGOPT_BENIGN(ImplicitInt);
66 PARSE_LANGOPT_BENIGN(Digraphs);
67 PARSE_LANGOPT_BENIGN(HexFloats);
68 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
69 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
70 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
71 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
72 PARSE_LANGOPT_BENIGN(CXXOperatorName);
73 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
74 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
75 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
Fariborz Jahanian45878032010-02-09 19:31:38 +000076 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000077 PARSE_LANGOPT_BENIGN(PascalStrings);
78 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump11289f42009-09-09 15:08:12 +000079 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000080 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +000081 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000082 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +000083 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000084 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
85 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
86 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +000087 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000088 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000089 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000090 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
91 PARSE_LANGOPT_BENIGN(EmitAllDecls);
92 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
93 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump11289f42009-09-09 15:08:12 +000094 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000095 diag::warn_pch_heinous_extensions);
96 // FIXME: Most of the options below are benign if the macro wasn't
97 // used. Unfortunately, this means that a PCH compiled without
98 // optimization can't be used with optimization turned on, even
99 // though the only thing that changes is whether __OPTIMIZE__ was
100 // defined... but if __OPTIMIZE__ never showed up in the header, it
101 // doesn't matter. We could consider making this some special kind
102 // of check.
103 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
104 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
105 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
106 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
107 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
108 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
109 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
110 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsoned4e2952009-11-05 20:14:16 +0000111 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000112 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000113 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000114 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
115 return true;
116 }
117 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000118 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
119 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000120 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000121 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stumpd9546382009-12-12 01:27:46 +0000122 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000123 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +0000124#undef PARSE_LANGOPT_IMPORTANT
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000125#undef PARSE_LANGOPT_BENIGN
126
127 return false;
128}
129
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000130bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
131 if (Triple == PP.getTargetInfo().getTriple().str())
132 return false;
133
134 Reader.Diag(diag::warn_pch_target_triple)
135 << Triple << PP.getTargetInfo().getTriple().str();
136 return true;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000137}
138
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000139bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000140 FileID PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000141 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000142 std::string &SuggestedPredefines) {
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000143 // We are in the context of an implicit include, so the predefines buffer will
144 // have a #include entry for the PCH file itself (as normalized by the
145 // preprocessor initialization). Find it and skip over it in the checking
146 // below.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000147 llvm::SmallString<256> PCHInclude;
148 PCHInclude += "#include \"";
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000149 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000150 PCHInclude += "\"\n";
151 std::pair<llvm::StringRef,llvm::StringRef> Split =
152 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
153 llvm::StringRef Left = Split.first, Right = Split.second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000154 if (Left == PP.getPredefines()) {
155 Error("Missing PCH include entry!");
156 return true;
157 }
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000158
159 // If the predefines is equal to the joined left and right halves, we're done!
160 if (Left.size() + Right.size() == PCHPredef.size() &&
161 PCHPredef.startswith(Left) && PCHPredef.endswith(Right))
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000162 return false;
163
164 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000165
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000166 // The predefines buffers are different. Determine what the differences are,
167 // and whether they require us to reject the PCH file.
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000168 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
169 PCHPredef.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
170
171 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
172 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
173 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000174
Daniel Dunbar499baed2009-11-11 05:26:28 +0000175 // Sort both sets of predefined buffer lines, since we allow some extra
176 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000177 std::sort(CmdLineLines.begin(), CmdLineLines.end());
178 std::sort(PCHLines.begin(), PCHLines.end());
179
Daniel Dunbar499baed2009-11-11 05:26:28 +0000180 // Determine which predefines that were used to build the PCH file are missing
181 // from the command line.
182 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000183 std::set_difference(PCHLines.begin(), PCHLines.end(),
184 CmdLineLines.begin(), CmdLineLines.end(),
185 std::back_inserter(MissingPredefines));
186
187 bool MissingDefines = false;
188 bool ConflictingDefines = false;
189 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000190 llvm::StringRef Missing = MissingPredefines[I];
191 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000192 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
193 return true;
194 }
Mike Stump11289f42009-09-09 15:08:12 +0000195
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000196 // This is a macro definition. Determine the name of the macro we're
197 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000198 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000199 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000200 = Missing.find_first_of("( \n\r", StartOfMacroName);
201 assert(EndOfMacroName != std::string::npos &&
202 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000203 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000204
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000205 // Determine whether this macro was given a different definition on the
206 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000207 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000208 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000209 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000210 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
211 MacroDefStart);
212 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000213 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000214 // Different macro; we're done.
215 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000216 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000217 }
Mike Stump11289f42009-09-09 15:08:12 +0000218
219 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000220 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000221 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000222 (*ConflictPos)[MacroDefLen] != '(')
223 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000224
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000225 // We found a conflicting macro definition.
226 break;
227 }
Mike Stump11289f42009-09-09 15:08:12 +0000228
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000229 if (ConflictPos != CmdLineLines.end()) {
230 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
231 << MacroName;
232
233 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000234 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
235 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
236 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
237 .getFileLocWithOffset(Offset);
238 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000239
240 ConflictingDefines = true;
241 continue;
242 }
Mike Stump11289f42009-09-09 15:08:12 +0000243
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000244 // If the macro doesn't conflict, then we'll just pick up the macro
245 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000246 if (ConflictingDefines)
247 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000248
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000249 if (!MissingDefines) {
250 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
251 MissingDefines = true;
252 }
253
254 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000255 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
256 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
257 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000258 .getFileLocWithOffset(Offset);
259 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
260 }
Mike Stump11289f42009-09-09 15:08:12 +0000261
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000262 if (ConflictingDefines)
263 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000264
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000265 // Determine what predefines were introduced based on command-line
266 // parameters that were not present when building the PCH
267 // file. Extra #defines are okay, so long as the identifiers being
268 // defined were not used within the precompiled header.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000269 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000270 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
271 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000272 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000273 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000274 llvm::StringRef &Extra = ExtraPredefines[I];
275 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000276 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
277 return true;
278 }
279
280 // This is an extra macro definition. Determine the name of the
281 // macro we're defining.
282 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000283 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000284 = Extra.find_first_of("( \n\r", StartOfMacroName);
285 assert(EndOfMacroName != std::string::npos &&
286 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000287 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000288
289 // Check whether this name was used somewhere in the PCH file. If
290 // so, defining it as a macro could change behavior, so we reject
291 // the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000292 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000293 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000294 return true;
295 }
296
297 // Add this definition to the suggested predefines buffer.
298 SuggestedPredefines += Extra;
299 SuggestedPredefines += '\n';
300 }
301
302 // If we get here, it's because the predefines buffer had compatible
303 // contents. Accept the PCH file.
304 return false;
305}
306
Douglas Gregor5712ebc2010-03-16 16:35:32 +0000307void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
308 unsigned ID) {
309 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
310 ++NumHeaderInfos;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000311}
312
313void PCHValidator::ReadCounter(unsigned Value) {
314 PP.setCounterValue(Value);
315}
316
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000317//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000318// PCH reader implementation
319//===----------------------------------------------------------------------===//
320
Mike Stump11289f42009-09-09 15:08:12 +0000321PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
322 const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000323 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
324 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000325 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000326 IdentifierTableData(0), IdentifierLookupTable(0),
327 IdentifierOffsets(0),
328 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
329 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000330 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregor9507d462010-03-19 22:13:20 +0000331 NumPreallocatedPreprocessingEntities(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000332 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump11289f42009-09-09 15:08:12 +0000333 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000334 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000335 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000336 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000337 RelocatablePCH = false;
338}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000339
340PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000341 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000342 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000343 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000344 IdentifierTableData(0), IdentifierLookupTable(0),
345 IdentifierOffsets(0),
346 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
347 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000348 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregor9507d462010-03-19 22:13:20 +0000349 NumPreallocatedPreprocessingEntities(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000350 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump11289f42009-09-09 15:08:12 +0000351 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000352 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000353 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000354 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000355 RelocatablePCH = false;
356}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000357
358PCHReader::~PCHReader() {}
359
Chris Lattner1de76db2009-04-27 05:58:23 +0000360Expr *PCHReader::ReadDeclExpr() {
361 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
362}
363
364Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor12bfa382009-10-17 00:13:19 +0000365 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000366}
367
368
Douglas Gregora868bbd2009-04-21 22:25:48 +0000369namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000370class PCHMethodPoolLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000371 PCHReader &Reader;
372
373public:
374 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
375
376 typedef Selector external_key_type;
377 typedef external_key_type internal_key_type;
378
379 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000380
Douglas Gregorc78d3462009-04-24 21:10:55 +0000381 static bool EqualKey(const internal_key_type& a,
382 const internal_key_type& b) {
383 return a == b;
384 }
Mike Stump11289f42009-09-09 15:08:12 +0000385
Douglas Gregorc78d3462009-04-24 21:10:55 +0000386 static unsigned ComputeHash(Selector Sel) {
387 unsigned N = Sel.getNumArgs();
388 if (N == 0)
389 ++N;
390 unsigned R = 5381;
391 for (unsigned I = 0; I != N; ++I)
392 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000393 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000394 return R;
395 }
Mike Stump11289f42009-09-09 15:08:12 +0000396
Douglas Gregorc78d3462009-04-24 21:10:55 +0000397 // This hopefully will just get inlined and removed by the optimizer.
398 static const internal_key_type&
399 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000400
Douglas Gregorc78d3462009-04-24 21:10:55 +0000401 static std::pair<unsigned, unsigned>
402 ReadKeyDataLength(const unsigned char*& d) {
403 using namespace clang::io;
404 unsigned KeyLen = ReadUnalignedLE16(d);
405 unsigned DataLen = ReadUnalignedLE16(d);
406 return std::make_pair(KeyLen, DataLen);
407 }
Mike Stump11289f42009-09-09 15:08:12 +0000408
Douglas Gregor95c13f52009-04-25 17:48:32 +0000409 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000410 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000411 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000412 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000413 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000414 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
415 if (N == 0)
416 return SelTable.getNullarySelector(FirstII);
417 else if (N == 1)
418 return SelTable.getUnarySelector(FirstII);
419
420 llvm::SmallVector<IdentifierInfo *, 16> Args;
421 Args.push_back(FirstII);
422 for (unsigned I = 1; I != N; ++I)
423 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
424
Douglas Gregor038c3382009-05-22 22:45:36 +0000425 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000426 }
Mike Stump11289f42009-09-09 15:08:12 +0000427
Douglas Gregorc78d3462009-04-24 21:10:55 +0000428 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
429 using namespace clang::io;
430 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
431 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
432
433 data_type Result;
434
435 // Load instance methods
436 ObjCMethodList *Prev = 0;
437 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000438 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000439 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
440 if (!Result.first.Method) {
441 // This is the first method, which is the easy case.
442 Result.first.Method = Method;
443 Prev = &Result.first;
444 continue;
445 }
446
Ted Kremenekda4abf12010-02-11 00:53:01 +0000447 ObjCMethodList *Mem =
448 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
449 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000450 Prev = Prev->Next;
451 }
452
453 // Load factory methods
454 Prev = 0;
455 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000456 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000457 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
458 if (!Result.second.Method) {
459 // This is the first method, which is the easy case.
460 Result.second.Method = Method;
461 Prev = &Result.second;
462 continue;
463 }
464
Ted Kremenekda4abf12010-02-11 00:53:01 +0000465 ObjCMethodList *Mem =
466 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
467 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000468 Prev = Prev->Next;
469 }
470
471 return Result;
472 }
473};
Mike Stump11289f42009-09-09 15:08:12 +0000474
475} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000476
477/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000478typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000479 PCHMethodPoolLookupTable;
480
481namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000482class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000483 PCHReader &Reader;
484
485 // If we know the IdentifierInfo in advance, it is here and we will
486 // not build a new one. Used when deserializing information about an
487 // identifier that was constructed before the PCH file was read.
488 IdentifierInfo *KnownII;
489
490public:
491 typedef IdentifierInfo * data_type;
492
493 typedef const std::pair<const char*, unsigned> external_key_type;
494
495 typedef external_key_type internal_key_type;
496
Mike Stump11289f42009-09-09 15:08:12 +0000497 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregora868bbd2009-04-21 22:25:48 +0000498 : Reader(Reader), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000499
Douglas Gregora868bbd2009-04-21 22:25:48 +0000500 static bool EqualKey(const internal_key_type& a,
501 const internal_key_type& b) {
502 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
503 : false;
504 }
Mike Stump11289f42009-09-09 15:08:12 +0000505
Douglas Gregora868bbd2009-04-21 22:25:48 +0000506 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000507 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000508 }
Mike Stump11289f42009-09-09 15:08:12 +0000509
Douglas Gregora868bbd2009-04-21 22:25:48 +0000510 // This hopefully will just get inlined and removed by the optimizer.
511 static const internal_key_type&
512 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000513
Douglas Gregora868bbd2009-04-21 22:25:48 +0000514 static std::pair<unsigned, unsigned>
515 ReadKeyDataLength(const unsigned char*& d) {
516 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000517 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000518 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000519 return std::make_pair(KeyLen, DataLen);
520 }
Mike Stump11289f42009-09-09 15:08:12 +0000521
Douglas Gregora868bbd2009-04-21 22:25:48 +0000522 static std::pair<const char*, unsigned>
523 ReadKey(const unsigned char* d, unsigned n) {
524 assert(n >= 2 && d[n-1] == '\0');
525 return std::make_pair((const char*) d, n-1);
526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
528 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000529 const unsigned char* d,
530 unsigned DataLen) {
531 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000532 pch::IdentID ID = ReadUnalignedLE32(d);
533 bool IsInteresting = ID & 0x01;
534
535 // Wipe out the "is interesting" bit.
536 ID = ID >> 1;
537
538 if (!IsInteresting) {
539 // For unintersting identifiers, just build the IdentifierInfo
540 // and associate it with the persistent ID.
541 IdentifierInfo *II = KnownII;
542 if (!II)
543 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
544 k.first, k.first + k.second);
545 Reader.SetIdentifierInfo(ID, II);
546 return II;
547 }
548
Douglas Gregorb9256522009-04-28 21:32:13 +0000549 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000550 bool CPlusPlusOperatorKeyword = Bits & 0x01;
551 Bits >>= 1;
552 bool Poisoned = Bits & 0x01;
553 Bits >>= 1;
554 bool ExtensionToken = Bits & 0x01;
555 Bits >>= 1;
556 bool hasMacroDefinition = Bits & 0x01;
557 Bits >>= 1;
558 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
559 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000560
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000561 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000562 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000563
564 // Build the IdentifierInfo itself and link the identifier ID with
565 // the new IdentifierInfo.
566 IdentifierInfo *II = KnownII;
567 if (!II)
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000568 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
569 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000570 Reader.SetIdentifierInfo(ID, II);
571
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000572 // Set or check the various bits in the IdentifierInfo structure.
573 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000574 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000575 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000576 "Incorrect extension token flag");
577 (void)ExtensionToken;
578 II->setIsPoisoned(Poisoned);
579 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
580 "Incorrect C++ operator keyword flag");
581 (void)CPlusPlusOperatorKeyword;
582
Douglas Gregorc3366a52009-04-21 23:56:24 +0000583 // If this identifier is a macro, deserialize the macro
584 // definition.
585 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000586 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregorc3366a52009-04-21 23:56:24 +0000587 Reader.ReadMacroRecord(Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000588 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000589 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000590
591 // Read all of the declarations visible at global scope with this
592 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000593 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000594 if (DataLen > 0) {
595 llvm::SmallVector<uint32_t, 4> DeclIDs;
596 for (; DataLen > 0; DataLen -= 4)
597 DeclIDs.push_back(ReadUnalignedLE32(d));
598 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000599 }
Mike Stump11289f42009-09-09 15:08:12 +0000600
Douglas Gregora868bbd2009-04-21 22:25:48 +0000601 return II;
602 }
603};
Mike Stump11289f42009-09-09 15:08:12 +0000604
605} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000606
607/// \brief The on-disk hash table used to contain information about
608/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000609typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000610 PCHIdentifierLookupTable;
611
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000612void PCHReader::Error(const char *Msg) {
613 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000614}
615
Douglas Gregor92863e42009-04-10 23:10:45 +0000616/// \brief Check the contents of the predefines buffer against the
617/// contents of the predefines buffer used to build the PCH file.
618///
619/// The contents of the two predefines buffers should be the same. If
620/// not, then some command-line option changed the preprocessor state
621/// and we must reject the PCH file.
622///
623/// \param PCHPredef The start of the predefines buffer in the PCH
624/// file.
625///
626/// \param PCHPredefLen The length of the predefines buffer in the PCH
627/// file.
628///
629/// \param PCHBufferID The FileID for the PCH predefines buffer.
630///
631/// \returns true if there was a mismatch (in which case the PCH file
632/// should be ignored), or false otherwise.
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000633bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregor92863e42009-04-10 23:10:45 +0000634 FileID PCHBufferID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000635 if (Listener)
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000636 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000637 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000638 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000639 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000640}
641
Douglas Gregorc5046832009-04-27 18:38:38 +0000642//===----------------------------------------------------------------------===//
643// Source Manager Deserialization
644//===----------------------------------------------------------------------===//
645
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000646/// \brief Read the line table in the source manager block.
647/// \returns true if ther was an error.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000648bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000649 unsigned Idx = 0;
650 LineTableInfo &LineTable = SourceMgr.getLineTable();
651
652 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000653 std::map<int, int> FileIDs;
654 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000655 // Extract the file name
656 unsigned FilenameLen = Record[Idx++];
657 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
658 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000659 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000660 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000661 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000662 }
663
664 // Parse the line entries
665 std::vector<LineEntry> Entries;
666 while (Idx < Record.size()) {
Douglas Gregora8854652009-04-13 17:12:42 +0000667 int FID = FileIDs[Record[Idx++]];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000668
669 // Extract the line entries
670 unsigned NumEntries = Record[Idx++];
671 Entries.clear();
672 Entries.reserve(NumEntries);
673 for (unsigned I = 0; I != NumEntries; ++I) {
674 unsigned FileOffset = Record[Idx++];
675 unsigned LineNo = Record[Idx++];
676 int FilenameID = Record[Idx++];
Mike Stump11289f42009-09-09 15:08:12 +0000677 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000678 = (SrcMgr::CharacteristicKind)Record[Idx++];
679 unsigned IncludeOffset = Record[Idx++];
680 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
681 FileKind, IncludeOffset));
682 }
683 LineTable.AddEntry(FID, Entries);
684 }
685
686 return false;
687}
688
Douglas Gregorc5046832009-04-27 18:38:38 +0000689namespace {
690
Benjamin Kramer16634c22009-11-28 10:07:24 +0000691class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000692public:
693 const bool hasStat;
694 const ino_t ino;
695 const dev_t dev;
696 const mode_t mode;
697 const time_t mtime;
698 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000699
Douglas Gregorc5046832009-04-27 18:38:38 +0000700 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000701 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
702
Douglas Gregorc5046832009-04-27 18:38:38 +0000703 PCHStatData()
704 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
705};
706
Benjamin Kramer16634c22009-11-28 10:07:24 +0000707class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000708 public:
709 typedef const char *external_key_type;
710 typedef const char *internal_key_type;
711
712 typedef PCHStatData data_type;
713
714 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000715 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000716 }
717
718 static internal_key_type GetInternalKey(const char *path) { return path; }
719
720 static bool EqualKey(internal_key_type a, internal_key_type b) {
721 return strcmp(a, b) == 0;
722 }
723
724 static std::pair<unsigned, unsigned>
725 ReadKeyDataLength(const unsigned char*& d) {
726 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
727 unsigned DataLen = (unsigned) *d++;
728 return std::make_pair(KeyLen + 1, DataLen);
729 }
730
731 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
732 return (const char *)d;
733 }
734
735 static data_type ReadData(const internal_key_type, const unsigned char *d,
736 unsigned /*DataLen*/) {
737 using namespace clang::io;
738
739 if (*d++ == 1)
740 return data_type();
741
742 ino_t ino = (ino_t) ReadUnalignedLE32(d);
743 dev_t dev = (dev_t) ReadUnalignedLE32(d);
744 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000745 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000746 off_t size = (off_t) ReadUnalignedLE64(d);
747 return data_type(ino, dev, mode, mtime, size);
748 }
749};
750
751/// \brief stat() cache for precompiled headers.
752///
753/// This cache is very similar to the stat cache used by pretokenized
754/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000755class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000756 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
757 CacheTy *Cache;
758
759 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000760public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000761 PCHStatCache(const unsigned char *Buckets,
762 const unsigned char *Base,
763 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000764 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000765 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
766 Cache = CacheTy::Create(Buckets, Base);
767 }
768
769 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000770
Douglas Gregorc5046832009-04-27 18:38:38 +0000771 int stat(const char *path, struct stat *buf) {
772 // Do the lookup for the file's data in the PCH file.
773 CacheTy::iterator I = Cache->find(path);
774
775 // If we don't get a hit in the PCH file just forward to 'stat'.
776 if (I == Cache->end()) {
777 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000778 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000779 }
Mike Stump11289f42009-09-09 15:08:12 +0000780
Douglas Gregorc5046832009-04-27 18:38:38 +0000781 ++NumStatHits;
782 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregorc5046832009-04-27 18:38:38 +0000784 if (!Data.hasStat)
785 return 1;
786
787 buf->st_ino = Data.ino;
788 buf->st_dev = Data.dev;
789 buf->st_mtime = Data.mtime;
790 buf->st_mode = Data.mode;
791 buf->st_size = Data.size;
792 return 0;
793 }
794};
795} // end anonymous namespace
796
797
Douglas Gregora7f71a92009-04-10 03:52:48 +0000798/// \brief Read the source manager block
Douglas Gregor92863e42009-04-10 23:10:45 +0000799PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000800 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000801
802 // Set the source-location entry cursor to the current position in
803 // the stream. This cursor will be used to read the contents of the
804 // source manager block initially, and then lazily read
805 // source-location entries as needed.
806 SLocEntryCursor = Stream;
807
808 // The stream itself is going to skip over the source manager block.
809 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000810 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000811 return Failure;
812 }
813
814 // Enter the source manager block.
815 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000816 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000817 return Failure;
818 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000819
Douglas Gregora7f71a92009-04-10 03:52:48 +0000820 RecordData Record;
821 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000822 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000823 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000824 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000825 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000826 return Failure;
827 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000828 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000829 }
Mike Stump11289f42009-09-09 15:08:12 +0000830
Douglas Gregora7f71a92009-04-10 03:52:48 +0000831 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
832 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000833 SLocEntryCursor.ReadSubBlockID();
834 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000835 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000836 return Failure;
837 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000838 continue;
839 }
Mike Stump11289f42009-09-09 15:08:12 +0000840
Douglas Gregora7f71a92009-04-10 03:52:48 +0000841 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000842 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000843 continue;
844 }
Mike Stump11289f42009-09-09 15:08:12 +0000845
Douglas Gregora7f71a92009-04-10 03:52:48 +0000846 // Read a record.
847 const char *BlobStart;
848 unsigned BlobLen;
849 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000850 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000851 default: // Default behavior: ignore.
852 break;
853
Chris Lattner184e65d2009-04-14 23:22:57 +0000854 case pch::SM_LINE_TABLE:
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000855 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000856 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000857 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000858
Douglas Gregor258ae542009-04-27 06:38:32 +0000859 case pch::SM_SLOC_FILE_ENTRY:
860 case pch::SM_SLOC_BUFFER_ENTRY:
861 case pch::SM_SLOC_INSTANTIATION_ENTRY:
862 // Once we hit one of the source location entries, we're done.
863 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000864 }
865 }
866}
867
Douglas Gregor258ae542009-04-27 06:38:32 +0000868/// \brief Read in the source location entry with the given ID.
869PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
870 if (ID == 0)
871 return Success;
872
873 if (ID > TotalNumSLocEntries) {
874 Error("source location entry ID out-of-range for PCH file");
875 return Failure;
876 }
877
878 ++NumSLocEntriesRead;
879 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
880 unsigned Code = SLocEntryCursor.ReadCode();
881 if (Code == llvm::bitc::END_BLOCK ||
882 Code == llvm::bitc::ENTER_SUBBLOCK ||
883 Code == llvm::bitc::DEFINE_ABBREV) {
884 Error("incorrectly-formatted source location entry in PCH file");
885 return Failure;
886 }
887
Douglas Gregor258ae542009-04-27 06:38:32 +0000888 RecordData Record;
889 const char *BlobStart;
890 unsigned BlobLen;
891 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
892 default:
893 Error("incorrectly-formatted source location entry in PCH file");
894 return Failure;
895
896 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000897 std::string Filename(BlobStart, BlobStart + BlobLen);
898 MaybeAddSystemRootToFilename(Filename);
899 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000900 if (File == 0) {
901 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000902 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000903 ErrorStr += "' referenced by PCH file";
904 Error(ErrorStr.c_str());
905 return Failure;
906 }
Mike Stump11289f42009-09-09 15:08:12 +0000907
Ted Kremenekabb1ddd2010-03-18 21:23:05 +0000908 if (Record.size() < 8) {
909 Error("source location entry is incorrect");
910 return Failure;
911 }
912
Douglas Gregor258ae542009-04-27 06:38:32 +0000913 FileID FID = SourceMgr.createFileID(File,
914 SourceLocation::getFromRawEncoding(Record[1]),
915 (SrcMgr::CharacteristicKind)Record[2],
916 ID, Record[0]);
917 if (Record[3])
918 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
919 .setHasLineDirectives();
920
Douglas Gregor5712ebc2010-03-16 16:35:32 +0000921 // Reconstruct header-search information for this file.
922 HeaderFileInfo HFI;
923 HFI.isImport = Record[4];
924 HFI.DirInfo = Record[5];
925 HFI.NumIncludes = Record[6];
926 HFI.ControllingMacroID = Record[7];
927 if (Listener)
928 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor258ae542009-04-27 06:38:32 +0000929 break;
930 }
931
932 case pch::SM_SLOC_BUFFER_ENTRY: {
933 const char *Name = BlobStart;
934 unsigned Offset = Record[0];
935 unsigned Code = SLocEntryCursor.ReadCode();
936 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000937 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +0000938 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000939
940 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
941 Error("PCH record has invalid code");
942 return Failure;
943 }
944
Douglas Gregor258ae542009-04-27 06:38:32 +0000945 llvm::MemoryBuffer *Buffer
Mike Stump11289f42009-09-09 15:08:12 +0000946 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor258ae542009-04-27 06:38:32 +0000947 BlobStart + BlobLen - 1,
948 Name);
949 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000950
Douglas Gregore6648fb2009-04-28 20:33:11 +0000951 if (strcmp(Name, "<built-in>") == 0) {
952 PCHPredefinesBufferID = BufferID;
953 PCHPredefines = BlobStart;
954 PCHPredefinesLen = BlobLen - 1;
955 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000956
957 break;
958 }
959
960 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +0000961 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +0000962 = SourceLocation::getFromRawEncoding(Record[1]);
963 SourceMgr.createInstantiationLoc(SpellingLoc,
964 SourceLocation::getFromRawEncoding(Record[2]),
965 SourceLocation::getFromRawEncoding(Record[3]),
966 Record[4],
967 ID,
968 Record[0]);
969 break;
Mike Stump11289f42009-09-09 15:08:12 +0000970 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000971 }
972
973 return Success;
974}
975
Chris Lattnere78a6be2009-04-27 01:05:14 +0000976/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
977/// specified cursor. Read the abbreviations that are at the top of the block
978/// and then leave the cursor pointing into the block.
979bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
980 unsigned BlockID) {
981 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000982 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +0000983 return Failure;
984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattnere78a6be2009-04-27 01:05:14 +0000986 while (true) {
987 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +0000988
Chris Lattnere78a6be2009-04-27 01:05:14 +0000989 // We expect all abbrevs to be at the start of the block.
990 if (Code != llvm::bitc::DEFINE_ABBREV)
991 return false;
992 Cursor.ReadAbbrevRecord();
993 }
994}
995
Douglas Gregorc3366a52009-04-21 23:56:24 +0000996void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000997 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +0000998
Douglas Gregorc3366a52009-04-21 23:56:24 +0000999 // Keep track of where we are in the stream, then jump back there
1000 // after reading this macro.
1001 SavedStreamPosition SavedPosition(Stream);
1002
1003 Stream.JumpToBit(Offset);
1004 RecordData Record;
1005 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1006 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001007
Douglas Gregorc3366a52009-04-21 23:56:24 +00001008 while (true) {
1009 unsigned Code = Stream.ReadCode();
1010 switch (Code) {
1011 case llvm::bitc::END_BLOCK:
1012 return;
1013
1014 case llvm::bitc::ENTER_SUBBLOCK:
1015 // No known subblocks, always skip them.
1016 Stream.ReadSubBlockID();
1017 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001018 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001019 return;
1020 }
1021 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001022
Douglas Gregorc3366a52009-04-21 23:56:24 +00001023 case llvm::bitc::DEFINE_ABBREV:
1024 Stream.ReadAbbrevRecord();
1025 continue;
1026 default: break;
1027 }
1028
1029 // Read a record.
1030 Record.clear();
1031 pch::PreprocessorRecordTypes RecType =
1032 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1033 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001034 case pch::PP_MACRO_OBJECT_LIKE:
1035 case pch::PP_MACRO_FUNCTION_LIKE: {
1036 // If we already have a macro, that means that we've hit the end
1037 // of the definition of the macro we were looking for. We're
1038 // done.
1039 if (Macro)
1040 return;
1041
1042 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1043 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001044 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001045 return;
1046 }
1047 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1048 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001049
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001050 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001051 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001052
Douglas Gregoraae92242010-03-19 21:51:54 +00001053 unsigned NextIndex = 3;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001054 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1055 // Decode function-like macro info.
1056 bool isC99VarArgs = Record[3];
1057 bool isGNUVarArgs = Record[4];
1058 MacroArgs.clear();
1059 unsigned NumArgs = Record[5];
Douglas Gregoraae92242010-03-19 21:51:54 +00001060 NextIndex = 6 + NumArgs;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001061 for (unsigned i = 0; i != NumArgs; ++i)
1062 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1063
1064 // Install function-like macro info.
1065 MI->setIsFunctionLike();
1066 if (isC99VarArgs) MI->setIsC99Varargs();
1067 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001068 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001069 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001070 }
1071
1072 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001073 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001074
1075 // Remember that we saw this macro last so that we add the tokens that
1076 // form its body to it.
1077 Macro = MI;
Douglas Gregoraae92242010-03-19 21:51:54 +00001078
1079 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1080 // We have a macro definition. Load it now.
1081 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1082 getMacroDefinition(Record[NextIndex]));
1083 }
1084
Douglas Gregorc3366a52009-04-21 23:56:24 +00001085 ++NumMacrosRead;
1086 break;
1087 }
Mike Stump11289f42009-09-09 15:08:12 +00001088
Douglas Gregorc3366a52009-04-21 23:56:24 +00001089 case pch::PP_TOKEN: {
1090 // If we see a TOKEN before a PP_MACRO_*, then the file is
1091 // erroneous, just pretend we didn't see this.
1092 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001093
Douglas Gregorc3366a52009-04-21 23:56:24 +00001094 Token Tok;
1095 Tok.startToken();
1096 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1097 Tok.setLength(Record[1]);
1098 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1099 Tok.setIdentifierInfo(II);
1100 Tok.setKind((tok::TokenKind)Record[3]);
1101 Tok.setFlag((Token::TokenFlags)Record[4]);
1102 Macro->AddTokenToBody(Tok);
1103 break;
1104 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001105
1106 case pch::PP_MACRO_INSTANTIATION: {
1107 // If we already have a macro, that means that we've hit the end
1108 // of the definition of the macro we were looking for. We're
1109 // done.
1110 if (Macro)
1111 return;
1112
1113 if (!PP->getPreprocessingRecord()) {
1114 Error("missing preprocessing record in PCH file");
1115 return;
1116 }
1117
1118 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1119 if (PPRec.getPreprocessedEntity(Record[0]))
1120 return;
1121
1122 MacroInstantiation *MI
1123 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1124 SourceRange(
1125 SourceLocation::getFromRawEncoding(Record[1]),
1126 SourceLocation::getFromRawEncoding(Record[2])),
1127 getMacroDefinition(Record[4]));
1128 PPRec.SetPreallocatedEntity(Record[0], MI);
1129 return;
1130 }
1131
1132 case pch::PP_MACRO_DEFINITION: {
1133 // If we already have a macro, that means that we've hit the end
1134 // of the definition of the macro we were looking for. We're
1135 // done.
1136 if (Macro)
1137 return;
1138
1139 if (!PP->getPreprocessingRecord()) {
1140 Error("missing preprocessing record in PCH file");
1141 return;
1142 }
1143
1144 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1145 if (PPRec.getPreprocessedEntity(Record[0]))
1146 return;
1147
1148 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1149 Error("out-of-bounds macro definition record");
1150 return;
1151 }
1152
1153 MacroDefinition *MD
1154 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1155 SourceLocation::getFromRawEncoding(Record[5]),
1156 SourceRange(
1157 SourceLocation::getFromRawEncoding(Record[2]),
1158 SourceLocation::getFromRawEncoding(Record[3])));
1159 PPRec.SetPreallocatedEntity(Record[0], MD);
1160 MacroDefinitionsLoaded[Record[1]] = MD;
1161 return;
1162 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001163 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001164 }
1165}
1166
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001167void PCHReader::ReadDefinedMacros() {
1168 // If there was no preprocessor block, do nothing.
1169 if (!MacroCursor.getBitStreamReader())
1170 return;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001171
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001172 llvm::BitstreamCursor Cursor = MacroCursor;
1173 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1174 Error("malformed preprocessor block record in PCH file");
1175 return;
1176 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001177
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001178 RecordData Record;
1179 while (true) {
1180 unsigned Code = Cursor.ReadCode();
1181 if (Code == llvm::bitc::END_BLOCK) {
1182 if (Cursor.ReadBlockEnd())
1183 Error("error at end of preprocessor block in PCH file");
1184 return;
1185 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001186
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001187 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1188 // No known subblocks, always skip them.
1189 Cursor.ReadSubBlockID();
1190 if (Cursor.SkipBlock()) {
1191 Error("malformed block record in PCH file");
1192 return;
1193 }
1194 continue;
1195 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001196
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001197 if (Code == llvm::bitc::DEFINE_ABBREV) {
1198 Cursor.ReadAbbrevRecord();
1199 continue;
1200 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001201
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001202 // Read a record.
1203 const char *BlobStart;
1204 unsigned BlobLen;
1205 Record.clear();
1206 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1207 default: // Default behavior: ignore.
1208 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001209
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001210 case pch::PP_MACRO_OBJECT_LIKE:
1211 case pch::PP_MACRO_FUNCTION_LIKE:
Douglas Gregoraae92242010-03-19 21:51:54 +00001212 DecodeIdentifierInfo(Record[0]);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001213 break;
1214
1215 case pch::PP_TOKEN:
1216 // Ignore tokens.
1217 break;
Douglas Gregoraae92242010-03-19 21:51:54 +00001218
1219 case pch::PP_MACRO_INSTANTIATION:
1220 case pch::PP_MACRO_DEFINITION:
1221 // Read the macro record.
1222 ReadMacroRecord(Cursor.GetCurrentBitNo());
1223 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001224 }
1225 }
1226}
1227
Douglas Gregoraae92242010-03-19 21:51:54 +00001228MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1229 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1230 return 0;
1231
1232 if (!MacroDefinitionsLoaded[ID])
1233 ReadMacroRecord(MacroDefinitionOffsets[ID]);
1234
1235 return MacroDefinitionsLoaded[ID];
1236}
1237
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001238/// \brief If we are loading a relocatable PCH file, and the filename is
1239/// not an absolute path, add the system root to the beginning of the file
1240/// name.
1241void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1242 // If this is not a relocatable PCH file, there's nothing to do.
1243 if (!RelocatablePCH)
1244 return;
Mike Stump11289f42009-09-09 15:08:12 +00001245
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001246 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001247 return;
1248
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001249 if (isysroot == 0) {
1250 // If no system root was given, default to '/'
1251 Filename.insert(Filename.begin(), '/');
1252 return;
1253 }
Mike Stump11289f42009-09-09 15:08:12 +00001254
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001255 unsigned Length = strlen(isysroot);
1256 if (isysroot[Length - 1] != '/')
1257 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001258
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001259 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1260}
1261
Mike Stump11289f42009-09-09 15:08:12 +00001262PCHReader::PCHReadResult
Douglas Gregoreda6a892009-04-26 00:07:37 +00001263PCHReader::ReadPCHBlock() {
Douglas Gregor55abb232009-04-10 20:39:37 +00001264 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001265 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001266 return Failure;
1267 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001268
1269 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001270 RecordData Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001271 while (!Stream.AtEndOfStream()) {
1272 unsigned Code = Stream.ReadCode();
1273 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001274 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001275 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001276 return Failure;
1277 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001278
Douglas Gregor55abb232009-04-10 20:39:37 +00001279 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001280 }
1281
1282 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1283 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001284 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001285 // We lazily load the decls block, but we want to set up the
1286 // DeclsCursor cursor to point into it. Clone our current bitcode
1287 // cursor to it, enter the block and read the abbrevs in that block.
1288 // With the main cursor, we just skip over it.
1289 DeclsCursor = Stream;
1290 if (Stream.SkipBlock() || // Skip with the main cursor.
1291 // Read the abbrevs.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001292 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001293 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001294 return Failure;
1295 }
1296 break;
Mike Stump11289f42009-09-09 15:08:12 +00001297
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001298 case pch::PREPROCESSOR_BLOCK_ID:
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001299 MacroCursor = Stream;
1300 if (PP)
1301 PP->setExternalSource(this);
1302
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001303 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001304 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001305 return Failure;
1306 }
1307 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001308
Douglas Gregora7f71a92009-04-10 03:52:48 +00001309 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001310 switch (ReadSourceManagerBlock()) {
1311 case Success:
1312 break;
1313
1314 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001315 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001316 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001317
1318 case IgnorePCH:
1319 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001320 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001321 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001322 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001323 continue;
1324 }
1325
1326 if (Code == llvm::bitc::DEFINE_ABBREV) {
1327 Stream.ReadAbbrevRecord();
1328 continue;
1329 }
1330
1331 // Read and process a record.
1332 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001333 const char *BlobStart = 0;
1334 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001335 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001336 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001337 default: // Default behavior: ignore.
1338 break;
1339
1340 case pch::TYPE_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001341 if (!TypesLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001342 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001343 return Failure;
1344 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001345 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001346 TypesLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001347 break;
1348
1349 case pch::DECL_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001350 if (!DeclsLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001351 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001352 return Failure;
1353 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001354 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001355 DeclsLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001356 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001357
1358 case pch::LANGUAGE_OPTIONS:
1359 if (ParseLanguageOptions(Record))
1360 return IgnorePCH;
1361 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001362
Douglas Gregor7b71e632009-04-27 22:23:34 +00001363 case pch::METADATA: {
1364 if (Record[0] != pch::VERSION_MAJOR) {
1365 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1366 : diag::warn_pch_version_too_new);
1367 return IgnorePCH;
1368 }
1369
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001370 RelocatablePCH = Record[4];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001371 if (Listener) {
1372 std::string TargetTriple(BlobStart, BlobLen);
1373 if (Listener->ReadTargetTriple(TargetTriple))
1374 return IgnorePCH;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001375 }
1376 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001377 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001378
1379 case pch::IDENTIFIER_TABLE:
Douglas Gregora868bbd2009-04-21 22:25:48 +00001380 IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001381 if (Record[0]) {
Mike Stump11289f42009-09-09 15:08:12 +00001382 IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001383 = PCHIdentifierLookupTable::Create(
Douglas Gregora868bbd2009-04-21 22:25:48 +00001384 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001385 (const unsigned char *)IdentifierTableData,
Douglas Gregora868bbd2009-04-21 22:25:48 +00001386 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001387 if (PP)
1388 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001389 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001390 break;
1391
1392 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001393 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001394 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001395 return Failure;
1396 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001397 IdentifierOffsets = (const uint32_t *)BlobStart;
1398 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001399 if (PP)
1400 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001401 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001402
1403 case pch::EXTERNAL_DEFINITIONS:
1404 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001405 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001406 return Failure;
1407 }
1408 ExternalDefinitions.swap(Record);
1409 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001410
Douglas Gregor652d82a2009-04-18 05:55:16 +00001411 case pch::SPECIAL_TYPES:
1412 SpecialTypes.swap(Record);
1413 break;
1414
Douglas Gregor08f01292009-04-17 22:13:46 +00001415 case pch::STATISTICS:
1416 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001417 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001418 TotalLexicalDeclContexts = Record[2];
1419 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001420 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001421
Douglas Gregord4df8652009-04-22 22:02:47 +00001422 case pch::TENTATIVE_DEFINITIONS:
1423 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001424 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001425 return Failure;
1426 }
1427 TentativeDefinitions.swap(Record);
1428 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001429
Tanya Lattner90073802010-02-12 00:07:30 +00001430 case pch::UNUSED_STATIC_FUNCS:
1431 if (!UnusedStaticFuncs.empty()) {
1432 Error("duplicate UNUSED_STATIC_FUNCS record in PCH file");
1433 return Failure;
1434 }
1435 UnusedStaticFuncs.swap(Record);
1436 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001437
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001438 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1439 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001440 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001441 return Failure;
1442 }
1443 LocallyScopedExternalDecls.swap(Record);
1444 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001445
Douglas Gregor95c13f52009-04-25 17:48:32 +00001446 case pch::SELECTOR_OFFSETS:
1447 SelectorOffsets = (const uint32_t *)BlobStart;
1448 TotalNumSelectors = Record[0];
1449 SelectorsLoaded.resize(TotalNumSelectors);
1450 break;
1451
Douglas Gregorc78d3462009-04-24 21:10:55 +00001452 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001453 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1454 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001455 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001456 = PCHMethodPoolLookupTable::Create(
1457 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001458 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001459 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001460 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001461 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001462
1463 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001464 if (!Record.empty() && Listener)
1465 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001466 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001467
1468 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001469 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001470 TotalNumSLocEntries = Record[0];
Douglas Gregord54f3a12009-10-05 21:07:28 +00001471 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001472 break;
1473
1474 case pch::SOURCE_LOCATION_PRELOADS:
1475 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1476 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1477 if (Result != Success)
1478 return Result;
1479 }
1480 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001481
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001482 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001483 PCHStatCache *MyStatCache =
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001484 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1485 (const unsigned char *)BlobStart,
1486 NumStatHits, NumStatMisses);
1487 FileMgr.addStatCache(MyStatCache);
1488 StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001489 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001490 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001491
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001492 case pch::EXT_VECTOR_DECLS:
1493 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001494 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001495 return Failure;
1496 }
1497 ExtVectorDecls.swap(Record);
1498 break;
1499
Douglas Gregor45fe0362009-05-12 01:31:05 +00001500 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001501 ActualOriginalFileName.assign(BlobStart, BlobLen);
1502 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001503 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001504 break;
Mike Stump11289f42009-09-09 15:08:12 +00001505
Ted Kremenek17437132010-01-22 20:59:36 +00001506 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek8bd09292010-02-12 23:31:14 +00001507 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek2377a0e2010-01-22 20:55:35 +00001508 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Ted Kremenek8bd09292010-02-12 23:31:14 +00001509 if (llvm::StringRef(CurBranch) != PCHBranch) {
Douglas Gregord54f3a12009-10-05 21:07:28 +00001510 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1511 return IgnorePCH;
1512 }
1513 break;
1514 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001515
1516 case pch::MACRO_DEFINITION_OFFSETS:
1517 MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1518 if (PP) {
1519 if (!PP->getPreprocessingRecord())
1520 PP->createPreprocessingRecord();
1521 PP->getPreprocessingRecord()->SetExternalSource(*this, Record[0]);
1522 } else {
1523 NumPreallocatedPreprocessingEntities = Record[0];
1524 }
1525
1526 MacroDefinitionsLoaded.resize(Record[1]);
1527 break;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001528 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001529 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001530 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001531 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001532}
1533
Douglas Gregor92863e42009-04-10 23:10:45 +00001534PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001535 // Set the PCH file name.
1536 this->FileName = FileName;
1537
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001538 // Open the PCH file.
Daniel Dunbar2d925eb2009-09-22 05:38:01 +00001539 //
1540 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001541 std::string ErrStr;
Daniel Dunbar69914f42009-11-10 00:46:19 +00001542 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregor92863e42009-04-10 23:10:45 +00001543 if (!Buffer) {
1544 Error(ErrStr.c_str());
1545 return IgnorePCH;
1546 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001547
1548 // Initialize the stream
Mike Stump11289f42009-09-09 15:08:12 +00001549 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattner9356ace2009-04-26 20:59:20 +00001550 (const unsigned char *)Buffer->getBufferEnd());
1551 Stream.init(StreamFile);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001552
1553 // Sniff for the signature.
1554 if (Stream.Read(8) != 'C' ||
1555 Stream.Read(8) != 'P' ||
1556 Stream.Read(8) != 'C' ||
Douglas Gregor92863e42009-04-10 23:10:45 +00001557 Stream.Read(8) != 'H') {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001558 Diag(diag::err_not_a_pch_file) << FileName;
1559 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001560 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001561
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001562 while (!Stream.AtEndOfStream()) {
1563 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001564
Douglas Gregor92863e42009-04-10 23:10:45 +00001565 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001566 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001567 return Failure;
1568 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001569
1570 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001571
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001572 // We only know the PCH subblock ID.
1573 switch (BlockID) {
1574 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001575 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001576 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001577 return Failure;
1578 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001579 break;
1580 case pch::PCH_BLOCK_ID:
Douglas Gregoreda6a892009-04-26 00:07:37 +00001581 switch (ReadPCHBlock()) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001582 case Success:
1583 break;
1584
1585 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001586 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001587
1588 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001589 // FIXME: We could consider reading through to the end of this
1590 // PCH block, skipping subblocks, to see if there are other
1591 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001592
1593 // Clear out any preallocated source location entries, so that
1594 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001595 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001596
1597 // Remove the stat cache.
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001598 if (StatCache)
1599 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001600
Douglas Gregor92863e42009-04-10 23:10:45 +00001601 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001602 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001603 break;
1604 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001605 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001606 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001607 return Failure;
1608 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001609 break;
1610 }
Mike Stump11289f42009-09-09 15:08:12 +00001611 }
1612
Douglas Gregore6648fb2009-04-28 20:33:11 +00001613 // Check the predefines buffer.
Daniel Dunbar20a682d2009-11-11 00:52:11 +00001614 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregore6648fb2009-04-28 20:33:11 +00001615 PCHPredefinesBufferID))
1616 return IgnorePCH;
Mike Stump11289f42009-09-09 15:08:12 +00001617
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001618 if (PP) {
Zhongxing Xu3f51f412009-07-18 09:26:51 +00001619 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001620 // PCH file is read, so there may be some identifiers that were
1621 // loaded into the IdentifierTable before we intercepted the
1622 // creation of identifiers. Iterate through the list of known
1623 // identifiers and determine whether we have to establish
1624 // preprocessor definitions or top-level identifier declaration
1625 // chains for those identifiers.
1626 //
1627 // We copy the IdentifierInfo pointers to a small vector first,
1628 // since de-serializing declarations or macro definitions can add
1629 // new entries into the identifier table, invalidating the
1630 // iterators.
1631 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1632 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1633 IdEnd = PP->getIdentifierTable().end();
1634 Id != IdEnd; ++Id)
1635 Identifiers.push_back(Id->second);
Mike Stump11289f42009-09-09 15:08:12 +00001636 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001637 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1638 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1639 IdentifierInfo *II = Identifiers[I];
1640 // Look in the on-disk hash table for an entry for
1641 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001642 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001643 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1644 if (Pos == IdTable->end())
1645 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001646
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001647 // Dereferencing the iterator has the effect of populating the
1648 // IdentifierInfo node with the various declarations it needs.
1649 (void)*Pos;
1650 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001651 }
1652
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001653 if (Context)
1654 InitializeContext(*Context);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001655
Douglas Gregora868bbd2009-04-21 22:25:48 +00001656 return Success;
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001657}
1658
Douglas Gregoraae92242010-03-19 21:51:54 +00001659void PCHReader::setPreprocessor(Preprocessor &pp) {
1660 PP = &pp;
1661
1662 if (NumPreallocatedPreprocessingEntities) {
1663 if (!PP->getPreprocessingRecord())
1664 PP->createPreprocessingRecord();
1665 PP->getPreprocessingRecord()->SetExternalSource(*this,
1666 NumPreallocatedPreprocessingEntities);
1667 NumPreallocatedPreprocessingEntities = 0;
1668 }
1669}
1670
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001671void PCHReader::InitializeContext(ASTContext &Ctx) {
1672 Context = &Ctx;
1673 assert(Context && "Passed null context!");
1674
1675 assert(PP && "Forgot to set Preprocessor ?");
1676 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1677 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001678 PP->setExternalSource(this);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001679
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001680 // Load the translation unit declaration
1681 ReadDeclRecord(DeclOffsets[0], 0);
1682
1683 // Load the special types.
1684 Context->setBuiltinVaListType(
1685 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1686 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1687 Context->setObjCIdType(GetType(Id));
1688 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1689 Context->setObjCSelType(GetType(Sel));
1690 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1691 Context->setObjCProtoType(GetType(Proto));
1692 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1693 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001694
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001695 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1696 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001697 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001698 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1699 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001700 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1701 QualType FileType = GetType(File);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001702 if (FileType.isNull()) {
1703 Error("FILE type is NULL");
1704 return;
1705 }
John McCall9dd450b2009-09-21 23:43:11 +00001706 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001707 Context->setFILEDecl(Typedef->getDecl());
1708 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001709 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001710 if (!Tag) {
1711 Error("Invalid FILE type in PCH file");
1712 return;
1713 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00001714 Context->setFILEDecl(Tag->getDecl());
1715 }
1716 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001717 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1718 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001719 if (Jmp_bufType.isNull()) {
1720 Error("jmp_bug type is NULL");
1721 return;
1722 }
John McCall9dd450b2009-09-21 23:43:11 +00001723 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001724 Context->setjmp_bufDecl(Typedef->getDecl());
1725 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001726 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001727 if (!Tag) {
1728 Error("Invalid jmp_bug type in PCH file");
1729 return;
1730 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001731 Context->setjmp_bufDecl(Tag->getDecl());
1732 }
1733 }
1734 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1735 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001736 if (Sigjmp_bufType.isNull()) {
1737 Error("sigjmp_buf type is NULL");
1738 return;
1739 }
John McCall9dd450b2009-09-21 23:43:11 +00001740 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001741 Context->setsigjmp_bufDecl(Typedef->getDecl());
1742 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001743 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001744 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1745 Context->setsigjmp_bufDecl(Tag->getDecl());
1746 }
1747 }
Mike Stump11289f42009-09-09 15:08:12 +00001748 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001749 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1750 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001751 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001752 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1753 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001754#if 0
1755 // FIXME. Accommodate for this in several PCH/Index tests
1756 if (unsigned ObjCSelRedef
1757 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00001758 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001759#endif
Mike Stumpd0153282009-10-20 02:12:22 +00001760 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1761 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00001762 if (unsigned String
1763 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1764 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001765}
1766
Douglas Gregor45fe0362009-05-12 01:31:05 +00001767/// \brief Retrieve the name of the original source file name
1768/// directly from the PCH file, without actually loading the PCH
1769/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00001770std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1771 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00001772 // Open the PCH file.
1773 std::string ErrStr;
1774 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1775 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1776 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001777 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001778 return std::string();
1779 }
1780
1781 // Initialize the stream
1782 llvm::BitstreamReader StreamFile;
1783 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001784 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001785 (const unsigned char *)Buffer->getBufferEnd());
1786 Stream.init(StreamFile);
1787
1788 // Sniff for the signature.
1789 if (Stream.Read(8) != 'C' ||
1790 Stream.Read(8) != 'P' ||
1791 Stream.Read(8) != 'C' ||
1792 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001793 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001794 return std::string();
1795 }
1796
1797 RecordData Record;
1798 while (!Stream.AtEndOfStream()) {
1799 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001800
Douglas Gregor45fe0362009-05-12 01:31:05 +00001801 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1802 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001803
Douglas Gregor45fe0362009-05-12 01:31:05 +00001804 // We only know the PCH subblock ID.
1805 switch (BlockID) {
1806 case pch::PCH_BLOCK_ID:
1807 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001808 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001809 return std::string();
1810 }
1811 break;
Mike Stump11289f42009-09-09 15:08:12 +00001812
Douglas Gregor45fe0362009-05-12 01:31:05 +00001813 default:
1814 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001815 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001816 return std::string();
1817 }
1818 break;
1819 }
1820 continue;
1821 }
1822
1823 if (Code == llvm::bitc::END_BLOCK) {
1824 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001825 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001826 return std::string();
1827 }
1828 continue;
1829 }
1830
1831 if (Code == llvm::bitc::DEFINE_ABBREV) {
1832 Stream.ReadAbbrevRecord();
1833 continue;
1834 }
1835
1836 Record.clear();
1837 const char *BlobStart = 0;
1838 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001839 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00001840 == pch::ORIGINAL_FILE_NAME)
1841 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00001842 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00001843
1844 return std::string();
1845}
1846
Douglas Gregor55abb232009-04-10 20:39:37 +00001847/// \brief Parse the record that corresponds to a LangOptions data
1848/// structure.
1849///
1850/// This routine compares the language options used to generate the
1851/// PCH file against the language options set for the current
1852/// compilation. For each option, we classify differences between the
1853/// two compiler states as either "benign" or "important". Benign
1854/// differences don't matter, and we accept them without complaint
1855/// (and without modifying the language options). Differences between
1856/// the states for important options cause the PCH file to be
1857/// unusable, so we emit a warning and return true to indicate that
1858/// there was an error.
1859///
1860/// \returns true if the PCH file is unacceptable, false otherwise.
1861bool PCHReader::ParseLanguageOptions(
1862 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001863 if (Listener) {
1864 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00001865
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001866 #define PARSE_LANGOPT(Option) \
1867 LangOpts.Option = Record[Idx]; \
1868 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00001869
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001870 unsigned Idx = 0;
1871 PARSE_LANGOPT(Trigraphs);
1872 PARSE_LANGOPT(BCPLComment);
1873 PARSE_LANGOPT(DollarIdents);
1874 PARSE_LANGOPT(AsmPreprocessor);
1875 PARSE_LANGOPT(GNUMode);
1876 PARSE_LANGOPT(ImplicitInt);
1877 PARSE_LANGOPT(Digraphs);
1878 PARSE_LANGOPT(HexFloats);
1879 PARSE_LANGOPT(C99);
1880 PARSE_LANGOPT(Microsoft);
1881 PARSE_LANGOPT(CPlusPlus);
1882 PARSE_LANGOPT(CPlusPlus0x);
1883 PARSE_LANGOPT(CXXOperatorNames);
1884 PARSE_LANGOPT(ObjC1);
1885 PARSE_LANGOPT(ObjC2);
1886 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00001887 PARSE_LANGOPT(ObjCNonFragileABI2);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001888 PARSE_LANGOPT(PascalStrings);
1889 PARSE_LANGOPT(WritableStrings);
1890 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00001891 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001892 PARSE_LANGOPT(Exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +00001893 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001894 PARSE_LANGOPT(NeXTRuntime);
1895 PARSE_LANGOPT(Freestanding);
1896 PARSE_LANGOPT(NoBuiltin);
1897 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00001898 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001899 PARSE_LANGOPT(Blocks);
1900 PARSE_LANGOPT(EmitAllDecls);
1901 PARSE_LANGOPT(MathErrno);
1902 PARSE_LANGOPT(OverflowChecking);
1903 PARSE_LANGOPT(HeinousExtensions);
1904 PARSE_LANGOPT(Optimize);
1905 PARSE_LANGOPT(OptimizeSize);
1906 PARSE_LANGOPT(Static);
1907 PARSE_LANGOPT(PICLevel);
1908 PARSE_LANGOPT(GNUInline);
1909 PARSE_LANGOPT(NoInline);
1910 PARSE_LANGOPT(AccessControl);
1911 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00001912 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001913 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1914 ++Idx;
1915 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1916 ++Idx;
Daniel Dunbar143021e2009-09-21 04:16:19 +00001917 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1918 Record[Idx]);
1919 ++Idx;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001920 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00001921 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00001922 PARSE_LANGOPT(CatchUndefined);
1923 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001924 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00001925
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001926 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00001927 }
Douglas Gregor55abb232009-04-10 20:39:37 +00001928
1929 return false;
1930}
1931
Douglas Gregoraae92242010-03-19 21:51:54 +00001932void PCHReader::ReadPreprocessedEntities() {
1933 ReadDefinedMacros();
1934}
1935
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001936/// \brief Read and return the type at the given offset.
1937///
1938/// This routine actually reads the record corresponding to the type
1939/// at the given offset in the bitstream. It is a helper routine for
1940/// GetType, which deals with reading type IDs.
1941QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001942 // Keep track of where we are in the stream, then jump back there
1943 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001944 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001945
Douglas Gregor1342e842009-07-06 18:54:52 +00001946 // Note that we are loading a type record.
1947 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00001948
Douglas Gregor12bfa382009-10-17 00:13:19 +00001949 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001950 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00001951 unsigned Code = DeclsCursor.ReadCode();
1952 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00001953 case pch::TYPE_EXT_QUAL: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001954 if (Record.size() != 2) {
1955 Error("Incorrect encoding of extended qualifier type");
1956 return QualType();
1957 }
Douglas Gregor455b8f42009-04-15 22:00:08 +00001958 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00001959 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1960 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00001961 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001962
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001963 case pch::TYPE_COMPLEX: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001964 if (Record.size() != 1) {
1965 Error("Incorrect encoding of complex type");
1966 return QualType();
1967 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001968 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001969 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001970 }
1971
1972 case pch::TYPE_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001973 if (Record.size() != 1) {
1974 Error("Incorrect encoding of pointer type");
1975 return QualType();
1976 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001977 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001978 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001979 }
1980
1981 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001982 if (Record.size() != 1) {
1983 Error("Incorrect encoding of block pointer type");
1984 return QualType();
1985 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001986 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001987 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001988 }
1989
1990 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001991 if (Record.size() != 1) {
1992 Error("Incorrect encoding of lvalue reference type");
1993 return QualType();
1994 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001995 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001996 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001997 }
1998
1999 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002000 if (Record.size() != 1) {
2001 Error("Incorrect encoding of rvalue reference type");
2002 return QualType();
2003 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002004 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002005 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002006 }
2007
2008 case pch::TYPE_MEMBER_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002009 if (Record.size() != 1) {
2010 Error("Incorrect encoding of member pointer type");
2011 return QualType();
2012 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002013 QualType PointeeType = GetType(Record[0]);
2014 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002015 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002016 }
2017
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002018 case pch::TYPE_CONSTANT_ARRAY: {
2019 QualType ElementType = GetType(Record[0]);
2020 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2021 unsigned IndexTypeQuals = Record[2];
2022 unsigned Idx = 3;
2023 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00002024 return Context->getConstantArrayType(ElementType, Size,
2025 ASM, IndexTypeQuals);
2026 }
2027
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002028 case pch::TYPE_INCOMPLETE_ARRAY: {
2029 QualType ElementType = GetType(Record[0]);
2030 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2031 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00002032 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002033 }
2034
2035 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002036 QualType ElementType = GetType(Record[0]);
2037 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2038 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00002039 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2040 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002041 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00002042 ASM, IndexTypeQuals,
2043 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002044 }
2045
2046 case pch::TYPE_VECTOR: {
John Thompson22334602010-02-05 00:12:22 +00002047 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002048 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002049 return QualType();
2050 }
2051
2052 QualType ElementType = GetType(Record[0]);
2053 unsigned NumElements = Record[1];
John Thompson22334602010-02-05 00:12:22 +00002054 bool AltiVec = Record[2];
2055 bool Pixel = Record[3];
2056 return Context->getVectorType(ElementType, NumElements, AltiVec, Pixel);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002057 }
2058
2059 case pch::TYPE_EXT_VECTOR: {
John Thompson22334602010-02-05 00:12:22 +00002060 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002061 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002062 return QualType();
2063 }
2064
2065 QualType ElementType = GetType(Record[0]);
2066 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00002067 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002068 }
2069
2070 case pch::TYPE_FUNCTION_NO_PROTO: {
Douglas Gregor8c940862010-01-18 17:14:39 +00002071 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002072 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002073 return QualType();
2074 }
2075 QualType ResultType = GetType(Record[0]);
Douglas Gregor8c940862010-01-18 17:14:39 +00002076 return Context->getFunctionNoProtoType(ResultType, Record[1],
2077 (CallingConv)Record[2]);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002078 }
2079
2080 case pch::TYPE_FUNCTION_PROTO: {
2081 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00002082 bool NoReturn = Record[1];
Douglas Gregor8c940862010-01-18 17:14:39 +00002083 CallingConv CallConv = (CallingConv)Record[2];
2084 unsigned Idx = 3;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002085 unsigned NumParams = Record[Idx++];
2086 llvm::SmallVector<QualType, 16> ParamTypes;
2087 for (unsigned I = 0; I != NumParams; ++I)
2088 ParamTypes.push_back(GetType(Record[Idx++]));
2089 bool isVariadic = Record[Idx++];
2090 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002091 bool hasExceptionSpec = Record[Idx++];
2092 bool hasAnyExceptionSpec = Record[Idx++];
2093 unsigned NumExceptions = Record[Idx++];
2094 llvm::SmallVector<QualType, 2> Exceptions;
2095 for (unsigned I = 0; I != NumExceptions; ++I)
2096 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00002097 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002098 isVariadic, Quals, hasExceptionSpec,
2099 hasAnyExceptionSpec, NumExceptions,
Douglas Gregor8c940862010-01-18 17:14:39 +00002100 Exceptions.data(), NoReturn, CallConv);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002101 }
2102
John McCallb96ec562009-12-04 22:46:56 +00002103 case pch::TYPE_UNRESOLVED_USING:
2104 return Context->getTypeDeclType(
2105 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2106
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002107 case pch::TYPE_TYPEDEF:
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002108 if (Record.size() != 1) {
2109 Error("incorrect encoding of typedef type");
2110 return QualType();
2111 }
Chris Lattner8575daa2009-04-27 21:45:14 +00002112 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002113
2114 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner8575daa2009-04-27 21:45:14 +00002115 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002116
2117 case pch::TYPE_TYPEOF: {
2118 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002119 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002120 return QualType();
2121 }
2122 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002123 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002124 }
Mike Stump11289f42009-09-09 15:08:12 +00002125
Anders Carlsson81df7b82009-06-24 19:06:50 +00002126 case pch::TYPE_DECLTYPE:
2127 return Context->getDecltypeType(ReadTypeExpr());
2128
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002129 case pch::TYPE_RECORD:
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002130 if (Record.size() != 1) {
2131 Error("incorrect encoding of record type");
2132 return QualType();
2133 }
Chris Lattner8575daa2009-04-27 21:45:14 +00002134 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002135
Douglas Gregor1daeb692009-04-13 18:14:40 +00002136 case pch::TYPE_ENUM:
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002137 if (Record.size() != 1) {
2138 Error("incorrect encoding of enum type");
2139 return QualType();
2140 }
Chris Lattner8575daa2009-04-27 21:45:14 +00002141 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor1daeb692009-04-13 18:14:40 +00002142
John McCallfcc33b02009-09-05 00:15:47 +00002143 case pch::TYPE_ELABORATED: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002144 if (Record.size() != 2) {
2145 Error("incorrect encoding of elaborated type");
2146 return QualType();
2147 }
John McCallfcc33b02009-09-05 00:15:47 +00002148 unsigned Tag = Record[1];
2149 return Context->getElaboratedType(GetType(Record[0]),
2150 (ElaboratedType::TagKind) Tag);
2151 }
2152
Steve Naroffc277ad12009-07-18 15:33:26 +00002153 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00002154 unsigned Idx = 0;
2155 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
2156 unsigned NumProtos = Record[Idx++];
2157 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2158 for (unsigned I = 0; I != NumProtos; ++I)
2159 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc277ad12009-07-18 15:33:26 +00002160 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00002161 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002162
Steve Narofffb4330f2009-06-17 22:40:22 +00002163 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00002164 unsigned Idx = 0;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002165 QualType OIT = GetType(Record[Idx++]);
Chris Lattner6e054af2009-04-22 06:40:03 +00002166 unsigned NumProtos = Record[Idx++];
2167 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2168 for (unsigned I = 0; I != NumProtos; ++I)
2169 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff7cae42b2009-07-10 23:34:53 +00002170 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattner6e054af2009-04-22 06:40:03 +00002171 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00002172
John McCallcebee162009-10-18 09:09:24 +00002173 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2174 unsigned Idx = 0;
2175 QualType Parm = GetType(Record[Idx++]);
2176 QualType Replacement = GetType(Record[Idx++]);
2177 return
2178 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2179 Replacement);
2180 }
John McCalle78aac42010-03-10 03:28:59 +00002181
2182 case pch::TYPE_INJECTED_CLASS_NAME: {
2183 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2184 QualType TST = GetType(Record[1]); // probably derivable
2185 return Context->getInjectedClassNameType(D, TST);
2186 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002187 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002188 // Suppress a GCC warning
2189 return QualType();
2190}
2191
John McCall8f115c62009-10-16 21:56:05 +00002192namespace {
2193
2194class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2195 PCHReader &Reader;
2196 const PCHReader::RecordData &Record;
2197 unsigned &Idx;
2198
2199public:
2200 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2201 unsigned &Idx)
2202 : Reader(Reader), Record(Record), Idx(Idx) { }
2203
John McCall17001972009-10-18 01:05:36 +00002204 // We want compile-time assurance that we've enumerated all of
2205 // these, so unfortunately we have to declare them first, then
2206 // define them out-of-line.
2207#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002208#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002209 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002210#include "clang/AST/TypeLocNodes.def"
2211
John McCall17001972009-10-18 01:05:36 +00002212 void VisitFunctionTypeLoc(FunctionTypeLoc);
2213 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002214};
2215
2216}
2217
John McCall17001972009-10-18 01:05:36 +00002218void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002219 // nothing to do
2220}
John McCall17001972009-10-18 01:05:36 +00002221void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +00002222 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2223 if (TL.needsExtraLocalData()) {
2224 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2225 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2226 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2227 TL.setModeAttr(Record[Idx++]);
2228 }
John McCall8f115c62009-10-16 21:56:05 +00002229}
John McCall17001972009-10-18 01:05:36 +00002230void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2231 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002232}
John McCall17001972009-10-18 01:05:36 +00002233void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2234 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002235}
John McCall17001972009-10-18 01:05:36 +00002236void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2237 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002238}
John McCall17001972009-10-18 01:05:36 +00002239void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2240 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002241}
John McCall17001972009-10-18 01:05:36 +00002242void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2243 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002244}
John McCall17001972009-10-18 01:05:36 +00002245void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2246 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002247}
John McCall17001972009-10-18 01:05:36 +00002248void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2249 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2250 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002251 if (Record[Idx++])
John McCall17001972009-10-18 01:05:36 +00002252 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor12bfa382009-10-17 00:13:19 +00002253 else
John McCall17001972009-10-18 01:05:36 +00002254 TL.setSizeExpr(0);
2255}
2256void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2257 VisitArrayTypeLoc(TL);
2258}
2259void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2260 VisitArrayTypeLoc(TL);
2261}
2262void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2263 VisitArrayTypeLoc(TL);
2264}
2265void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2266 DependentSizedArrayTypeLoc TL) {
2267 VisitArrayTypeLoc(TL);
2268}
2269void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2270 DependentSizedExtVectorTypeLoc TL) {
2271 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2272}
2273void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2274 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2275}
2276void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2277 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2278}
2279void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2280 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2281 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2282 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002283 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002284 }
2285}
2286void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2287 VisitFunctionTypeLoc(TL);
2288}
2289void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2290 VisitFunctionTypeLoc(TL);
2291}
John McCallb96ec562009-12-04 22:46:56 +00002292void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2293 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2294}
John McCall17001972009-10-18 01:05:36 +00002295void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2296 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2297}
2298void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002299 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2300 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2301 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002302}
2303void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002304 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2305 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2306 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2307 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002308}
2309void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2310 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2311}
2312void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2313 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2314}
2315void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2316 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2317}
2318void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2319 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2320}
2321void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2322 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2323}
John McCallcebee162009-10-18 09:09:24 +00002324void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2325 SubstTemplateTypeParmTypeLoc TL) {
2326 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2327}
John McCall17001972009-10-18 01:05:36 +00002328void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2329 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002330 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2331 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2332 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2333 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2334 TL.setArgLocInfo(i,
2335 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2336 Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002337}
2338void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2339 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2340}
John McCalle78aac42010-03-10 03:28:59 +00002341void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2342 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2343}
John McCall17001972009-10-18 01:05:36 +00002344void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2345 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2346}
2347void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2348 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002349 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2350 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2351 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2352 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002353}
John McCallfc93cf92009-10-22 22:37:11 +00002354void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2355 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2356 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2357 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2358 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2359 TL.setHasProtocolsAsWritten(Record[Idx++]);
2360 if (TL.hasProtocolsAsWritten())
2361 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2362 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2363}
John McCall8f115c62009-10-16 21:56:05 +00002364
John McCallbcd03502009-12-07 02:54:59 +00002365TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002366 unsigned &Idx) {
2367 QualType InfoTy = GetType(Record[Idx++]);
2368 if (InfoTy.isNull())
2369 return 0;
2370
John McCallbcd03502009-12-07 02:54:59 +00002371 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCall8f115c62009-10-16 21:56:05 +00002372 TypeLocReader TLR(*this, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002373 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002374 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002375 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002376}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002377
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002378QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002379 unsigned FastQuals = ID & Qualifiers::FastMask;
2380 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002381
2382 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2383 QualType T;
2384 switch ((pch::PredefinedTypeIDs)Index) {
2385 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002386 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2387 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002388
2389 case pch::PREDEF_TYPE_CHAR_U_ID:
2390 case pch::PREDEF_TYPE_CHAR_S_ID:
2391 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002392 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002393 break;
2394
Chris Lattner8575daa2009-04-27 21:45:14 +00002395 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2396 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2397 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2398 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2399 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002400 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002401 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2402 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2403 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2404 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2405 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2406 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002407 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002408 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2409 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2410 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2411 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2412 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002413 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002414 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2415 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002416 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2417 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002418 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002419 }
2420
2421 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002422 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002423 }
2424
2425 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002426 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall8ccfcb52009-09-24 19:53:00 +00002427 if (TypesLoaded[Index].isNull())
2428 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump11289f42009-09-09 15:08:12 +00002429
John McCall8ccfcb52009-09-24 19:53:00 +00002430 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002431}
2432
John McCall0ad16662009-10-29 08:12:44 +00002433TemplateArgumentLocInfo
2434PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2435 const RecordData &Record,
2436 unsigned &Index) {
2437 switch (Kind) {
2438 case TemplateArgument::Expression:
2439 return ReadDeclExpr();
2440 case TemplateArgument::Type:
John McCallbcd03502009-12-07 02:54:59 +00002441 return GetTypeSourceInfo(Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002442 case TemplateArgument::Template: {
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00002443 SourceLocation
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002444 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2445 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2446 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2447 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2448 TemplateNameLoc);
2449 }
John McCall0ad16662009-10-29 08:12:44 +00002450 case TemplateArgument::Null:
2451 case TemplateArgument::Integral:
2452 case TemplateArgument::Declaration:
2453 case TemplateArgument::Pack:
2454 return TemplateArgumentLocInfo();
2455 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002456 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002457 return TemplateArgumentLocInfo();
2458}
2459
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002460Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002461 if (ID == 0)
2462 return 0;
2463
Douglas Gregor745ed142009-04-25 18:35:21 +00002464 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002465 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002466 return 0;
2467 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002468
Douglas Gregor745ed142009-04-25 18:35:21 +00002469 unsigned Index = ID - 1;
2470 if (!DeclsLoaded[Index])
2471 ReadDeclRecord(DeclOffsets[Index], Index);
2472
2473 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002474}
2475
Chris Lattner9c28af02009-04-27 05:46:25 +00002476/// \brief Resolve the offset of a statement into a statement.
2477///
2478/// This operation will read a new statement from the external
2479/// source each time it is called, and is meant to be used via a
2480/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2481Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002482 // Since we know tha this statement is part of a decl, make sure to use the
2483 // decl cursor to read it.
2484 DeclsCursor.JumpToBit(Offset);
2485 return ReadStmt(DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002486}
2487
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002488bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002489 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002490 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002491 "DeclContext has no lexical decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002492
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002493 uint64_t Offset = DeclContextOffsets[DC].first;
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002494 if (Offset == 0) {
2495 Error("DeclContext has no lexical decls in storage");
2496 return true;
2497 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002498
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002499 // Keep track of where we are in the stream, then jump back there
2500 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002501 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002502
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002503 // Load the record containing all of the declarations lexically in
2504 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002505 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002506 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002507 unsigned Code = DeclsCursor.ReadCode();
2508 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002509 if (RecCode != pch::DECL_CONTEXT_LEXICAL) {
2510 Error("Expected lexical block");
2511 return true;
2512 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002513
2514 // Load all of the declaration IDs
2515 Decls.clear();
2516 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002517 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002518 return false;
2519}
2520
2521bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner72405d62009-04-27 07:35:40 +00002522 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002523 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002524 "DeclContext has no visible decls in storage");
2525 uint64_t Offset = DeclContextOffsets[DC].second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002526 if (Offset == 0) {
2527 Error("DeclContext has no visible decls in storage");
2528 return true;
2529 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002530
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002531 // Keep track of where we are in the stream, then jump back there
2532 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002533 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002534
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002535 // Load the record containing all of the declarations visible in
2536 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002537 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002538 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002539 unsigned Code = DeclsCursor.ReadCode();
2540 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002541 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2542 Error("Expected visible block");
2543 return true;
2544 }
2545
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002546 if (Record.size() == 0)
Mike Stump11289f42009-09-09 15:08:12 +00002547 return false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002548
2549 Decls.clear();
2550
2551 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002552 while (Idx < Record.size()) {
2553 Decls.push_back(VisibleDeclaration());
2554 Decls.back().Name = ReadDeclarationName(Record, Idx);
2555
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002556 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002557 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002558 LoadedDecls.reserve(Size);
2559 for (unsigned I = 0; I < Size; ++I)
2560 LoadedDecls.push_back(Record[Idx++]);
2561 }
2562
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002563 ++NumVisibleDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002564 return false;
2565}
2566
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002567void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002568 this->Consumer = Consumer;
2569
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002570 if (!Consumer)
2571 return;
2572
2573 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002574 // Force deserialization of this decl, which will cause it to be passed to
2575 // the consumer (or queued).
2576 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002577 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002578
2579 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2580 DeclGroupRef DG(InterestingDecls[I]);
2581 Consumer->HandleTopLevelDecl(DG);
2582 }
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002583}
2584
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002585void PCHReader::PrintStats() {
2586 std::fprintf(stderr, "*** PCH Statistics:\n");
2587
Mike Stump11289f42009-09-09 15:08:12 +00002588 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002589 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00002590 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00002591 unsigned NumDeclsLoaded
2592 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2593 (Decl *)0);
2594 unsigned NumIdentifiersLoaded
2595 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2596 IdentifiersLoaded.end(),
2597 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002598 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002599 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2600 SelectorsLoaded.end(),
2601 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002602
Douglas Gregorc5046832009-04-27 18:38:38 +00002603 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2604 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002605 if (TotalNumSLocEntries)
2606 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2607 NumSLocEntriesRead, TotalNumSLocEntries,
2608 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002609 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002610 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002611 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2612 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2613 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002614 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002615 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2616 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002617 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002618 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002619 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2620 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002621 if (TotalNumSelectors)
2622 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2623 NumSelectorsLoaded, TotalNumSelectors,
2624 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2625 if (TotalNumStatements)
2626 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2627 NumStatementsRead, TotalNumStatements,
2628 ((float)NumStatementsRead/TotalNumStatements * 100));
2629 if (TotalNumMacros)
2630 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2631 NumMacrosRead, TotalNumMacros,
2632 ((float)NumMacrosRead/TotalNumMacros * 100));
2633 if (TotalLexicalDeclContexts)
2634 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2635 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2636 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2637 * 100));
2638 if (TotalVisibleDeclContexts)
2639 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2640 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2641 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2642 * 100));
2643 if (TotalSelectorsInMethodPool) {
2644 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2645 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2646 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2647 * 100));
2648 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2649 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002650 std::fprintf(stderr, "\n");
2651}
2652
Douglas Gregora868bbd2009-04-21 22:25:48 +00002653void PCHReader::InitializeSema(Sema &S) {
2654 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002655 S.ExternalSource = this;
2656
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002657 // Makes sure any declarations that were deserialized "too early"
2658 // still get added to the identifier's declaration chains.
2659 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2660 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2661 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002662 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002663 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002664
2665 // If there were any tentative definitions, deserialize them and add
Sebastian Redl35351a92010-01-31 22:27:38 +00002666 // them to Sema's list of tentative definitions.
Douglas Gregord4df8652009-04-22 22:02:47 +00002667 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2668 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redl35351a92010-01-31 22:27:38 +00002669 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregord4df8652009-04-22 22:02:47 +00002670 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00002671
Tanya Lattner90073802010-02-12 00:07:30 +00002672 // If there were any unused static functions, deserialize them and add to
2673 // Sema's list of unused static functions.
2674 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
2675 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
2676 SemaObj->UnusedStaticFuncs.push_back(FD);
2677 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002678
2679 // If there were any locally-scoped external declarations,
2680 // deserialize them and add them to Sema's table of locally-scoped
2681 // external declarations.
2682 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2683 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2684 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2685 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002686
2687 // If there were any ext_vector type declarations, deserialize them
2688 // and add them to Sema's vector of such declarations.
2689 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2690 SemaObj->ExtVectorDecls.push_back(
2691 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00002692}
2693
2694IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2695 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00002696 PCHIdentifierLookupTable *IdTable
Douglas Gregora868bbd2009-04-21 22:25:48 +00002697 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2698 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2699 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2700 if (Pos == IdTable->end())
2701 return 0;
2702
2703 // Dereferencing the iterator has the effect of building the
2704 // IdentifierInfo node and populating it with the various
2705 // declarations it needs.
2706 return *Pos;
2707}
2708
Mike Stump11289f42009-09-09 15:08:12 +00002709std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00002710PCHReader::ReadMethodPool(Selector Sel) {
2711 if (!MethodPoolLookupTable)
2712 return std::pair<ObjCMethodList, ObjCMethodList>();
2713
2714 // Try to find this selector within our on-disk hash table.
2715 PCHMethodPoolLookupTable *PoolTable
2716 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2717 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00002718 if (Pos == PoolTable->end()) {
2719 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002720 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00002721 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00002722
Douglas Gregor95c13f52009-04-25 17:48:32 +00002723 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002724 return *Pos;
2725}
2726
Douglas Gregor0e149972009-04-25 19:10:14 +00002727void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00002728 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002729 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00002730 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00002731}
2732
Douglas Gregor1342e842009-07-06 18:54:52 +00002733/// \brief Set the globally-visible declarations associated with the given
2734/// identifier.
2735///
2736/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00002737/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00002738/// them.
2739///
2740/// \param II an IdentifierInfo that refers to one or more globally-visible
2741/// declarations.
2742///
2743/// \param DeclIDs the set of declaration IDs with the name @p II that are
2744/// visible at global scope.
2745///
2746/// \param Nonrecursive should be true to indicate that the caller knows that
2747/// this call is non-recursive, and therefore the globally-visible declarations
2748/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00002749void
2750PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00002751 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2752 bool Nonrecursive) {
2753 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2754 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2755 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2756 PII.II = II;
2757 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2758 PII.DeclIDs.push_back(DeclIDs[I]);
2759 return;
2760 }
Mike Stump11289f42009-09-09 15:08:12 +00002761
Douglas Gregor1342e842009-07-06 18:54:52 +00002762 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2763 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2764 if (SemaObj) {
2765 // Introduce this declaration into the translation-unit scope
2766 // and add it to the declaration chain for this identifier, so
2767 // that (unqualified) name lookup will find it.
2768 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2769 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2770 } else {
2771 // Queue this declaration so that it will be added to the
2772 // translation unit scope and identifier's declaration chain
2773 // once a Sema object is known.
2774 PreloadedDecls.push_back(D);
2775 }
2776 }
2777}
2778
Chris Lattnerc523d8e2009-04-11 21:15:38 +00002779IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002780 if (ID == 0)
2781 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002782
Douglas Gregor0e149972009-04-25 19:10:14 +00002783 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002784 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002785 return 0;
2786 }
Mike Stump11289f42009-09-09 15:08:12 +00002787
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002788 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00002789 if (!IdentifiersLoaded[ID - 1]) {
2790 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor95272492009-04-25 21:21:38 +00002791 const char *Str = IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00002792
Douglas Gregorab4df582009-04-28 20:01:51 +00002793 // All of the strings in the PCH file are preceded by a 16-bit
2794 // length. Extract that 16-bit length to avoid having to execute
2795 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00002796 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2797 // unsigned integers. This is important to avoid integer overflow when
2798 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00002799 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00002800 unsigned StrLen = (((unsigned) StrLenPtr[0])
2801 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00002802 IdentifiersLoaded[ID - 1]
Kovarththanan Rajaratnama3b09592010-03-12 10:32:27 +00002803 = &PP->getIdentifierTable().get(Str, StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002804 }
Mike Stump11289f42009-09-09 15:08:12 +00002805
Douglas Gregor0e149972009-04-25 19:10:14 +00002806 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002807}
2808
Douglas Gregor258ae542009-04-27 06:38:32 +00002809void PCHReader::ReadSLocEntry(unsigned ID) {
2810 ReadSLocEntryRecord(ID);
2811}
2812
Steve Naroff2ddea052009-04-23 10:39:46 +00002813Selector PCHReader::DecodeSelector(unsigned ID) {
2814 if (ID == 0)
2815 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00002816
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002817 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00002818 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002819
2820 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002821 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00002822 return Selector();
2823 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00002824
2825 unsigned Index = ID - 1;
2826 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2827 // Load this selector from the selector table.
2828 // FIXME: endianness portability issues with SelectorOffsets table
2829 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002830 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00002831 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2832 }
2833
2834 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00002835}
2836
Mike Stump11289f42009-09-09 15:08:12 +00002837DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002838PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2839 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2840 switch (Kind) {
2841 case DeclarationName::Identifier:
2842 return DeclarationName(GetIdentifierInfo(Record, Idx));
2843
2844 case DeclarationName::ObjCZeroArgSelector:
2845 case DeclarationName::ObjCOneArgSelector:
2846 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00002847 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002848
2849 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002850 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002851 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002852
2853 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002854 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002855 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002856
2857 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002858 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002859 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002860
2861 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002862 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002863 (OverloadedOperatorKind)Record[Idx++]);
2864
Alexis Hunt3d221f22009-11-29 07:34:05 +00002865 case DeclarationName::CXXLiteralOperatorName:
2866 return Context->DeclarationNames.getCXXLiteralOperatorName(
2867 GetIdentifierInfo(Record, Idx));
2868
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002869 case DeclarationName::CXXUsingDirective:
2870 return DeclarationName::getUsingDirectiveName();
2871 }
2872
2873 // Required to silence GCC warning
2874 return DeclarationName();
2875}
Douglas Gregor55abb232009-04-10 20:39:37 +00002876
Douglas Gregor1daeb692009-04-13 18:14:40 +00002877/// \brief Read an integral value
2878llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2879 unsigned BitWidth = Record[Idx++];
2880 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2881 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2882 Idx += NumWords;
2883 return Result;
2884}
2885
2886/// \brief Read a signed integral value
2887llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2888 bool isUnsigned = Record[Idx++];
2889 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2890}
2891
Douglas Gregore0a3a512009-04-14 21:55:33 +00002892/// \brief Read a floating-point value
2893llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00002894 return llvm::APFloat(ReadAPInt(Record, Idx));
2895}
2896
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002897// \brief Read a string
2898std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2899 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00002900 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002901 Idx += Len;
2902 return Result;
2903}
2904
Douglas Gregor55abb232009-04-10 20:39:37 +00002905DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00002906 return Diag(SourceLocation(), DiagID);
2907}
2908
2909DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002910 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00002911}
Douglas Gregora9af1d12009-04-17 00:04:06 +00002912
Douglas Gregora868bbd2009-04-21 22:25:48 +00002913/// \brief Retrieve the identifier table associated with the
2914/// preprocessor.
2915IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002916 assert(PP && "Forgot to set Preprocessor ?");
2917 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00002918}
2919
Douglas Gregora9af1d12009-04-17 00:04:06 +00002920/// \brief Record that the given ID maps to the given switch-case
2921/// statement.
2922void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2923 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2924 SwitchCaseStmts[ID] = SC;
2925}
2926
2927/// \brief Retrieve the switch-case statement with the given ID.
2928SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2929 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2930 return SwitchCaseStmts[ID];
2931}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002932
2933/// \brief Record that the given label statement has been
2934/// deserialized and has the given ID.
2935void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00002936 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002937 "Deserialized label twice");
2938 LabelStmts[ID] = S;
2939
2940 // If we've already seen any goto statements that point to this
2941 // label, resolve them now.
2942 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2943 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2944 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2945 Goto->second->setLabel(S);
2946 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00002947
2948 // If we've already seen any address-label statements that point to
2949 // this label, resolve them now.
2950 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00002951 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00002952 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00002953 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00002954 AddrLabel != AddrLabels.second; ++AddrLabel)
2955 AddrLabel->second->setLabel(S);
2956 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002957}
2958
2959/// \brief Set the label of the given statement to the label
2960/// identified by ID.
2961///
2962/// Depending on the order in which the label and other statements
2963/// referencing that label occur, this operation may complete
2964/// immediately (updating the statement) or it may queue the
2965/// statement to be back-patched later.
2966void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2967 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2968 if (Label != LabelStmts.end()) {
2969 // We've already seen this label, so set the label of the goto and
2970 // we're done.
2971 S->setLabel(Label->second);
2972 } else {
2973 // We haven't seen this label yet, so add this goto to the set of
2974 // unresolved goto statements.
2975 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2976 }
2977}
Douglas Gregor779d8652009-04-17 18:58:21 +00002978
2979/// \brief Set the label of the given expression to the label
2980/// identified by ID.
2981///
2982/// Depending on the order in which the label and other statements
2983/// referencing that label occur, this operation may complete
2984/// immediately (updating the statement) or it may queue the
2985/// statement to be back-patched later.
2986void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2987 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2988 if (Label != LabelStmts.end()) {
2989 // We've already seen this label, so set the label of the
2990 // label-address expression and we're done.
2991 S->setLabel(Label->second);
2992 } else {
2993 // We haven't seen this label yet, so add this label-address
2994 // expression to the set of unresolved label-address expressions.
2995 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2996 }
2997}
Douglas Gregor1342e842009-07-06 18:54:52 +00002998
2999
Mike Stump11289f42009-09-09 15:08:12 +00003000PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00003001 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
3002 Reader.CurrentlyLoadingTypeOrDecl = this;
3003}
3004
3005PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
3006 if (!Parent) {
3007 // If any identifiers with corresponding top-level declarations have
3008 // been loaded, load those declarations now.
3009 while (!Reader.PendingIdentifierInfos.empty()) {
3010 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
3011 Reader.PendingIdentifierInfos.front().DeclIDs,
3012 true);
3013 Reader.PendingIdentifierInfos.pop_front();
3014 }
3015 }
3016
Mike Stump11289f42009-09-09 15:08:12 +00003017 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00003018}