blob: 16afabbb7e448cecc769b458d4453c6cc70b469d [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"
Sebastian Redl85b2a6a2010-07-14 23:45:08 +000016#include "clang/Frontend/PCHDeserializationListener.h"
Daniel Dunbar732ef8a2009-11-11 23:58:53 +000017#include "clang/Frontend/Utils.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000018#include "clang/Sema/Sema.h"
Douglas Gregor1a0d0b92009-04-14 00:24:19 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000021#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000023#include "clang/AST/TypeLocVisitor.h"
Chris Lattner34321bc2009-04-10 21:41:48 +000024#include "clang/Lex/MacroInfo.h"
Douglas Gregoraae92242010-03-19 21:51:54 +000025#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000026#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000027#include "clang/Lex/HeaderSearch.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000028#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000029#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000030#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000031#include "clang/Basic/FileManager.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000032#include "clang/Basic/TargetInfo.h"
Douglas Gregord54f3a12009-10-05 21:07:28 +000033#include "clang/Basic/Version.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000035#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000036#include "llvm/Support/MemoryBuffer.h"
John McCall0ad16662009-10-29 08:12:44 +000037#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +000038#include "llvm/System/Path.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000039#include <algorithm>
Douglas Gregorc379c072009-04-28 18:58:38 +000040#include <iterator>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000041#include <cstdio>
Douglas Gregorc5046832009-04-27 18:38:38 +000042#include <sys/stat.h>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000043using namespace clang;
44
45//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000046// PCH reader validator implementation
47//===----------------------------------------------------------------------===//
48
49PCHReaderListener::~PCHReaderListener() {}
50
51bool
52PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
53 const LangOptions &PPLangOpts = PP.getLangOptions();
54#define PARSE_LANGOPT_BENIGN(Option)
55#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
56 if (PPLangOpts.Option != LangOpts.Option) { \
57 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
58 return true; \
59 }
60
61 PARSE_LANGOPT_BENIGN(Trigraphs);
62 PARSE_LANGOPT_BENIGN(BCPLComment);
63 PARSE_LANGOPT_BENIGN(DollarIdents);
64 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
65 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
Chandler Carruthe03aa552010-04-17 20:17:31 +000066 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000067 PARSE_LANGOPT_BENIGN(ImplicitInt);
68 PARSE_LANGOPT_BENIGN(Digraphs);
69 PARSE_LANGOPT_BENIGN(HexFloats);
70 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
71 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
72 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
73 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
74 PARSE_LANGOPT_BENIGN(CXXOperatorName);
75 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
76 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
77 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
Fariborz Jahanian45878032010-02-09 19:31:38 +000078 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Fariborz Jahanian62c56022010-04-22 21:01:59 +000079 PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
80 diag::warn_pch_no_constant_cfstrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000081 PARSE_LANGOPT_BENIGN(PascalStrings);
82 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump11289f42009-09-09 15:08:12 +000083 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000084 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +000085 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000086 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +000087 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000088 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
89 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
90 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +000091 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000092 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000093 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000094 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
95 PARSE_LANGOPT_BENIGN(EmitAllDecls);
96 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
Chris Lattner51924e512010-06-26 21:25:03 +000097 PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
Mike Stump11289f42009-09-09 15:08:12 +000098 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000099 diag::warn_pch_heinous_extensions);
100 // FIXME: Most of the options below are benign if the macro wasn't
101 // used. Unfortunately, this means that a PCH compiled without
102 // optimization can't be used with optimization turned on, even
103 // though the only thing that changes is whether __OPTIMIZE__ was
104 // defined... but if __OPTIMIZE__ never showed up in the header, it
105 // doesn't matter. We could consider making this some special kind
106 // of check.
107 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
108 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
109 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
110 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
111 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
112 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
113 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
114 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsoned4e2952009-11-05 20:14:16 +0000115 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000116 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000117 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000118 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
119 return true;
120 }
121 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000122 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
123 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000124 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000125 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stumpd9546382009-12-12 01:27:46 +0000126 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000127 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +0000128 PARSE_LANGOPT_BENIGN(SpellChecking);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +0000129#undef PARSE_LANGOPT_IMPORTANT
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000130#undef PARSE_LANGOPT_BENIGN
131
132 return false;
133}
134
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000135bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
136 if (Triple == PP.getTargetInfo().getTriple().str())
137 return false;
138
139 Reader.Diag(diag::warn_pch_target_triple)
140 << Triple << PP.getTargetInfo().getTriple().str();
141 return true;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000142}
143
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000144struct EmptyStringRef {
Benjamin Kramer8d5609b2010-07-14 23:19:41 +0000145 bool operator ()(llvm::StringRef r) const { return r.empty(); }
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000146};
147struct EmptyBlock {
148 bool operator ()(const PCHPredefinesBlock &r) const { return r.Data.empty(); }
149};
150
151static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L,
152 PCHPredefinesBlocks R) {
153 // First, sum up the lengths.
154 unsigned LL = 0, RL = 0;
155 for (unsigned I = 0, N = L.size(); I != N; ++I) {
156 LL += L[I].size();
157 }
158 for (unsigned I = 0, N = R.size(); I != N; ++I) {
159 RL += R[I].Data.size();
160 }
161 if (LL != RL)
162 return false;
163 if (LL == 0 && RL == 0)
164 return true;
165
166 // Kick out empty parts, they confuse the algorithm below.
167 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
168 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
169
170 // Do it the hard way. At this point, both vectors must be non-empty.
171 llvm::StringRef LR = L[0], RR = R[0].Data;
172 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
Daniel Dunbar01ad0a72010-07-16 00:00:11 +0000173 (void) RN;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000174 for (;;) {
175 // Compare the current pieces.
176 if (LR.size() == RR.size()) {
177 // If they're the same length, it's pretty easy.
178 if (LR != RR)
179 return false;
180 // Both pieces are done, advance.
181 ++LI;
182 ++RI;
183 // If either string is done, they're both done, since they're the same
184 // length.
185 if (LI == LN) {
186 assert(RI == RN && "Strings not the same length after all?");
187 return true;
188 }
189 LR = L[LI];
190 RR = R[RI].Data;
191 } else if (LR.size() < RR.size()) {
192 // Right piece is longer.
193 if (!RR.startswith(LR))
194 return false;
195 ++LI;
196 assert(LI != LN && "Strings not the same length after all?");
197 RR = RR.substr(LR.size());
198 LR = L[LI];
199 } else {
200 // Left piece is longer.
201 if (!LR.startswith(RR))
202 return false;
203 ++RI;
204 assert(RI != RN && "Strings not the same length after all?");
205 LR = LR.substr(RR.size());
206 RR = R[RI].Data;
207 }
208 }
209}
210
211static std::pair<FileID, llvm::StringRef::size_type>
212FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
213 std::pair<FileID, llvm::StringRef::size_type> Res;
214 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
215 Res.second = Buffers[I].Data.find(MacroDef);
216 if (Res.second != llvm::StringRef::npos) {
217 Res.first = Buffers[I].BufferID;
218 break;
219 }
220 }
221 return Res;
222}
223
224bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000225 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000226 std::string &SuggestedPredefines) {
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000227 // We are in the context of an implicit include, so the predefines buffer will
228 // have a #include entry for the PCH file itself (as normalized by the
229 // preprocessor initialization). Find it and skip over it in the checking
230 // below.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000231 llvm::SmallString<256> PCHInclude;
232 PCHInclude += "#include \"";
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000233 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000234 PCHInclude += "\"\n";
235 std::pair<llvm::StringRef,llvm::StringRef> Split =
236 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
237 llvm::StringRef Left = Split.first, Right = Split.second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000238 if (Left == PP.getPredefines()) {
239 Error("Missing PCH include entry!");
240 return true;
241 }
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000242
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000243 // If the concatenation of all the PCH buffers is equal to the adjusted
244 // command line, we're done.
245 // We build a SmallVector of the command line here, because we'll eventually
246 // need to support an arbitrary amount of pieces anyway (when we have chained
247 // PCH reading).
248 llvm::SmallVector<llvm::StringRef, 2> CommandLine;
249 CommandLine.push_back(Left);
250 CommandLine.push_back(Right);
251 if (EqualConcatenations(CommandLine, Buffers))
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000252 return false;
253
254 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000255
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000256 // The predefines buffers are different. Determine what the differences are,
257 // and whether they require us to reject the PCH file.
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000258 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000259 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
260 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000261
262 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
263 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
264 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000265
Daniel Dunbar499baed2009-11-11 05:26:28 +0000266 // Sort both sets of predefined buffer lines, since we allow some extra
267 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000268 std::sort(CmdLineLines.begin(), CmdLineLines.end());
269 std::sort(PCHLines.begin(), PCHLines.end());
270
Daniel Dunbar499baed2009-11-11 05:26:28 +0000271 // Determine which predefines that were used to build the PCH file are missing
272 // from the command line.
273 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000274 std::set_difference(PCHLines.begin(), PCHLines.end(),
275 CmdLineLines.begin(), CmdLineLines.end(),
276 std::back_inserter(MissingPredefines));
277
278 bool MissingDefines = false;
279 bool ConflictingDefines = false;
280 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000281 llvm::StringRef Missing = MissingPredefines[I];
282 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000283 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
284 return true;
285 }
Mike Stump11289f42009-09-09 15:08:12 +0000286
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000287 // This is a macro definition. Determine the name of the macro we're
288 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000289 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000290 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000291 = Missing.find_first_of("( \n\r", StartOfMacroName);
292 assert(EndOfMacroName != std::string::npos &&
293 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000294 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000295
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000296 // Determine whether this macro was given a different definition on the
297 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000298 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000299 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000300 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000301 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
302 MacroDefStart);
303 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000304 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000305 // Different macro; we're done.
306 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000307 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000308 }
Mike Stump11289f42009-09-09 15:08:12 +0000309
310 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000311 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000312 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000313 (*ConflictPos)[MacroDefLen] != '(')
314 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000315
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000316 // We found a conflicting macro definition.
317 break;
318 }
Mike Stump11289f42009-09-09 15:08:12 +0000319
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000320 if (ConflictPos != CmdLineLines.end()) {
321 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
322 << MacroName;
323
324 // Show the definition of this macro within the PCH file.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000325 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
326 FindMacro(Buffers, Missing);
327 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
328 SourceLocation PCHMissingLoc =
329 SourceMgr.getLocForStartOfFile(MacroLoc.first)
330 .getFileLocWithOffset(MacroLoc.second);
Daniel Dunbar499baed2009-11-11 05:26:28 +0000331 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000332
333 ConflictingDefines = true;
334 continue;
335 }
Mike Stump11289f42009-09-09 15:08:12 +0000336
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000337 // If the macro doesn't conflict, then we'll just pick up the macro
338 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000339 if (ConflictingDefines)
340 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000341
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000342 if (!MissingDefines) {
343 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
344 MissingDefines = true;
345 }
346
347 // Show the definition of this macro within the PCH file.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000348 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
349 FindMacro(Buffers, Missing);
350 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
351 SourceLocation PCHMissingLoc =
352 SourceMgr.getLocForStartOfFile(MacroLoc.first)
353 .getFileLocWithOffset(MacroLoc.second);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000354 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
355 }
Mike Stump11289f42009-09-09 15:08:12 +0000356
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000357 if (ConflictingDefines)
358 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000360 // Determine what predefines were introduced based on command-line
361 // parameters that were not present when building the PCH
362 // file. Extra #defines are okay, so long as the identifiers being
363 // defined were not used within the precompiled header.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000364 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000365 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
366 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000367 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000368 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000369 llvm::StringRef &Extra = ExtraPredefines[I];
370 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000371 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
372 return true;
373 }
374
375 // This is an extra macro definition. Determine the name of the
376 // macro we're defining.
377 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000378 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000379 = Extra.find_first_of("( \n\r", StartOfMacroName);
380 assert(EndOfMacroName != std::string::npos &&
381 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000382 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000383
384 // Check whether this name was used somewhere in the PCH file. If
385 // so, defining it as a macro could change behavior, so we reject
386 // the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000387 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000388 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000389 return true;
390 }
391
392 // Add this definition to the suggested predefines buffer.
393 SuggestedPredefines += Extra;
394 SuggestedPredefines += '\n';
395 }
396
397 // If we get here, it's because the predefines buffer had compatible
398 // contents. Accept the PCH file.
399 return false;
400}
401
Douglas Gregor5712ebc2010-03-16 16:35:32 +0000402void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
403 unsigned ID) {
404 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
405 ++NumHeaderInfos;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000406}
407
408void PCHValidator::ReadCounter(unsigned Value) {
409 PP.setCounterValue(Value);
410}
411
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000412//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000413// PCH reader implementation
414//===----------------------------------------------------------------------===//
415
Mike Stump11289f42009-09-09 15:08:12 +0000416PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000417 const char *isysroot, bool DisableValidation)
Sebastian Redl85b2a6a2010-07-14 23:45:08 +0000418 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
419 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
420 Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
Sebastian Redlada023c2010-08-04 20:40:17 +0000421 Consumer(0), isysroot(isysroot), DisableValidation(DisableValidation),
422 NumStatHits(0), NumStatMisses(0), NumSLocEntriesRead(0),
423 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
Sebastian Redl6e1a2a02010-08-04 21:22:45 +0000424 NumMacrosRead(0), TotalNumMacros(0), NumSelectorsRead(0),
425 NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0),
426 TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0),
Sebastian Redlada023c2010-08-04 20:40:17 +0000427 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
428 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000429 RelocatablePCH = false;
430}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000431
432PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000433 Diagnostic &Diags, const char *isysroot,
434 bool DisableValidation)
Sebastian Redl85b2a6a2010-07-14 23:45:08 +0000435 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
Sebastian Redl34522812010-07-16 17:50:48 +0000436 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
Sebastian Redlada023c2010-08-04 20:40:17 +0000437 isysroot(isysroot), DisableValidation(DisableValidation), NumStatHits(0),
438 NumStatMisses(0), NumSLocEntriesRead(0), TotalNumSLocEntries(0),
439 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
Sebastian Redl6e1a2a02010-08-04 21:22:45 +0000440 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
441 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
Sebastian Redlada023c2010-08-04 20:40:17 +0000442 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
443 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
444 NumCurrentElementsDeserializing(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000445 RelocatablePCH = false;
446}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000447
Sebastian Redl34522812010-07-16 17:50:48 +0000448PCHReader::~PCHReader() {
449 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
450 delete Chain[e - i - 1];
451}
452
453PCHReader::PerFileData::PerFileData()
Sebastian Redl9e687992010-07-19 22:06:55 +0000454 : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
Sebastian Redlbd1b5be2010-07-19 22:28:42 +0000455 LocalNumDecls(0), DeclOffsets(0), LocalNumIdentifiers(0),
Sebastian Redlfa061442010-07-21 20:07:32 +0000456 IdentifierOffsets(0), IdentifierTableData(0), IdentifierLookupTable(0),
457 LocalNumMacroDefinitions(0), MacroDefinitionOffsets(0),
Sebastian Redlada023c2010-08-04 20:40:17 +0000458 NumPreallocatedPreprocessingEntities(0), SelectorLookupTable(0),
459 SelectorLookupTableData(0), SelectorOffsets(0), LocalNumSelectors(0)
Sebastian Redl34522812010-07-16 17:50:48 +0000460{}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000461
Sebastian Redl07a89a82010-07-30 00:29:29 +0000462void
463PCHReader::setDeserializationListener(PCHDeserializationListener *Listener) {
464 DeserializationListener = Listener;
465 if (DeserializationListener)
466 DeserializationListener->SetReader(this);
467}
468
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000469
Douglas Gregora868bbd2009-04-21 22:25:48 +0000470namespace {
Sebastian Redlada023c2010-08-04 20:40:17 +0000471class PCHSelectorLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000472 PCHReader &Reader;
473
474public:
Sebastian Redl834bb972010-08-04 17:20:04 +0000475 struct data_type {
476 pch::SelectorID ID;
477 ObjCMethodList Instance, Factory;
478 };
Douglas Gregorc78d3462009-04-24 21:10:55 +0000479
480 typedef Selector external_key_type;
481 typedef external_key_type internal_key_type;
482
Sebastian Redlada023c2010-08-04 20:40:17 +0000483 explicit PCHSelectorLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000484
Douglas Gregorc78d3462009-04-24 21:10:55 +0000485 static bool EqualKey(const internal_key_type& a,
486 const internal_key_type& b) {
487 return a == b;
488 }
Mike Stump11289f42009-09-09 15:08:12 +0000489
Douglas Gregorc78d3462009-04-24 21:10:55 +0000490 static unsigned ComputeHash(Selector Sel) {
491 unsigned N = Sel.getNumArgs();
492 if (N == 0)
493 ++N;
494 unsigned R = 5381;
495 for (unsigned I = 0; I != N; ++I)
496 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000497 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000498 return R;
499 }
Mike Stump11289f42009-09-09 15:08:12 +0000500
Douglas Gregorc78d3462009-04-24 21:10:55 +0000501 // This hopefully will just get inlined and removed by the optimizer.
502 static const internal_key_type&
503 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000504
Douglas Gregorc78d3462009-04-24 21:10:55 +0000505 static std::pair<unsigned, unsigned>
506 ReadKeyDataLength(const unsigned char*& d) {
507 using namespace clang::io;
508 unsigned KeyLen = ReadUnalignedLE16(d);
509 unsigned DataLen = ReadUnalignedLE16(d);
510 return std::make_pair(KeyLen, DataLen);
511 }
Mike Stump11289f42009-09-09 15:08:12 +0000512
Douglas Gregor95c13f52009-04-25 17:48:32 +0000513 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000514 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000515 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000516 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000517 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000518 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
519 if (N == 0)
520 return SelTable.getNullarySelector(FirstII);
521 else if (N == 1)
522 return SelTable.getUnarySelector(FirstII);
523
524 llvm::SmallVector<IdentifierInfo *, 16> Args;
525 Args.push_back(FirstII);
526 for (unsigned I = 1; I != N; ++I)
527 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
528
Douglas Gregor038c3382009-05-22 22:45:36 +0000529 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000530 }
Mike Stump11289f42009-09-09 15:08:12 +0000531
Douglas Gregorc78d3462009-04-24 21:10:55 +0000532 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
533 using namespace clang::io;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000534
535 data_type Result;
536
Sebastian Redl834bb972010-08-04 17:20:04 +0000537 Result.ID = ReadUnalignedLE32(d);
538 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
539 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
540
Douglas Gregorc78d3462009-04-24 21:10:55 +0000541 // Load instance methods
542 ObjCMethodList *Prev = 0;
543 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000544 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000545 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Sebastian Redl834bb972010-08-04 17:20:04 +0000546 if (!Result.Instance.Method) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000547 // This is the first method, which is the easy case.
Sebastian Redl834bb972010-08-04 17:20:04 +0000548 Result.Instance.Method = Method;
549 Prev = &Result.Instance;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000550 continue;
551 }
552
Ted Kremenekda4abf12010-02-11 00:53:01 +0000553 ObjCMethodList *Mem =
554 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
555 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000556 Prev = Prev->Next;
557 }
558
559 // Load factory methods
560 Prev = 0;
561 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000562 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000563 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Sebastian Redl834bb972010-08-04 17:20:04 +0000564 if (!Result.Factory.Method) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000565 // This is the first method, which is the easy case.
Sebastian Redl834bb972010-08-04 17:20:04 +0000566 Result.Factory.Method = Method;
567 Prev = &Result.Factory;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000568 continue;
569 }
570
Ted Kremenekda4abf12010-02-11 00:53:01 +0000571 ObjCMethodList *Mem =
572 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
573 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000574 Prev = Prev->Next;
575 }
576
577 return Result;
578 }
579};
Mike Stump11289f42009-09-09 15:08:12 +0000580
581} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000582
583/// \brief The on-disk hash table used for the global method pool.
Sebastian Redlada023c2010-08-04 20:40:17 +0000584typedef OnDiskChainedHashTable<PCHSelectorLookupTrait>
585 PCHSelectorLookupTable;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000586
587namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000588class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000589 PCHReader &Reader;
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000590 llvm::BitstreamCursor &Stream;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000591
592 // If we know the IdentifierInfo in advance, it is here and we will
593 // not build a new one. Used when deserializing information about an
594 // identifier that was constructed before the PCH file was read.
595 IdentifierInfo *KnownII;
596
597public:
598 typedef IdentifierInfo * data_type;
599
600 typedef const std::pair<const char*, unsigned> external_key_type;
601
602 typedef external_key_type internal_key_type;
603
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000604 PCHIdentifierLookupTrait(PCHReader &Reader, llvm::BitstreamCursor &Stream,
605 IdentifierInfo *II = 0)
606 : Reader(Reader), Stream(Stream), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000607
Douglas Gregora868bbd2009-04-21 22:25:48 +0000608 static bool EqualKey(const internal_key_type& a,
609 const internal_key_type& b) {
610 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
611 : false;
612 }
Mike Stump11289f42009-09-09 15:08:12 +0000613
Douglas Gregora868bbd2009-04-21 22:25:48 +0000614 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000615 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000616 }
Mike Stump11289f42009-09-09 15:08:12 +0000617
Douglas Gregora868bbd2009-04-21 22:25:48 +0000618 // This hopefully will just get inlined and removed by the optimizer.
619 static const internal_key_type&
620 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000621
Douglas Gregora868bbd2009-04-21 22:25:48 +0000622 static std::pair<unsigned, unsigned>
623 ReadKeyDataLength(const unsigned char*& d) {
624 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000625 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000626 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000627 return std::make_pair(KeyLen, DataLen);
628 }
Mike Stump11289f42009-09-09 15:08:12 +0000629
Douglas Gregora868bbd2009-04-21 22:25:48 +0000630 static std::pair<const char*, unsigned>
631 ReadKey(const unsigned char* d, unsigned n) {
632 assert(n >= 2 && d[n-1] == '\0');
633 return std::make_pair((const char*) d, n-1);
634 }
Mike Stump11289f42009-09-09 15:08:12 +0000635
636 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000637 const unsigned char* d,
638 unsigned DataLen) {
639 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000640 pch::IdentID ID = ReadUnalignedLE32(d);
641 bool IsInteresting = ID & 0x01;
642
643 // Wipe out the "is interesting" bit.
644 ID = ID >> 1;
645
646 if (!IsInteresting) {
Sebastian Redl98912122010-07-27 23:01:28 +0000647 // For uninteresting identifiers, just build the IdentifierInfo
Douglas Gregor1d583f22009-04-28 21:18:29 +0000648 // and associate it with the persistent ID.
649 IdentifierInfo *II = KnownII;
650 if (!II)
Sebastian Redl07a89a82010-07-30 00:29:29 +0000651 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregor1d583f22009-04-28 21:18:29 +0000652 Reader.SetIdentifierInfo(ID, II);
Sebastian Redl07a89a82010-07-30 00:29:29 +0000653 II->setIsFromPCH();
Douglas Gregor1d583f22009-04-28 21:18:29 +0000654 return II;
655 }
656
Douglas Gregorb9256522009-04-28 21:32:13 +0000657 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000658 bool CPlusPlusOperatorKeyword = Bits & 0x01;
659 Bits >>= 1;
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +0000660 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
661 Bits >>= 1;
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000662 bool Poisoned = Bits & 0x01;
663 Bits >>= 1;
664 bool ExtensionToken = Bits & 0x01;
665 Bits >>= 1;
666 bool hasMacroDefinition = Bits & 0x01;
667 Bits >>= 1;
668 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
669 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000670
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000671 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000672 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000673
674 // Build the IdentifierInfo itself and link the identifier ID with
675 // the new IdentifierInfo.
676 IdentifierInfo *II = KnownII;
677 if (!II)
Sebastian Redl07a89a82010-07-30 00:29:29 +0000678 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000679 Reader.SetIdentifierInfo(ID, II);
680
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000681 // Set or check the various bits in the IdentifierInfo structure.
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +0000682 // Token IDs are read-only.
683 if (HasRevertedTokenIDToIdentifier)
684 II->RevertTokenIDToIdentifier();
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000685 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000686 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000687 "Incorrect extension token flag");
688 (void)ExtensionToken;
689 II->setIsPoisoned(Poisoned);
690 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
691 "Incorrect C++ operator keyword flag");
692 (void)CPlusPlusOperatorKeyword;
693
Douglas Gregorc3366a52009-04-21 23:56:24 +0000694 // If this identifier is a macro, deserialize the macro
695 // definition.
696 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000697 uint32_t Offset = ReadUnalignedLE32(d);
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000698 Reader.ReadMacroRecord(Stream, Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000699 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000700 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000701
702 // Read all of the declarations visible at global scope with this
703 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000704 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000705 if (DataLen > 0) {
706 llvm::SmallVector<uint32_t, 4> DeclIDs;
707 for (; DataLen > 0; DataLen -= 4)
708 DeclIDs.push_back(ReadUnalignedLE32(d));
709 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000710 }
Mike Stump11289f42009-09-09 15:08:12 +0000711
Sebastian Redl07a89a82010-07-30 00:29:29 +0000712 II->setIsFromPCH();
Douglas Gregora868bbd2009-04-21 22:25:48 +0000713 return II;
714 }
715};
Mike Stump11289f42009-09-09 15:08:12 +0000716
717} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000718
719/// \brief The on-disk hash table used to contain information about
720/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000721typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000722 PCHIdentifierLookupTable;
723
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000724void PCHReader::Error(const char *Msg) {
725 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000726}
727
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000728/// \brief Check the contents of the concatenation of all predefines buffers in
729/// the PCH chain against the contents of the predefines buffer of the current
730/// compiler invocation.
Douglas Gregor92863e42009-04-10 23:10:45 +0000731///
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000732/// The contents should be the same. If not, then some command-line option
733/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregor92863e42009-04-10 23:10:45 +0000734///
735/// \returns true if there was a mismatch (in which case the PCH file
736/// should be ignored), or false otherwise.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000737bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000738 if (Listener)
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000739 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000740 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000741 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000742 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000743}
744
Douglas Gregorc5046832009-04-27 18:38:38 +0000745//===----------------------------------------------------------------------===//
746// Source Manager Deserialization
747//===----------------------------------------------------------------------===//
748
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000749/// \brief Read the line table in the source manager block.
750/// \returns true if ther was an error.
Sebastian Redlb293a452010-07-20 21:20:32 +0000751bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000752 unsigned Idx = 0;
753 LineTableInfo &LineTable = SourceMgr.getLineTable();
754
755 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000756 std::map<int, int> FileIDs;
757 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000758 // Extract the file name
759 unsigned FilenameLen = Record[Idx++];
760 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
761 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000762 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000763 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000764 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000765 }
766
767 // Parse the line entries
768 std::vector<LineEntry> Entries;
769 while (Idx < Record.size()) {
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000770 int FID = Record[Idx++];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000771
772 // Extract the line entries
773 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000774 assert(NumEntries && "Numentries is 00000");
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000775 Entries.clear();
776 Entries.reserve(NumEntries);
777 for (unsigned I = 0; I != NumEntries; ++I) {
778 unsigned FileOffset = Record[Idx++];
779 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000780 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump11289f42009-09-09 15:08:12 +0000781 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000782 = (SrcMgr::CharacteristicKind)Record[Idx++];
783 unsigned IncludeOffset = Record[Idx++];
784 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
785 FileKind, IncludeOffset));
786 }
787 LineTable.AddEntry(FID, Entries);
788 }
789
790 return false;
791}
792
Douglas Gregorc5046832009-04-27 18:38:38 +0000793namespace {
794
Benjamin Kramer16634c22009-11-28 10:07:24 +0000795class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000796public:
797 const bool hasStat;
798 const ino_t ino;
799 const dev_t dev;
800 const mode_t mode;
801 const time_t mtime;
802 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000803
Douglas Gregorc5046832009-04-27 18:38:38 +0000804 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000805 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
806
Douglas Gregorc5046832009-04-27 18:38:38 +0000807 PCHStatData()
808 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
809};
810
Benjamin Kramer16634c22009-11-28 10:07:24 +0000811class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000812 public:
813 typedef const char *external_key_type;
814 typedef const char *internal_key_type;
815
816 typedef PCHStatData data_type;
817
818 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000819 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000820 }
821
822 static internal_key_type GetInternalKey(const char *path) { return path; }
823
824 static bool EqualKey(internal_key_type a, internal_key_type b) {
825 return strcmp(a, b) == 0;
826 }
827
828 static std::pair<unsigned, unsigned>
829 ReadKeyDataLength(const unsigned char*& d) {
830 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
831 unsigned DataLen = (unsigned) *d++;
832 return std::make_pair(KeyLen + 1, DataLen);
833 }
834
835 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
836 return (const char *)d;
837 }
838
839 static data_type ReadData(const internal_key_type, const unsigned char *d,
840 unsigned /*DataLen*/) {
841 using namespace clang::io;
842
843 if (*d++ == 1)
844 return data_type();
845
846 ino_t ino = (ino_t) ReadUnalignedLE32(d);
847 dev_t dev = (dev_t) ReadUnalignedLE32(d);
848 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000849 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000850 off_t size = (off_t) ReadUnalignedLE64(d);
851 return data_type(ino, dev, mode, mtime, size);
852 }
853};
854
855/// \brief stat() cache for precompiled headers.
856///
857/// This cache is very similar to the stat cache used by pretokenized
858/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000859class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000860 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
861 CacheTy *Cache;
862
863 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000864public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000865 PCHStatCache(const unsigned char *Buckets,
866 const unsigned char *Base,
867 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000868 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000869 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
870 Cache = CacheTy::Create(Buckets, Base);
871 }
872
873 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000874
Douglas Gregorc5046832009-04-27 18:38:38 +0000875 int stat(const char *path, struct stat *buf) {
876 // Do the lookup for the file's data in the PCH file.
877 CacheTy::iterator I = Cache->find(path);
878
879 // If we don't get a hit in the PCH file just forward to 'stat'.
880 if (I == Cache->end()) {
881 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000882 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000883 }
Mike Stump11289f42009-09-09 15:08:12 +0000884
Douglas Gregorc5046832009-04-27 18:38:38 +0000885 ++NumStatHits;
886 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000887
Douglas Gregorc5046832009-04-27 18:38:38 +0000888 if (!Data.hasStat)
889 return 1;
890
891 buf->st_ino = Data.ino;
892 buf->st_dev = Data.dev;
893 buf->st_mtime = Data.mtime;
894 buf->st_mode = Data.mode;
895 buf->st_size = Data.size;
896 return 0;
897 }
898};
899} // end anonymous namespace
900
901
Sebastian Redl393f8b72010-07-19 20:52:06 +0000902/// \brief Read a source manager block
903PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000904 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000905
Sebastian Redl393f8b72010-07-19 20:52:06 +0000906 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl34522812010-07-16 17:50:48 +0000907
Douglas Gregor258ae542009-04-27 06:38:32 +0000908 // Set the source-location entry cursor to the current position in
909 // the stream. This cursor will be used to read the contents of the
910 // source manager block initially, and then lazily read
911 // source-location entries as needed.
Sebastian Redl393f8b72010-07-19 20:52:06 +0000912 SLocEntryCursor = F.Stream;
Douglas Gregor258ae542009-04-27 06:38:32 +0000913
914 // The stream itself is going to skip over the source manager block.
Sebastian Redl393f8b72010-07-19 20:52:06 +0000915 if (F.Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000916 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000917 return Failure;
918 }
919
920 // Enter the source manager block.
921 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000922 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000923 return Failure;
924 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000925
Douglas Gregora7f71a92009-04-10 03:52:48 +0000926 RecordData Record;
927 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000928 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000929 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000930 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000931 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000932 return Failure;
933 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000934 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000935 }
Mike Stump11289f42009-09-09 15:08:12 +0000936
Douglas Gregora7f71a92009-04-10 03:52:48 +0000937 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
938 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000939 SLocEntryCursor.ReadSubBlockID();
940 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000941 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000942 return Failure;
943 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000944 continue;
945 }
Mike Stump11289f42009-09-09 15:08:12 +0000946
Douglas Gregora7f71a92009-04-10 03:52:48 +0000947 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000948 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000949 continue;
950 }
Mike Stump11289f42009-09-09 15:08:12 +0000951
Douglas Gregora7f71a92009-04-10 03:52:48 +0000952 // Read a record.
953 const char *BlobStart;
954 unsigned BlobLen;
955 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000956 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000957 default: // Default behavior: ignore.
958 break;
959
Chris Lattner184e65d2009-04-14 23:22:57 +0000960 case pch::SM_LINE_TABLE:
Sebastian Redlb293a452010-07-20 21:20:32 +0000961 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000962 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000963 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000964
Douglas Gregor258ae542009-04-27 06:38:32 +0000965 case pch::SM_SLOC_FILE_ENTRY:
966 case pch::SM_SLOC_BUFFER_ENTRY:
967 case pch::SM_SLOC_INSTANTIATION_ENTRY:
968 // Once we hit one of the source location entries, we're done.
969 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000970 }
971 }
972}
973
Sebastian Redl06750302010-07-20 21:50:20 +0000974/// \brief Get a cursor that's correctly positioned for reading the source
975/// location entry with the given ID.
976llvm::BitstreamCursor &PCHReader::SLocCursorForID(unsigned ID) {
977 assert(ID != 0 && ID <= TotalNumSLocEntries &&
978 "SLocCursorForID should only be called for real IDs.");
979
980 ID -= 1;
981 PerFileData *F = 0;
982 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
983 F = Chain[N - I - 1];
984 if (ID < F->LocalNumSLocEntries)
985 break;
986 ID -= F->LocalNumSLocEntries;
987 }
988 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
989
990 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
991 return F->SLocEntryCursor;
992}
993
Douglas Gregor258ae542009-04-27 06:38:32 +0000994/// \brief Read in the source location entry with the given ID.
995PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
996 if (ID == 0)
997 return Success;
998
999 if (ID > TotalNumSLocEntries) {
1000 Error("source location entry ID out-of-range for PCH file");
1001 return Failure;
1002 }
1003
Sebastian Redl06750302010-07-20 21:50:20 +00001004 llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
Sebastian Redl34522812010-07-16 17:50:48 +00001005
Douglas Gregor258ae542009-04-27 06:38:32 +00001006 ++NumSLocEntriesRead;
Douglas Gregor258ae542009-04-27 06:38:32 +00001007 unsigned Code = SLocEntryCursor.ReadCode();
1008 if (Code == llvm::bitc::END_BLOCK ||
1009 Code == llvm::bitc::ENTER_SUBBLOCK ||
1010 Code == llvm::bitc::DEFINE_ABBREV) {
1011 Error("incorrectly-formatted source location entry in PCH file");
1012 return Failure;
1013 }
1014
Douglas Gregor258ae542009-04-27 06:38:32 +00001015 RecordData Record;
1016 const char *BlobStart;
1017 unsigned BlobLen;
1018 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1019 default:
1020 Error("incorrectly-formatted source location entry in PCH file");
1021 return Failure;
1022
1023 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001024 std::string Filename(BlobStart, BlobStart + BlobLen);
1025 MaybeAddSystemRootToFilename(Filename);
1026 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +00001027 if (File == 0) {
1028 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001029 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +00001030 ErrorStr += "' referenced by PCH file";
1031 Error(ErrorStr.c_str());
1032 return Failure;
1033 }
Mike Stump11289f42009-09-09 15:08:12 +00001034
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001035 if (Record.size() < 10) {
Ted Kremenekabb1ddd2010-03-18 21:23:05 +00001036 Error("source location entry is incorrect");
1037 return Failure;
1038 }
1039
Douglas Gregorce3a8292010-07-27 00:27:13 +00001040 if (!DisableValidation &&
1041 ((off_t)Record[4] != File->getSize()
Douglas Gregor08288f22010-04-09 15:54:22 +00001042#if !defined(LLVM_ON_WIN32)
1043 // In our regression testing, the Windows file system seems to
1044 // have inconsistent modification times that sometimes
1045 // erroneously trigger this error-handling path.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001046 || (time_t)Record[5] != File->getModificationTime()
Douglas Gregor08288f22010-04-09 15:54:22 +00001047#endif
Douglas Gregorce3a8292010-07-27 00:27:13 +00001048 )) {
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001049 Diag(diag::err_fe_pch_file_modified)
1050 << Filename;
1051 return Failure;
1052 }
1053
Douglas Gregor258ae542009-04-27 06:38:32 +00001054 FileID FID = SourceMgr.createFileID(File,
1055 SourceLocation::getFromRawEncoding(Record[1]),
1056 (SrcMgr::CharacteristicKind)Record[2],
1057 ID, Record[0]);
1058 if (Record[3])
1059 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1060 .setHasLineDirectives();
1061
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001062 // Reconstruct header-search information for this file.
1063 HeaderFileInfo HFI;
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001064 HFI.isImport = Record[6];
1065 HFI.DirInfo = Record[7];
1066 HFI.NumIncludes = Record[8];
1067 HFI.ControllingMacroID = Record[9];
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001068 if (Listener)
1069 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor258ae542009-04-27 06:38:32 +00001070 break;
1071 }
1072
1073 case pch::SM_SLOC_BUFFER_ENTRY: {
1074 const char *Name = BlobStart;
1075 unsigned Offset = Record[0];
1076 unsigned Code = SLocEntryCursor.ReadCode();
1077 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001078 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +00001079 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001080
1081 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1082 Error("PCH record has invalid code");
1083 return Failure;
1084 }
1085
Douglas Gregor258ae542009-04-27 06:38:32 +00001086 llvm::MemoryBuffer *Buffer
Chris Lattner58c79342010-04-05 22:42:27 +00001087 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1088 Name);
Douglas Gregor258ae542009-04-27 06:38:32 +00001089 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +00001090
Douglas Gregore6648fb2009-04-28 20:33:11 +00001091 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl75fbb3b2010-07-14 17:49:11 +00001092 PCHPredefinesBlock Block = {
1093 BufferID,
1094 llvm::StringRef(BlobStart, BlobLen - 1)
1095 };
1096 PCHPredefinesBuffers.push_back(Block);
Douglas Gregore6648fb2009-04-28 20:33:11 +00001097 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001098
1099 break;
1100 }
1101
1102 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +00001103 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +00001104 = SourceLocation::getFromRawEncoding(Record[1]);
1105 SourceMgr.createInstantiationLoc(SpellingLoc,
1106 SourceLocation::getFromRawEncoding(Record[2]),
1107 SourceLocation::getFromRawEncoding(Record[3]),
1108 Record[4],
1109 ID,
1110 Record[0]);
1111 break;
Mike Stump11289f42009-09-09 15:08:12 +00001112 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001113 }
1114
1115 return Success;
1116}
1117
Chris Lattnere78a6be2009-04-27 01:05:14 +00001118/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1119/// specified cursor. Read the abbreviations that are at the top of the block
1120/// and then leave the cursor pointing into the block.
1121bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1122 unsigned BlockID) {
1123 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001124 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001125 return Failure;
1126 }
Mike Stump11289f42009-09-09 15:08:12 +00001127
Chris Lattnere78a6be2009-04-27 01:05:14 +00001128 while (true) {
1129 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001130
Chris Lattnere78a6be2009-04-27 01:05:14 +00001131 // We expect all abbrevs to be at the start of the block.
1132 if (Code != llvm::bitc::DEFINE_ABBREV)
1133 return false;
1134 Cursor.ReadAbbrevRecord();
1135 }
1136}
1137
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001138void PCHReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001139 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +00001140
Douglas Gregorc3366a52009-04-21 23:56:24 +00001141 // Keep track of where we are in the stream, then jump back there
1142 // after reading this macro.
1143 SavedStreamPosition SavedPosition(Stream);
1144
1145 Stream.JumpToBit(Offset);
1146 RecordData Record;
1147 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1148 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001149
Douglas Gregorc3366a52009-04-21 23:56:24 +00001150 while (true) {
1151 unsigned Code = Stream.ReadCode();
1152 switch (Code) {
1153 case llvm::bitc::END_BLOCK:
1154 return;
1155
1156 case llvm::bitc::ENTER_SUBBLOCK:
1157 // No known subblocks, always skip them.
1158 Stream.ReadSubBlockID();
1159 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001160 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001161 return;
1162 }
1163 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001164
Douglas Gregorc3366a52009-04-21 23:56:24 +00001165 case llvm::bitc::DEFINE_ABBREV:
1166 Stream.ReadAbbrevRecord();
1167 continue;
1168 default: break;
1169 }
1170
1171 // Read a record.
1172 Record.clear();
1173 pch::PreprocessorRecordTypes RecType =
1174 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1175 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001176 case pch::PP_MACRO_OBJECT_LIKE:
1177 case pch::PP_MACRO_FUNCTION_LIKE: {
1178 // If we already have a macro, that means that we've hit the end
1179 // of the definition of the macro we were looking for. We're
1180 // done.
1181 if (Macro)
1182 return;
1183
1184 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1185 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001186 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001187 return;
1188 }
1189 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1190 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001191
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001192 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001193 MI->setIsUsed(isUsed);
Sebastian Redl98912122010-07-27 23:01:28 +00001194 MI->setIsFromPCH();
Mike Stump11289f42009-09-09 15:08:12 +00001195
Douglas Gregoraae92242010-03-19 21:51:54 +00001196 unsigned NextIndex = 3;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001197 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1198 // Decode function-like macro info.
1199 bool isC99VarArgs = Record[3];
1200 bool isGNUVarArgs = Record[4];
1201 MacroArgs.clear();
1202 unsigned NumArgs = Record[5];
Douglas Gregoraae92242010-03-19 21:51:54 +00001203 NextIndex = 6 + NumArgs;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001204 for (unsigned i = 0; i != NumArgs; ++i)
1205 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1206
1207 // Install function-like macro info.
1208 MI->setIsFunctionLike();
1209 if (isC99VarArgs) MI->setIsC99Varargs();
1210 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001211 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001212 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001213 }
1214
1215 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001216 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001217
1218 // Remember that we saw this macro last so that we add the tokens that
1219 // form its body to it.
1220 Macro = MI;
Douglas Gregoraae92242010-03-19 21:51:54 +00001221
1222 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1223 // We have a macro definition. Load it now.
1224 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1225 getMacroDefinition(Record[NextIndex]));
1226 }
1227
Douglas Gregorc3366a52009-04-21 23:56:24 +00001228 ++NumMacrosRead;
1229 break;
1230 }
Mike Stump11289f42009-09-09 15:08:12 +00001231
Douglas Gregorc3366a52009-04-21 23:56:24 +00001232 case pch::PP_TOKEN: {
1233 // If we see a TOKEN before a PP_MACRO_*, then the file is
1234 // erroneous, just pretend we didn't see this.
1235 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001236
Douglas Gregorc3366a52009-04-21 23:56:24 +00001237 Token Tok;
1238 Tok.startToken();
1239 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1240 Tok.setLength(Record[1]);
1241 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1242 Tok.setIdentifierInfo(II);
1243 Tok.setKind((tok::TokenKind)Record[3]);
1244 Tok.setFlag((Token::TokenFlags)Record[4]);
1245 Macro->AddTokenToBody(Tok);
1246 break;
1247 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001248
1249 case pch::PP_MACRO_INSTANTIATION: {
1250 // If we already have a macro, that means that we've hit the end
1251 // of the definition of the macro we were looking for. We're
1252 // done.
1253 if (Macro)
1254 return;
1255
1256 if (!PP->getPreprocessingRecord()) {
1257 Error("missing preprocessing record in PCH file");
1258 return;
1259 }
1260
1261 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1262 if (PPRec.getPreprocessedEntity(Record[0]))
1263 return;
1264
1265 MacroInstantiation *MI
1266 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1267 SourceRange(
1268 SourceLocation::getFromRawEncoding(Record[1]),
1269 SourceLocation::getFromRawEncoding(Record[2])),
1270 getMacroDefinition(Record[4]));
1271 PPRec.SetPreallocatedEntity(Record[0], MI);
1272 return;
1273 }
1274
1275 case pch::PP_MACRO_DEFINITION: {
1276 // If we already have a macro, that means that we've hit the end
1277 // of the definition of the macro we were looking for. We're
1278 // done.
1279 if (Macro)
1280 return;
1281
1282 if (!PP->getPreprocessingRecord()) {
1283 Error("missing preprocessing record in PCH file");
1284 return;
1285 }
1286
1287 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1288 if (PPRec.getPreprocessedEntity(Record[0]))
1289 return;
1290
1291 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1292 Error("out-of-bounds macro definition record");
1293 return;
1294 }
1295
1296 MacroDefinition *MD
1297 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1298 SourceLocation::getFromRawEncoding(Record[5]),
1299 SourceRange(
1300 SourceLocation::getFromRawEncoding(Record[2]),
1301 SourceLocation::getFromRawEncoding(Record[3])));
1302 PPRec.SetPreallocatedEntity(Record[0], MD);
1303 MacroDefinitionsLoaded[Record[1]] = MD;
1304 return;
1305 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001306 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001307 }
1308}
1309
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001310void PCHReader::ReadDefinedMacros() {
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001311 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1312 llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
Sebastian Redl34522812010-07-16 17:50:48 +00001313
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001314 // If there was no preprocessor block, skip this file.
1315 if (!MacroCursor.getBitStreamReader())
1316 continue;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001317
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001318 llvm::BitstreamCursor Cursor = MacroCursor;
1319 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1320 Error("malformed preprocessor block record in PCH file");
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001321 return;
1322 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001323
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001324 RecordData Record;
1325 while (true) {
1326 unsigned Code = Cursor.ReadCode();
1327 if (Code == llvm::bitc::END_BLOCK) {
1328 if (Cursor.ReadBlockEnd()) {
1329 Error("error at end of preprocessor block in PCH file");
1330 return;
1331 }
1332 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001333 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001334
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001335 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1336 // No known subblocks, always skip them.
1337 Cursor.ReadSubBlockID();
1338 if (Cursor.SkipBlock()) {
1339 Error("malformed block record in PCH file");
1340 return;
1341 }
1342 continue;
1343 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001344
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001345 if (Code == llvm::bitc::DEFINE_ABBREV) {
1346 Cursor.ReadAbbrevRecord();
1347 continue;
1348 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001349
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001350 // Read a record.
1351 const char *BlobStart;
1352 unsigned BlobLen;
1353 Record.clear();
1354 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1355 default: // Default behavior: ignore.
1356 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001357
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001358 case pch::PP_MACRO_OBJECT_LIKE:
1359 case pch::PP_MACRO_FUNCTION_LIKE:
1360 DecodeIdentifierInfo(Record[0]);
1361 break;
1362
1363 case pch::PP_TOKEN:
1364 // Ignore tokens.
1365 break;
Douglas Gregoraae92242010-03-19 21:51:54 +00001366
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001367 case pch::PP_MACRO_INSTANTIATION:
1368 case pch::PP_MACRO_DEFINITION:
1369 // Read the macro record.
1370 ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1371 break;
1372 }
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001373 }
1374 }
1375}
1376
Douglas Gregoraae92242010-03-19 21:51:54 +00001377MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1378 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1379 return 0;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001380
1381 if (!MacroDefinitionsLoaded[ID]) {
1382 unsigned Index = ID;
1383 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1384 PerFileData &F = *Chain[N - I - 1];
1385 if (Index < F.LocalNumMacroDefinitions) {
1386 ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1387 break;
1388 }
1389 Index -= F.LocalNumMacroDefinitions;
1390 }
1391 assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1392 }
1393
Douglas Gregoraae92242010-03-19 21:51:54 +00001394 return MacroDefinitionsLoaded[ID];
1395}
1396
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001397/// \brief If we are loading a relocatable PCH file, and the filename is
1398/// not an absolute path, add the system root to the beginning of the file
1399/// name.
1400void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1401 // If this is not a relocatable PCH file, there's nothing to do.
1402 if (!RelocatablePCH)
1403 return;
Mike Stump11289f42009-09-09 15:08:12 +00001404
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001405 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001406 return;
1407
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001408 if (isysroot == 0) {
1409 // If no system root was given, default to '/'
1410 Filename.insert(Filename.begin(), '/');
1411 return;
1412 }
Mike Stump11289f42009-09-09 15:08:12 +00001413
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001414 unsigned Length = strlen(isysroot);
1415 if (isysroot[Length - 1] != '/')
1416 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001417
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001418 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1419}
1420
Mike Stump11289f42009-09-09 15:08:12 +00001421PCHReader::PCHReadResult
Sebastian Redl2abc0382010-07-16 20:41:52 +00001422PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl34522812010-07-16 17:50:48 +00001423 llvm::BitstreamCursor &Stream = F.Stream;
1424
Douglas Gregor55abb232009-04-10 20:39:37 +00001425 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001426 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001427 return Failure;
1428 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001429
1430 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001431 RecordData Record;
Sebastian Redl393f8b72010-07-19 20:52:06 +00001432 bool First = true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001433 while (!Stream.AtEndOfStream()) {
1434 unsigned Code = Stream.ReadCode();
1435 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001436 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001437 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001438 return Failure;
1439 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001440
Douglas Gregor55abb232009-04-10 20:39:37 +00001441 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001442 }
1443
1444 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1445 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001446 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001447 // We lazily load the decls block, but we want to set up the
1448 // DeclsCursor cursor to point into it. Clone our current bitcode
1449 // cursor to it, enter the block and read the abbrevs in that block.
1450 // With the main cursor, we just skip over it.
Sebastian Redl34522812010-07-16 17:50:48 +00001451 F.DeclsCursor = Stream;
Chris Lattnere78a6be2009-04-27 01:05:14 +00001452 if (Stream.SkipBlock() || // Skip with the main cursor.
1453 // Read the abbrevs.
Sebastian Redl34522812010-07-16 17:50:48 +00001454 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001455 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001456 return Failure;
1457 }
1458 break;
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001460 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl34522812010-07-16 17:50:48 +00001461 F.MacroCursor = Stream;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001462 if (PP)
1463 PP->setExternalSource(this);
1464
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001465 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001466 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001467 return Failure;
1468 }
1469 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001470
Douglas Gregora7f71a92009-04-10 03:52:48 +00001471 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl393f8b72010-07-19 20:52:06 +00001472 switch (ReadSourceManagerBlock(F)) {
Douglas Gregor92863e42009-04-10 23:10:45 +00001473 case Success:
1474 break;
1475
1476 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001477 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001478 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001479
1480 case IgnorePCH:
1481 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001482 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001483 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001484 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00001485 First = false;
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001486 continue;
1487 }
1488
1489 if (Code == llvm::bitc::DEFINE_ABBREV) {
1490 Stream.ReadAbbrevRecord();
1491 continue;
1492 }
1493
1494 // Read and process a record.
1495 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001496 const char *BlobStart = 0;
1497 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001498 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001499 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001500 default: // Default behavior: ignore.
1501 break;
1502
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001503 case pch::METADATA: {
Douglas Gregorce3a8292010-07-27 00:27:13 +00001504 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001505 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1506 : diag::warn_pch_version_too_new);
1507 return IgnorePCH;
1508 }
1509
1510 RelocatablePCH = Record[4];
1511 if (Listener) {
1512 std::string TargetTriple(BlobStart, BlobLen);
1513 if (Listener->ReadTargetTriple(TargetTriple))
1514 return IgnorePCH;
1515 }
1516 break;
1517 }
1518
1519 case pch::CHAINED_METADATA: {
Sebastian Redl393f8b72010-07-19 20:52:06 +00001520 if (!First) {
1521 Error("CHAINED_METADATA is not first record in block");
1522 return Failure;
1523 }
Douglas Gregorce3a8292010-07-27 00:27:13 +00001524 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001525 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1526 : diag::warn_pch_version_too_new);
1527 return IgnorePCH;
1528 }
1529
1530 // Load the chained file.
1531 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1532 case Failure: return Failure;
1533 // If we have to ignore the dependency, we'll have to ignore this too.
1534 case IgnorePCH: return IgnorePCH;
1535 case Success: break;
1536 }
1537 break;
1538 }
1539
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001540 case pch::TYPE_OFFSET:
Sebastian Redl9e687992010-07-19 22:06:55 +00001541 if (F.LocalNumTypes != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001542 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001543 return Failure;
1544 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001545 F.TypeOffsets = (const uint32_t *)BlobStart;
1546 F.LocalNumTypes = Record[0];
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001547 break;
1548
1549 case pch::DECL_OFFSET:
Sebastian Redl9e687992010-07-19 22:06:55 +00001550 if (F.LocalNumDecls != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001551 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001552 return Failure;
1553 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001554 F.DeclOffsets = (const uint32_t *)BlobStart;
1555 F.LocalNumDecls = Record[0];
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001556 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001557
Sebastian Redl4b1f4902010-07-27 18:24:41 +00001558 case pch::TU_UPDATE_LEXICAL: {
1559 DeclContextInfo Info = {
1560 /* No visible information */ 0, 0,
1561 reinterpret_cast<const pch::DeclID *>(BlobStart),
1562 BlobLen / sizeof(pch::DeclID)
1563 };
1564 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1565 break;
1566 }
1567
Argyrios Kyrtzidis839bbac2010-08-03 17:30:10 +00001568 case pch::REDECLS_UPDATE_LATEST: {
1569 assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
1570 for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
1571 pch::DeclID First = Record[i], Latest = Record[i+1];
1572 assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
1573 Latest > FirstLatestDeclIDs[First]) &&
1574 "The new latest is supposed to come after the previous latest");
1575 FirstLatestDeclIDs[First] = Latest;
1576 }
1577 break;
1578 }
1579
Douglas Gregor55abb232009-04-10 20:39:37 +00001580 case pch::LANGUAGE_OPTIONS:
Douglas Gregorce3a8292010-07-27 00:27:13 +00001581 if (ParseLanguageOptions(Record) && !DisableValidation)
Douglas Gregor55abb232009-04-10 20:39:37 +00001582 return IgnorePCH;
1583 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001584
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001585 case pch::IDENTIFIER_TABLE:
Sebastian Redl393f8b72010-07-19 20:52:06 +00001586 F.IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001587 if (Record[0]) {
Sebastian Redl393f8b72010-07-19 20:52:06 +00001588 F.IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001589 = PCHIdentifierLookupTable::Create(
Sebastian Redl393f8b72010-07-19 20:52:06 +00001590 (const unsigned char *)F.IdentifierTableData + Record[0],
1591 (const unsigned char *)F.IdentifierTableData,
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001592 PCHIdentifierLookupTrait(*this, F.Stream));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001593 if (PP)
1594 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001595 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001596 break;
1597
1598 case pch::IDENTIFIER_OFFSET:
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001599 if (F.LocalNumIdentifiers != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001600 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001601 return Failure;
1602 }
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001603 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1604 F.LocalNumIdentifiers = Record[0];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001605 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001606
1607 case pch::EXTERNAL_DEFINITIONS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001608 // Optimization for the first block.
1609 if (ExternalDefinitions.empty())
1610 ExternalDefinitions.swap(Record);
1611 else
1612 ExternalDefinitions.insert(ExternalDefinitions.end(),
1613 Record.begin(), Record.end());
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001614 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001615
Douglas Gregor652d82a2009-04-18 05:55:16 +00001616 case pch::SPECIAL_TYPES:
Sebastian Redlb293a452010-07-20 21:20:32 +00001617 // Optimization for the first block
1618 if (SpecialTypes.empty())
1619 SpecialTypes.swap(Record);
1620 else
1621 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
Douglas Gregor652d82a2009-04-18 05:55:16 +00001622 break;
1623
Douglas Gregor08f01292009-04-17 22:13:46 +00001624 case pch::STATISTICS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001625 TotalNumStatements += Record[0];
1626 TotalNumMacros += Record[1];
1627 TotalLexicalDeclContexts += Record[2];
1628 TotalVisibleDeclContexts += Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001629 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001630
Douglas Gregord4df8652009-04-22 22:02:47 +00001631 case pch::TENTATIVE_DEFINITIONS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001632 // Optimization for the first block.
1633 if (TentativeDefinitions.empty())
1634 TentativeDefinitions.swap(Record);
1635 else
1636 TentativeDefinitions.insert(TentativeDefinitions.end(),
1637 Record.begin(), Record.end());
Douglas Gregord4df8652009-04-22 22:02:47 +00001638 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001639
Tanya Lattner90073802010-02-12 00:07:30 +00001640 case pch::UNUSED_STATIC_FUNCS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001641 // Optimization for the first block.
1642 if (UnusedStaticFuncs.empty())
1643 UnusedStaticFuncs.swap(Record);
1644 else
1645 UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
1646 Record.begin(), Record.end());
Tanya Lattner90073802010-02-12 00:07:30 +00001647 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001648
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00001649 case pch::WEAK_UNDECLARED_IDENTIFIERS:
Sebastian Redl08aca90252010-08-05 18:21:25 +00001650 // Later blocks overwrite earlier ones.
1651 WeakUndeclaredIdentifiers.swap(Record);
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00001652 break;
1653
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001654 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001655 // Optimization for the first block.
1656 if (LocallyScopedExternalDecls.empty())
1657 LocallyScopedExternalDecls.swap(Record);
1658 else
1659 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1660 Record.begin(), Record.end());
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001661 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001662
Douglas Gregor95c13f52009-04-25 17:48:32 +00001663 case pch::SELECTOR_OFFSETS:
Sebastian Redla19a67f2010-08-03 21:58:15 +00001664 F.SelectorOffsets = (const uint32_t *)BlobStart;
Sebastian Redlada023c2010-08-04 20:40:17 +00001665 F.LocalNumSelectors = Record[0];
Douglas Gregor95c13f52009-04-25 17:48:32 +00001666 break;
1667
Douglas Gregorc78d3462009-04-24 21:10:55 +00001668 case pch::METHOD_POOL:
Sebastian Redlada023c2010-08-04 20:40:17 +00001669 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
Douglas Gregor95c13f52009-04-25 17:48:32 +00001670 if (Record[0])
Sebastian Redlada023c2010-08-04 20:40:17 +00001671 F.SelectorLookupTable
1672 = PCHSelectorLookupTable::Create(
1673 F.SelectorLookupTableData + Record[0],
1674 F.SelectorLookupTableData,
1675 PCHSelectorLookupTrait(*this));
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00001676 TotalNumMethodPoolEntries += Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001677 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001678
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001679 case pch::REFERENCED_SELECTOR_POOL: {
Sebastian Redlada023c2010-08-04 20:40:17 +00001680 ReferencedSelectorsData.insert(ReferencedSelectorsData.end(),
1681 Record.begin(), Record.end());
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001682 break;
Sebastian Redl66c5eef2010-07-27 00:17:23 +00001683 }
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001684
Douglas Gregoreda6a892009-04-26 00:07:37 +00001685 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001686 if (!Record.empty() && Listener)
1687 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001688 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001689
1690 case pch::SOURCE_LOCATION_OFFSETS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001691 F.SLocOffsets = (const uint32_t *)BlobStart;
1692 F.LocalNumSLocEntries = Record[0];
1693 // We cannot delay this until all PCHs are loaded, because then source
1694 // location preloads would also have to be delayed.
1695 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregord54f3a12009-10-05 21:07:28 +00001696 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001697 break;
1698
1699 case pch::SOURCE_LOCATION_PRELOADS:
1700 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1701 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1702 if (Result != Success)
1703 return Result;
1704 }
1705 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001706
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001707 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001708 PCHStatCache *MyStatCache =
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001709 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1710 (const unsigned char *)BlobStart,
1711 NumStatHits, NumStatMisses);
1712 FileMgr.addStatCache(MyStatCache);
Sebastian Redl34522812010-07-16 17:50:48 +00001713 F.StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001714 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001715 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001716
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001717 case pch::EXT_VECTOR_DECLS:
Sebastian Redl04f5c312010-07-28 21:38:49 +00001718 // Optimization for the first block.
1719 if (ExtVectorDecls.empty())
1720 ExtVectorDecls.swap(Record);
1721 else
1722 ExtVectorDecls.insert(ExtVectorDecls.end(),
1723 Record.begin(), Record.end());
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001724 break;
1725
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00001726 case pch::VTABLE_USES:
Sebastian Redl08aca90252010-08-05 18:21:25 +00001727 // Later tables overwrite earlier ones.
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00001728 VTableUses.swap(Record);
1729 break;
1730
1731 case pch::DYNAMIC_CLASSES:
Sebastian Redl08aca90252010-08-05 18:21:25 +00001732 // Optimization for the first block.
1733 if (DynamicClasses.empty())
1734 DynamicClasses.swap(Record);
1735 else
1736 DynamicClasses.insert(DynamicClasses.end(),
1737 Record.begin(), Record.end());
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00001738 break;
1739
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00001740 case pch::PENDING_IMPLICIT_INSTANTIATIONS:
1741 // Optimization for the first block.
1742 if (PendingImplicitInstantiations.empty())
1743 PendingImplicitInstantiations.swap(Record);
1744 else
1745 PendingImplicitInstantiations.insert(
1746 PendingImplicitInstantiations.end(), Record.begin(), Record.end());
1747 break;
1748
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001749 case pch::SEMA_DECL_REFS:
Sebastian Redl08aca90252010-08-05 18:21:25 +00001750 // Later tables overwrite earlier ones.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001751 SemaDeclRefs.swap(Record);
1752 break;
1753
Douglas Gregor45fe0362009-05-12 01:31:05 +00001754 case pch::ORIGINAL_FILE_NAME:
Sebastian Redlb293a452010-07-20 21:20:32 +00001755 // The primary PCH will be the last to get here, so it will be the one
1756 // that's used.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001757 ActualOriginalFileName.assign(BlobStart, BlobLen);
1758 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001759 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001760 break;
Mike Stump11289f42009-09-09 15:08:12 +00001761
Ted Kremenek17437132010-01-22 20:59:36 +00001762 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek8bd09292010-02-12 23:31:14 +00001763 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek2377a0e2010-01-22 20:55:35 +00001764 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001765 if (llvm::StringRef(CurBranch) != PCHBranch && !DisableValidation) {
Douglas Gregord54f3a12009-10-05 21:07:28 +00001766 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1767 return IgnorePCH;
1768 }
1769 break;
1770 }
Sebastian Redlfa061442010-07-21 20:07:32 +00001771
Douglas Gregoraae92242010-03-19 21:51:54 +00001772 case pch::MACRO_DEFINITION_OFFSETS:
Sebastian Redlfa061442010-07-21 20:07:32 +00001773 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1774 F.NumPreallocatedPreprocessingEntities = Record[0];
1775 F.LocalNumMacroDefinitions = Record[1];
Douglas Gregoraae92242010-03-19 21:51:54 +00001776 break;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001777 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00001778 First = false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001779 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001780 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001781 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001782}
1783
Douglas Gregor92863e42009-04-10 23:10:45 +00001784PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001785 switch(ReadPCHCore(FileName)) {
Sebastian Redl2abc0382010-07-16 20:41:52 +00001786 case Failure: return Failure;
1787 case IgnorePCH: return IgnorePCH;
1788 case Success: break;
1789 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001790
1791 // Here comes stuff that we only do once the entire chain is loaded.
1792
Sebastian Redlb293a452010-07-20 21:20:32 +00001793 // Allocate space for loaded identifiers, decls and types.
Sebastian Redlfa061442010-07-21 20:07:32 +00001794 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
Sebastian Redlada023c2010-08-04 20:40:17 +00001795 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0,
1796 TotalNumSelectors = 0;
Sebastian Redl9e687992010-07-19 22:06:55 +00001797 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001798 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
Sebastian Redl9e687992010-07-19 22:06:55 +00001799 TotalNumTypes += Chain[I]->LocalNumTypes;
1800 TotalNumDecls += Chain[I]->LocalNumDecls;
Sebastian Redlfa061442010-07-21 20:07:32 +00001801 TotalNumPreallocatedPreprocessingEntities +=
1802 Chain[I]->NumPreallocatedPreprocessingEntities;
1803 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
Sebastian Redlada023c2010-08-04 20:40:17 +00001804 TotalNumSelectors += Chain[I]->LocalNumSelectors;
Sebastian Redl9e687992010-07-19 22:06:55 +00001805 }
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001806 IdentifiersLoaded.resize(TotalNumIdentifiers);
Sebastian Redl9e687992010-07-19 22:06:55 +00001807 TypesLoaded.resize(TotalNumTypes);
1808 DeclsLoaded.resize(TotalNumDecls);
Sebastian Redlfa061442010-07-21 20:07:32 +00001809 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
1810 if (PP) {
1811 if (TotalNumIdentifiers > 0)
1812 PP->getHeaderSearchInfo().SetExternalLookup(this);
1813 if (TotalNumPreallocatedPreprocessingEntities > 0) {
1814 if (!PP->getPreprocessingRecord())
1815 PP->createPreprocessingRecord();
1816 PP->getPreprocessingRecord()->SetExternalSource(*this,
1817 TotalNumPreallocatedPreprocessingEntities);
1818 }
1819 }
Sebastian Redlada023c2010-08-04 20:40:17 +00001820 SelectorsLoaded.resize(TotalNumSelectors);
Sebastian Redl9e687992010-07-19 22:06:55 +00001821
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001822 // Check the predefines buffers.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001823 if (!DisableValidation && CheckPredefinesBuffers())
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001824 return IgnorePCH;
1825
1826 if (PP) {
1827 // Initialization of keywords and pragmas occurs before the
1828 // PCH file is read, so there may be some identifiers that were
1829 // loaded into the IdentifierTable before we intercepted the
1830 // creation of identifiers. Iterate through the list of known
1831 // identifiers and determine whether we have to establish
1832 // preprocessor definitions or top-level identifier declaration
1833 // chains for those identifiers.
1834 //
1835 // We copy the IdentifierInfo pointers to a small vector first,
1836 // since de-serializing declarations or macro definitions can add
1837 // new entries into the identifier table, invalidating the
1838 // iterators.
1839 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1840 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1841 IdEnd = PP->getIdentifierTable().end();
1842 Id != IdEnd; ++Id)
1843 Identifiers.push_back(Id->second);
Sebastian Redlfa061442010-07-21 20:07:32 +00001844 // We need to search the tables in all files.
Sebastian Redlfa061442010-07-21 20:07:32 +00001845 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1846 PCHIdentifierLookupTable *IdTable
1847 = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
Sebastian Redl5c415f32010-07-22 17:01:13 +00001848 // Not all PCH files necessarily have identifier tables, only the useful
1849 // ones.
1850 if (!IdTable)
1851 continue;
Sebastian Redlfa061442010-07-21 20:07:32 +00001852 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1853 IdentifierInfo *II = Identifiers[I];
1854 // Look in the on-disk hash tables for an entry for this identifier
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001855 PCHIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
Sebastian Redlfa061442010-07-21 20:07:32 +00001856 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
Sebastian Redlb293a452010-07-20 21:20:32 +00001857 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1858 if (Pos == IdTable->end())
1859 continue;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001860
Sebastian Redlb293a452010-07-20 21:20:32 +00001861 // Dereferencing the iterator has the effect of populating the
1862 // IdentifierInfo node with the various declarations it needs.
1863 (void)*Pos;
1864 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001865 }
1866 }
1867
1868 if (Context)
1869 InitializeContext(*Context);
1870
1871 return Success;
1872}
1873
1874PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1875 Chain.push_back(new PerFileData());
Sebastian Redl34522812010-07-16 17:50:48 +00001876 PerFileData &F = *Chain.back();
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001877
1878 // Set the PCH file name.
1879 F.FileName = FileName;
1880
1881 // Open the PCH file.
1882 //
1883 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1884 std::string ErrStr;
1885 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1886 if (!F.Buffer) {
1887 Error(ErrStr.c_str());
1888 return IgnorePCH;
1889 }
1890
1891 // Initialize the stream
1892 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1893 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl34522812010-07-16 17:50:48 +00001894 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001895 Stream.init(F.StreamFile);
Sebastian Redlfa061442010-07-21 20:07:32 +00001896 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001897
1898 // Sniff for the signature.
1899 if (Stream.Read(8) != 'C' ||
1900 Stream.Read(8) != 'P' ||
1901 Stream.Read(8) != 'C' ||
1902 Stream.Read(8) != 'H') {
1903 Diag(diag::err_not_a_pch_file) << FileName;
1904 return Failure;
1905 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001906
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001907 while (!Stream.AtEndOfStream()) {
1908 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001909
Douglas Gregor92863e42009-04-10 23:10:45 +00001910 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001911 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001912 return Failure;
1913 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001914
1915 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001916
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001917 // We only know the PCH subblock ID.
1918 switch (BlockID) {
1919 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001920 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001921 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001922 return Failure;
1923 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001924 break;
1925 case pch::PCH_BLOCK_ID:
Sebastian Redl2abc0382010-07-16 20:41:52 +00001926 switch (ReadPCHBlock(F)) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001927 case Success:
1928 break;
1929
1930 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001931 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001932
1933 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001934 // FIXME: We could consider reading through to the end of this
1935 // PCH block, skipping subblocks, to see if there are other
1936 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001937
1938 // Clear out any preallocated source location entries, so that
1939 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001940 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001941
1942 // Remove the stat cache.
Sebastian Redl34522812010-07-16 17:50:48 +00001943 if (F.StatCache)
1944 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001945
Douglas Gregor92863e42009-04-10 23:10:45 +00001946 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001947 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001948 break;
1949 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001950 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001951 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001952 return Failure;
1953 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001954 break;
1955 }
Mike Stump11289f42009-09-09 15:08:12 +00001956 }
1957
Sebastian Redl2abc0382010-07-16 20:41:52 +00001958 return Success;
1959}
1960
Douglas Gregoraae92242010-03-19 21:51:54 +00001961void PCHReader::setPreprocessor(Preprocessor &pp) {
1962 PP = &pp;
Sebastian Redlfa061442010-07-21 20:07:32 +00001963
1964 unsigned TotalNum = 0;
1965 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
1966 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
1967 if (TotalNum) {
Douglas Gregoraae92242010-03-19 21:51:54 +00001968 if (!PP->getPreprocessingRecord())
1969 PP->createPreprocessingRecord();
Sebastian Redlfa061442010-07-21 20:07:32 +00001970 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
Douglas Gregoraae92242010-03-19 21:51:54 +00001971 }
1972}
1973
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001974void PCHReader::InitializeContext(ASTContext &Ctx) {
1975 Context = &Ctx;
1976 assert(Context && "Passed null context!");
1977
1978 assert(PP && "Forgot to set Preprocessor ?");
1979 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1980 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001981 PP->setExternalSource(this);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001982
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001983 // Load the translation unit declaration
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00001984 GetTranslationUnitDecl();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001985
1986 // Load the special types.
1987 Context->setBuiltinVaListType(
1988 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1989 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1990 Context->setObjCIdType(GetType(Id));
1991 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1992 Context->setObjCSelType(GetType(Sel));
1993 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1994 Context->setObjCProtoType(GetType(Proto));
1995 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1996 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001997
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001998 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1999 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00002000 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002001 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
2002 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00002003 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
2004 QualType FileType = GetType(File);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002005 if (FileType.isNull()) {
2006 Error("FILE type is NULL");
2007 return;
2008 }
John McCall9dd450b2009-09-21 23:43:11 +00002009 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00002010 Context->setFILEDecl(Typedef->getDecl());
2011 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002012 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002013 if (!Tag) {
2014 Error("Invalid FILE type in PCH file");
2015 return;
2016 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00002017 Context->setFILEDecl(Tag->getDecl());
2018 }
2019 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00002020 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
2021 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002022 if (Jmp_bufType.isNull()) {
2023 Error("jmp_bug type is NULL");
2024 return;
2025 }
John McCall9dd450b2009-09-21 23:43:11 +00002026 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00002027 Context->setjmp_bufDecl(Typedef->getDecl());
2028 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002029 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002030 if (!Tag) {
2031 Error("Invalid jmp_bug type in PCH file");
2032 return;
2033 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00002034 Context->setjmp_bufDecl(Tag->getDecl());
2035 }
2036 }
2037 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
2038 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002039 if (Sigjmp_bufType.isNull()) {
2040 Error("sigjmp_buf type is NULL");
2041 return;
2042 }
John McCall9dd450b2009-09-21 23:43:11 +00002043 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00002044 Context->setsigjmp_bufDecl(Typedef->getDecl());
2045 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002046 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00002047 assert(Tag && "Invalid sigjmp_buf type in PCH file");
2048 Context->setsigjmp_bufDecl(Tag->getDecl());
2049 }
2050 }
Mike Stump11289f42009-09-09 15:08:12 +00002051 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00002052 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2053 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00002054 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00002055 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2056 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpd0153282009-10-20 02:12:22 +00002057 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2058 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002059 if (unsigned String
2060 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2061 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002062 if (unsigned ObjCSelRedef
2063 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2064 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2065 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
2066 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +00002067
2068 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
2069 Context->setInt128Installed();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002070}
2071
Douglas Gregor45fe0362009-05-12 01:31:05 +00002072/// \brief Retrieve the name of the original source file name
2073/// directly from the PCH file, without actually loading the PCH
2074/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00002075std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
2076 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00002077 // Open the PCH file.
2078 std::string ErrStr;
2079 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2080 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
2081 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002082 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002083 return std::string();
2084 }
2085
2086 // Initialize the stream
2087 llvm::BitstreamReader StreamFile;
2088 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00002089 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00002090 (const unsigned char *)Buffer->getBufferEnd());
2091 Stream.init(StreamFile);
2092
2093 // Sniff for the signature.
2094 if (Stream.Read(8) != 'C' ||
2095 Stream.Read(8) != 'P' ||
2096 Stream.Read(8) != 'C' ||
2097 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002098 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002099 return std::string();
2100 }
2101
2102 RecordData Record;
2103 while (!Stream.AtEndOfStream()) {
2104 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00002105
Douglas Gregor45fe0362009-05-12 01:31:05 +00002106 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2107 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00002108
Douglas Gregor45fe0362009-05-12 01:31:05 +00002109 // We only know the PCH subblock ID.
2110 switch (BlockID) {
2111 case pch::PCH_BLOCK_ID:
2112 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002113 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002114 return std::string();
2115 }
2116 break;
Mike Stump11289f42009-09-09 15:08:12 +00002117
Douglas Gregor45fe0362009-05-12 01:31:05 +00002118 default:
2119 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002120 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002121 return std::string();
2122 }
2123 break;
2124 }
2125 continue;
2126 }
2127
2128 if (Code == llvm::bitc::END_BLOCK) {
2129 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002130 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002131 return std::string();
2132 }
2133 continue;
2134 }
2135
2136 if (Code == llvm::bitc::DEFINE_ABBREV) {
2137 Stream.ReadAbbrevRecord();
2138 continue;
2139 }
2140
2141 Record.clear();
2142 const char *BlobStart = 0;
2143 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002144 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00002145 == pch::ORIGINAL_FILE_NAME)
2146 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00002147 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00002148
2149 return std::string();
2150}
2151
Douglas Gregor55abb232009-04-10 20:39:37 +00002152/// \brief Parse the record that corresponds to a LangOptions data
2153/// structure.
2154///
2155/// This routine compares the language options used to generate the
2156/// PCH file against the language options set for the current
2157/// compilation. For each option, we classify differences between the
2158/// two compiler states as either "benign" or "important". Benign
2159/// differences don't matter, and we accept them without complaint
2160/// (and without modifying the language options). Differences between
2161/// the states for important options cause the PCH file to be
2162/// unusable, so we emit a warning and return true to indicate that
2163/// there was an error.
2164///
2165/// \returns true if the PCH file is unacceptable, false otherwise.
2166bool PCHReader::ParseLanguageOptions(
2167 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002168 if (Listener) {
2169 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00002170
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002171 #define PARSE_LANGOPT(Option) \
2172 LangOpts.Option = Record[Idx]; \
2173 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00002174
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002175 unsigned Idx = 0;
2176 PARSE_LANGOPT(Trigraphs);
2177 PARSE_LANGOPT(BCPLComment);
2178 PARSE_LANGOPT(DollarIdents);
2179 PARSE_LANGOPT(AsmPreprocessor);
2180 PARSE_LANGOPT(GNUMode);
Chandler Carruthe03aa552010-04-17 20:17:31 +00002181 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002182 PARSE_LANGOPT(ImplicitInt);
2183 PARSE_LANGOPT(Digraphs);
2184 PARSE_LANGOPT(HexFloats);
2185 PARSE_LANGOPT(C99);
2186 PARSE_LANGOPT(Microsoft);
2187 PARSE_LANGOPT(CPlusPlus);
2188 PARSE_LANGOPT(CPlusPlus0x);
2189 PARSE_LANGOPT(CXXOperatorNames);
2190 PARSE_LANGOPT(ObjC1);
2191 PARSE_LANGOPT(ObjC2);
2192 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00002193 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian62c56022010-04-22 21:01:59 +00002194 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002195 PARSE_LANGOPT(PascalStrings);
2196 PARSE_LANGOPT(WritableStrings);
2197 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00002198 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002199 PARSE_LANGOPT(Exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +00002200 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002201 PARSE_LANGOPT(NeXTRuntime);
2202 PARSE_LANGOPT(Freestanding);
2203 PARSE_LANGOPT(NoBuiltin);
2204 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00002205 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002206 PARSE_LANGOPT(Blocks);
2207 PARSE_LANGOPT(EmitAllDecls);
2208 PARSE_LANGOPT(MathErrno);
Chris Lattner51924e512010-06-26 21:25:03 +00002209 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2210 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002211 PARSE_LANGOPT(HeinousExtensions);
2212 PARSE_LANGOPT(Optimize);
2213 PARSE_LANGOPT(OptimizeSize);
2214 PARSE_LANGOPT(Static);
2215 PARSE_LANGOPT(PICLevel);
2216 PARSE_LANGOPT(GNUInline);
2217 PARSE_LANGOPT(NoInline);
2218 PARSE_LANGOPT(AccessControl);
2219 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00002220 PARSE_LANGOPT(ShortWChar);
Chris Lattner51924e512010-06-26 21:25:03 +00002221 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2222 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbar143021e2009-09-21 04:16:19 +00002223 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattner51924e512010-06-26 21:25:03 +00002224 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002225 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00002226 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00002227 PARSE_LANGOPT(CatchUndefined);
2228 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002229 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00002230
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002231 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00002232 }
Douglas Gregor55abb232009-04-10 20:39:37 +00002233
2234 return false;
2235}
2236
Douglas Gregoraae92242010-03-19 21:51:54 +00002237void PCHReader::ReadPreprocessedEntities() {
2238 ReadDefinedMacros();
2239}
2240
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002241/// \brief Get the correct cursor and offset for loading a type.
2242PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
2243 PerFileData *F = 0;
2244 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2245 F = Chain[N - I - 1];
2246 if (Index < F->LocalNumTypes)
2247 break;
2248 Index -= F->LocalNumTypes;
2249 }
2250 assert(F && F->LocalNumTypes > Index && "Broken chain");
Sebastian Redlb2831db2010-07-20 22:55:31 +00002251 return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002252}
2253
2254/// \brief Read and return the type with the given index..
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002255///
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002256/// The index is the type ID, shifted and minus the number of predefs. This
2257/// routine actually reads the record corresponding to the type at the given
2258/// location. It is a helper routine for GetType, which deals with reading type
2259/// IDs.
2260QualType PCHReader::ReadTypeRecord(unsigned Index) {
2261 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redlb2831db2010-07-20 22:55:31 +00002262 llvm::BitstreamCursor &DeclsCursor = *Loc.first;
Sebastian Redl34522812010-07-16 17:50:48 +00002263
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002264 // Keep track of where we are in the stream, then jump back there
2265 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00002266 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002267
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002268 ReadingKindTracker ReadingKind(Read_Type, *this);
Sebastian Redleaa4ade2010-08-11 18:52:41 +00002269
Douglas Gregor1342e842009-07-06 18:54:52 +00002270 // Note that we are loading a type record.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00002271 Deserializing AType(this);
Mike Stump11289f42009-09-09 15:08:12 +00002272
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002273 DeclsCursor.JumpToBit(Loc.second);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002274 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00002275 unsigned Code = DeclsCursor.ReadCode();
2276 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00002277 case pch::TYPE_EXT_QUAL: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002278 if (Record.size() != 2) {
2279 Error("Incorrect encoding of extended qualifier type");
2280 return QualType();
2281 }
Douglas Gregor455b8f42009-04-15 22:00:08 +00002282 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00002283 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2284 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00002285 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002286
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002287 case pch::TYPE_COMPLEX: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002288 if (Record.size() != 1) {
2289 Error("Incorrect encoding of complex type");
2290 return QualType();
2291 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002292 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002293 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002294 }
2295
2296 case pch::TYPE_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002297 if (Record.size() != 1) {
2298 Error("Incorrect encoding of pointer type");
2299 return QualType();
2300 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002301 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002302 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002303 }
2304
2305 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002306 if (Record.size() != 1) {
2307 Error("Incorrect encoding of block pointer type");
2308 return QualType();
2309 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002310 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002311 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002312 }
2313
2314 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002315 if (Record.size() != 1) {
2316 Error("Incorrect encoding of lvalue reference type");
2317 return QualType();
2318 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002319 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002320 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002321 }
2322
2323 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002324 if (Record.size() != 1) {
2325 Error("Incorrect encoding of rvalue reference type");
2326 return QualType();
2327 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002328 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002329 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002330 }
2331
2332 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidisee776bc2010-07-02 11:55:15 +00002333 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002334 Error("Incorrect encoding of member pointer type");
2335 return QualType();
2336 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002337 QualType PointeeType = GetType(Record[0]);
2338 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002339 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002340 }
2341
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002342 case pch::TYPE_CONSTANT_ARRAY: {
2343 QualType ElementType = GetType(Record[0]);
2344 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2345 unsigned IndexTypeQuals = Record[2];
2346 unsigned Idx = 3;
2347 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00002348 return Context->getConstantArrayType(ElementType, Size,
2349 ASM, IndexTypeQuals);
2350 }
2351
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002352 case pch::TYPE_INCOMPLETE_ARRAY: {
2353 QualType ElementType = GetType(Record[0]);
2354 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2355 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00002356 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002357 }
2358
2359 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002360 QualType ElementType = GetType(Record[0]);
2361 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2362 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00002363 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2364 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Sebastian Redlc67764e2010-07-22 22:43:28 +00002365 return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
Douglas Gregor04318252009-07-06 15:59:29 +00002366 ASM, IndexTypeQuals,
2367 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002368 }
2369
2370 case pch::TYPE_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002371 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002372 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002373 return QualType();
2374 }
2375
2376 QualType ElementType = GetType(Record[0]);
2377 unsigned NumElements = Record[1];
Chris Lattner37141f42010-06-23 06:00:24 +00002378 unsigned AltiVecSpec = Record[2];
2379 return Context->getVectorType(ElementType, NumElements,
2380 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002381 }
2382
2383 case pch::TYPE_EXT_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002384 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002385 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002386 return QualType();
2387 }
2388
2389 QualType ElementType = GetType(Record[0]);
2390 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00002391 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002392 }
2393
2394 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002395 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002396 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002397 return QualType();
2398 }
2399 QualType ResultType = GetType(Record[0]);
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002400 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002401 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002402 }
2403
2404 case pch::TYPE_FUNCTION_PROTO: {
2405 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00002406 bool NoReturn = Record[1];
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002407 unsigned RegParm = Record[2];
2408 CallingConv CallConv = (CallingConv)Record[3];
2409 unsigned Idx = 4;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002410 unsigned NumParams = Record[Idx++];
2411 llvm::SmallVector<QualType, 16> ParamTypes;
2412 for (unsigned I = 0; I != NumParams; ++I)
2413 ParamTypes.push_back(GetType(Record[Idx++]));
2414 bool isVariadic = Record[Idx++];
2415 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002416 bool hasExceptionSpec = Record[Idx++];
2417 bool hasAnyExceptionSpec = Record[Idx++];
2418 unsigned NumExceptions = Record[Idx++];
2419 llvm::SmallVector<QualType, 2> Exceptions;
2420 for (unsigned I = 0; I != NumExceptions; ++I)
2421 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00002422 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002423 isVariadic, Quals, hasExceptionSpec,
2424 hasAnyExceptionSpec, NumExceptions,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002425 Exceptions.data(),
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002426 FunctionType::ExtInfo(NoReturn, RegParm,
2427 CallConv));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002428 }
2429
John McCallb96ec562009-12-04 22:46:56 +00002430 case pch::TYPE_UNRESOLVED_USING:
2431 return Context->getTypeDeclType(
2432 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2433
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002434 case pch::TYPE_TYPEDEF: {
2435 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002436 Error("incorrect encoding of typedef type");
2437 return QualType();
2438 }
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002439 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2440 QualType Canonical = GetType(Record[1]);
2441 return Context->getTypedefType(Decl, Canonical);
2442 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002443
2444 case pch::TYPE_TYPEOF_EXPR:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002445 return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002446
2447 case pch::TYPE_TYPEOF: {
2448 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002449 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002450 return QualType();
2451 }
2452 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002453 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002454 }
Mike Stump11289f42009-09-09 15:08:12 +00002455
Anders Carlsson81df7b82009-06-24 19:06:50 +00002456 case pch::TYPE_DECLTYPE:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002457 return Context->getDecltypeType(ReadExpr(DeclsCursor));
Anders Carlsson81df7b82009-06-24 19:06:50 +00002458
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002459 case pch::TYPE_RECORD: {
2460 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002461 Error("incorrect encoding of record type");
2462 return QualType();
2463 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002464 bool IsDependent = Record[0];
2465 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2466 T->Dependent = IsDependent;
2467 return T;
2468 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002469
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002470 case pch::TYPE_ENUM: {
2471 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002472 Error("incorrect encoding of enum type");
2473 return QualType();
2474 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002475 bool IsDependent = Record[0];
2476 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2477 T->Dependent = IsDependent;
2478 return T;
2479 }
Douglas Gregor1daeb692009-04-13 18:14:40 +00002480
John McCallfcc33b02009-09-05 00:15:47 +00002481 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002482 unsigned Idx = 0;
2483 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2484 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2485 QualType NamedType = GetType(Record[Idx++]);
2486 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCallfcc33b02009-09-05 00:15:47 +00002487 }
2488
Steve Naroffc277ad12009-07-18 15:33:26 +00002489 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00002490 unsigned Idx = 0;
2491 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002492 return Context->getObjCInterfaceType(ItfD);
2493 }
2494
2495 case pch::TYPE_OBJC_OBJECT: {
2496 unsigned Idx = 0;
2497 QualType Base = GetType(Record[Idx++]);
Chris Lattner587cbe12009-04-22 06:45:28 +00002498 unsigned NumProtos = Record[Idx++];
2499 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2500 for (unsigned I = 0; I != NumProtos; ++I)
2501 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCall8b07ec22010-05-15 11:32:37 +00002502 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00002503 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002504
Steve Narofffb4330f2009-06-17 22:40:22 +00002505 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00002506 unsigned Idx = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002507 QualType Pointee = GetType(Record[Idx++]);
2508 return Context->getObjCObjectPointerType(Pointee);
Chris Lattner6e054af2009-04-22 06:40:03 +00002509 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00002510
John McCallcebee162009-10-18 09:09:24 +00002511 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2512 unsigned Idx = 0;
2513 QualType Parm = GetType(Record[Idx++]);
2514 QualType Replacement = GetType(Record[Idx++]);
2515 return
2516 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2517 Replacement);
2518 }
John McCalle78aac42010-03-10 03:28:59 +00002519
2520 case pch::TYPE_INJECTED_CLASS_NAME: {
2521 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2522 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidisdab33c52010-07-02 11:55:20 +00002523 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2524 // for PCH reading, too much interdependencies.
2525 return
2526 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCalle78aac42010-03-10 03:28:59 +00002527 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002528
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002529 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2530 unsigned Idx = 0;
2531 unsigned Depth = Record[Idx++];
2532 unsigned Index = Record[Idx++];
2533 bool Pack = Record[Idx++];
2534 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2535 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2536 }
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002537
2538 case pch::TYPE_DEPENDENT_NAME: {
2539 unsigned Idx = 0;
2540 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2541 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2542 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidise9290952010-07-02 11:55:24 +00002543 QualType Canon = GetType(Record[Idx++]);
2544 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002545 }
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002546
2547 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2548 unsigned Idx = 0;
2549 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2550 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2551 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2552 unsigned NumArgs = Record[Idx++];
2553 llvm::SmallVector<TemplateArgument, 8> Args;
2554 Args.reserve(NumArgs);
2555 while (NumArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00002556 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002557 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2558 Args.size(), Args.data());
2559 }
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00002560
2561 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2562 unsigned Idx = 0;
2563
2564 // ArrayType
2565 QualType ElementType = GetType(Record[Idx++]);
2566 ArrayType::ArraySizeModifier ASM
2567 = (ArrayType::ArraySizeModifier)Record[Idx++];
2568 unsigned IndexTypeQuals = Record[Idx++];
2569
2570 // DependentSizedArrayType
Sebastian Redlc67764e2010-07-22 22:43:28 +00002571 Expr *NumElts = ReadExpr(DeclsCursor);
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00002572 SourceRange Brackets = ReadSourceRange(Record, Idx);
2573
2574 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2575 IndexTypeQuals, Brackets);
2576 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002577
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002578 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2579 unsigned Idx = 0;
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002580 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002581 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002582 llvm::SmallVector<TemplateArgument, 8> Args;
Sebastian Redlc67764e2010-07-22 22:43:28 +00002583 ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00002584 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002585 QualType T;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002586 if (Canon.isNull())
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002587 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2588 Args.size());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002589 else
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002590 T = Context->getTemplateSpecializationType(Name, Args.data(),
2591 Args.size(), Canon);
2592 T->Dependent = IsDependent;
2593 return T;
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002594 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002595 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002596 // Suppress a GCC warning
2597 return QualType();
2598}
2599
John McCall8f115c62009-10-16 21:56:05 +00002600namespace {
2601
2602class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2603 PCHReader &Reader;
Sebastian Redlc67764e2010-07-22 22:43:28 +00002604 llvm::BitstreamCursor &DeclsCursor;
John McCall8f115c62009-10-16 21:56:05 +00002605 const PCHReader::RecordData &Record;
2606 unsigned &Idx;
2607
2608public:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002609 TypeLocReader(PCHReader &Reader, llvm::BitstreamCursor &Cursor,
2610 const PCHReader::RecordData &Record, unsigned &Idx)
2611 : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
John McCall8f115c62009-10-16 21:56:05 +00002612
John McCall17001972009-10-18 01:05:36 +00002613 // We want compile-time assurance that we've enumerated all of
2614 // these, so unfortunately we have to declare them first, then
2615 // define them out-of-line.
2616#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002617#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002618 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002619#include "clang/AST/TypeLocNodes.def"
2620
John McCall17001972009-10-18 01:05:36 +00002621 void VisitFunctionTypeLoc(FunctionTypeLoc);
2622 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002623};
2624
2625}
2626
John McCall17001972009-10-18 01:05:36 +00002627void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002628 // nothing to do
2629}
John McCall17001972009-10-18 01:05:36 +00002630void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +00002631 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2632 if (TL.needsExtraLocalData()) {
2633 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2634 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2635 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2636 TL.setModeAttr(Record[Idx++]);
2637 }
John McCall8f115c62009-10-16 21:56:05 +00002638}
John McCall17001972009-10-18 01:05:36 +00002639void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2640 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002641}
John McCall17001972009-10-18 01:05:36 +00002642void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2643 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002644}
John McCall17001972009-10-18 01:05:36 +00002645void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2646 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002647}
John McCall17001972009-10-18 01:05:36 +00002648void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2649 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002650}
John McCall17001972009-10-18 01:05:36 +00002651void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2652 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002653}
John McCall17001972009-10-18 01:05:36 +00002654void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2655 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002656}
John McCall17001972009-10-18 01:05:36 +00002657void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2658 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2659 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002660 if (Record[Idx++])
Sebastian Redlc67764e2010-07-22 22:43:28 +00002661 TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
Douglas Gregor12bfa382009-10-17 00:13:19 +00002662 else
John McCall17001972009-10-18 01:05:36 +00002663 TL.setSizeExpr(0);
2664}
2665void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2666 VisitArrayTypeLoc(TL);
2667}
2668void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2669 VisitArrayTypeLoc(TL);
2670}
2671void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2672 VisitArrayTypeLoc(TL);
2673}
2674void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2675 DependentSizedArrayTypeLoc TL) {
2676 VisitArrayTypeLoc(TL);
2677}
2678void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2679 DependentSizedExtVectorTypeLoc TL) {
2680 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2681}
2682void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2683 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2684}
2685void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2686 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2687}
2688void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2689 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2690 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2691 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002692 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002693 }
2694}
2695void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2696 VisitFunctionTypeLoc(TL);
2697}
2698void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2699 VisitFunctionTypeLoc(TL);
2700}
John McCallb96ec562009-12-04 22:46:56 +00002701void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2702 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2703}
John McCall17001972009-10-18 01:05:36 +00002704void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2705 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2706}
2707void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002708 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2709 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2710 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002711}
2712void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002713 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2714 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2715 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Sebastian Redlc67764e2010-07-22 22:43:28 +00002716 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002717}
2718void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2719 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2720}
2721void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2722 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2723}
2724void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2725 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2726}
John McCall17001972009-10-18 01:05:36 +00002727void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2728 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2729}
John McCallcebee162009-10-18 09:09:24 +00002730void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2731 SubstTemplateTypeParmTypeLoc TL) {
2732 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2733}
John McCall17001972009-10-18 01:05:36 +00002734void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2735 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002736 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2737 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2738 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2739 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2740 TL.setArgLocInfo(i,
2741 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002742 DeclsCursor, Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002743}
Abramo Bagnara6150c882010-05-11 21:36:43 +00002744void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002745 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2746 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002747}
John McCalle78aac42010-03-10 03:28:59 +00002748void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2749 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2750}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002751void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002752 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2753 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002754 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2755}
John McCallc392f372010-06-11 00:33:02 +00002756void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2757 DependentTemplateSpecializationTypeLoc TL) {
2758 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2759 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2760 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2761 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2762 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2763 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2764 TL.setArgLocInfo(I,
2765 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002766 DeclsCursor, Record, Idx));
John McCallc392f372010-06-11 00:33:02 +00002767}
John McCall17001972009-10-18 01:05:36 +00002768void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2769 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002770}
2771void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2772 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall17001972009-10-18 01:05:36 +00002773 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2774 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2775 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2776 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002777}
John McCallfc93cf92009-10-22 22:37:11 +00002778void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2779 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallfc93cf92009-10-22 22:37:11 +00002780}
John McCall8f115c62009-10-16 21:56:05 +00002781
Sebastian Redlc67764e2010-07-22 22:43:28 +00002782TypeSourceInfo *PCHReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2783 const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002784 unsigned &Idx) {
2785 QualType InfoTy = GetType(Record[Idx++]);
2786 if (InfoTy.isNull())
2787 return 0;
2788
John McCallbcd03502009-12-07 02:54:59 +00002789 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
Sebastian Redlc67764e2010-07-22 22:43:28 +00002790 TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002791 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002792 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002793 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002794}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002795
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002796QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002797 unsigned FastQuals = ID & Qualifiers::FastMask;
2798 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002799
2800 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2801 QualType T;
2802 switch ((pch::PredefinedTypeIDs)Index) {
2803 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002804 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2805 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002806
2807 case pch::PREDEF_TYPE_CHAR_U_ID:
2808 case pch::PREDEF_TYPE_CHAR_S_ID:
2809 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002810 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002811 break;
2812
Chris Lattner8575daa2009-04-27 21:45:14 +00002813 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2814 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2815 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2816 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2817 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002818 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002819 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2820 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2821 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2822 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2823 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2824 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002825 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002826 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2827 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2828 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2829 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2830 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002831 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002832 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2833 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002834 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2835 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002836 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002837 }
2838
2839 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002840 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002841 }
2842
2843 Index -= pch::NUM_PREDEF_TYPE_IDS;
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002844 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl409183f2010-07-14 20:26:45 +00002845 if (TypesLoaded[Index].isNull()) {
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002846 TypesLoaded[Index] = ReadTypeRecord(Index);
Sebastian Redl409183f2010-07-14 20:26:45 +00002847 TypesLoaded[Index]->setFromPCH();
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002848 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002849 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2850 TypesLoaded[Index]);
Sebastian Redl409183f2010-07-14 20:26:45 +00002851 }
Mike Stump11289f42009-09-09 15:08:12 +00002852
John McCall8ccfcb52009-09-24 19:53:00 +00002853 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002854}
2855
John McCall0ad16662009-10-29 08:12:44 +00002856TemplateArgumentLocInfo
2857PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Sebastian Redlc67764e2010-07-22 22:43:28 +00002858 llvm::BitstreamCursor &DeclsCursor,
John McCall0ad16662009-10-29 08:12:44 +00002859 const RecordData &Record,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002860 unsigned &Index) {
John McCall0ad16662009-10-29 08:12:44 +00002861 switch (Kind) {
2862 case TemplateArgument::Expression:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002863 return ReadExpr(DeclsCursor);
John McCall0ad16662009-10-29 08:12:44 +00002864 case TemplateArgument::Type:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002865 return GetTypeSourceInfo(DeclsCursor, Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002866 case TemplateArgument::Template: {
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002867 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2868 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2869 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002870 }
John McCall0ad16662009-10-29 08:12:44 +00002871 case TemplateArgument::Null:
2872 case TemplateArgument::Integral:
2873 case TemplateArgument::Declaration:
2874 case TemplateArgument::Pack:
2875 return TemplateArgumentLocInfo();
2876 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002877 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002878 return TemplateArgumentLocInfo();
2879}
2880
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002881TemplateArgumentLoc
Sebastian Redlc67764e2010-07-22 22:43:28 +00002882PCHReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
2883 const RecordData &Record, unsigned &Index) {
2884 TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002885
2886 if (Arg.getKind() == TemplateArgument::Expression) {
2887 if (Record[Index++]) // bool InfoHasSameExpr.
2888 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2889 }
2890 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002891 DeclsCursor,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002892 Record, Index));
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00002893}
2894
John McCall75b960e2010-06-01 09:23:16 +00002895Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2896 return GetDecl(ID);
2897}
2898
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002899TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002900 if (!DeclsLoaded[0]) {
Argyrios Kyrtzidis839bbac2010-08-03 17:30:10 +00002901 ReadDeclRecord(0, 0);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002902 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002903 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002904 }
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002905
2906 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2907}
2908
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002909Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002910 if (ID == 0)
2911 return 0;
2912
Douglas Gregor745ed142009-04-25 18:35:21 +00002913 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002914 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002915 return 0;
2916 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002917
Douglas Gregor745ed142009-04-25 18:35:21 +00002918 unsigned Index = ID - 1;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002919 if (!DeclsLoaded[Index]) {
Argyrios Kyrtzidis839bbac2010-08-03 17:30:10 +00002920 ReadDeclRecord(Index, ID);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002921 if (DeserializationListener)
2922 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2923 }
Douglas Gregor745ed142009-04-25 18:35:21 +00002924
2925 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002926}
2927
Chris Lattner9c28af02009-04-27 05:46:25 +00002928/// \brief Resolve the offset of a statement into a statement.
2929///
2930/// This operation will read a new statement from the external
2931/// source each time it is called, and is meant to be used via a
2932/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall75b960e2010-06-01 09:23:16 +00002933Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Sebastian Redl5c415f32010-07-22 17:01:13 +00002934 // Offset here is a global offset across the entire chain.
2935 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2936 PerFileData &F = *Chain[N - I - 1];
2937 if (Offset < F.SizeInBits) {
2938 // Since we know that this statement is part of a decl, make sure to use
2939 // the decl cursor to read it.
2940 F.DeclsCursor.JumpToBit(Offset);
2941 return ReadStmtFromStream(F.DeclsCursor);
2942 }
2943 Offset -= F.SizeInBits;
2944 }
2945 llvm_unreachable("Broken chain");
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002946}
2947
John McCall75b960e2010-06-01 09:23:16 +00002948bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2949 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002950 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002951 "DeclContext has no lexical decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002952
Sebastian Redl5c415f32010-07-22 17:01:13 +00002953 // There might be lexical decls in multiple parts of the chain, for the TU
2954 // at least.
2955 DeclContextInfos &Infos = DeclContextOffsets[DC];
2956 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2957 I != E; ++I) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002958 // IDs can be 0 if this context doesn't contain declarations.
2959 if (!I->LexicalDecls)
Sebastian Redl5c415f32010-07-22 17:01:13 +00002960 continue;
Sebastian Redl5c415f32010-07-22 17:01:13 +00002961
2962 // Load all of the declaration IDs
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002963 for (const pch::DeclID *ID = I->LexicalDecls,
2964 *IDE = ID + I->NumLexicalDecls;
2965 ID != IDE; ++ID)
2966 Decls.push_back(GetDecl(*ID));
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002967 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002968
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002969 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002970 return false;
2971}
2972
John McCall75b960e2010-06-01 09:23:16 +00002973DeclContext::lookup_result
2974PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2975 DeclarationName Name) {
Mike Stump11289f42009-09-09 15:08:12 +00002976 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002977 "DeclContext has no visible decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002978
John McCall75b960e2010-06-01 09:23:16 +00002979 llvm::SmallVector<VisibleDeclaration, 64> Decls;
Sebastian Redl5c415f32010-07-22 17:01:13 +00002980 // There might be lexical decls in multiple parts of the chain, for the TU
2981 // and namespaces.
2982 DeclContextInfos &Infos = DeclContextOffsets[DC];
2983 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2984 I != E; ++I) {
2985 uint64_t Offset = I->OffsetToVisibleDecls;
2986 if (Offset == 0)
2987 continue;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002988
Sebastian Redl5c415f32010-07-22 17:01:13 +00002989 llvm::BitstreamCursor &DeclsCursor = *I->Stream;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002990
Sebastian Redl5c415f32010-07-22 17:01:13 +00002991 // Keep track of where we are in the stream, then jump back there
2992 // after reading this context.
2993 SavedStreamPosition SavedPosition(DeclsCursor);
2994
2995 // Load the record containing all of the declarations visible in
2996 // this context.
2997 DeclsCursor.JumpToBit(Offset);
2998 RecordData Record;
2999 unsigned Code = DeclsCursor.ReadCode();
3000 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
3001 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
3002 Error("Expected visible block");
3003 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
3004 DeclContext::lookup_iterator());
3005 }
3006
3007 if (Record.empty())
3008 continue;
3009
3010 unsigned Idx = 0;
3011 while (Idx < Record.size()) {
3012 Decls.push_back(VisibleDeclaration());
3013 Decls.back().Name = ReadDeclarationName(Record, Idx);
3014
3015 unsigned Size = Record[Idx++];
3016 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
3017 LoadedDecls.reserve(Size);
3018 for (unsigned J = 0; J < Size; ++J)
3019 LoadedDecls.push_back(Record[Idx++]);
3020 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003021 }
3022
Douglas Gregora57c3ab2009-04-22 22:34:57 +00003023 ++NumVisibleDeclContextsRead;
John McCall75b960e2010-06-01 09:23:16 +00003024
3025 SetExternalVisibleDecls(DC, Decls);
3026 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003027}
3028
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003029void PCHReader::PassInterestingDeclsToConsumer() {
3030 assert(Consumer);
3031 while (!InterestingDecls.empty()) {
3032 DeclGroupRef DG(InterestingDecls.front());
3033 InterestingDecls.pop_front();
Sebastian Redleaa4ade2010-08-11 18:52:41 +00003034 Consumer->HandleInterestingDecl(DG);
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003035 }
3036}
3037
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003038void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00003039 this->Consumer = Consumer;
3040
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003041 if (!Consumer)
3042 return;
3043
3044 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003045 // Force deserialization of this decl, which will cause it to be queued for
3046 // passing to the consumer.
Daniel Dunbar865c2a72009-09-17 03:06:44 +00003047 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003048 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00003049
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003050 PassInterestingDeclsToConsumer();
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003051}
3052
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003053void PCHReader::PrintStats() {
3054 std::fprintf(stderr, "*** PCH Statistics:\n");
3055
Mike Stump11289f42009-09-09 15:08:12 +00003056 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00003057 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00003058 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00003059 unsigned NumDeclsLoaded
3060 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3061 (Decl *)0);
3062 unsigned NumIdentifiersLoaded
3063 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3064 IdentifiersLoaded.end(),
3065 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00003066 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00003067 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3068 SelectorsLoaded.end(),
3069 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00003070
Douglas Gregorc5046832009-04-27 18:38:38 +00003071 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
3072 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00003073 if (TotalNumSLocEntries)
3074 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
3075 NumSLocEntriesRead, TotalNumSLocEntries,
3076 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00003077 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003078 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00003079 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3080 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3081 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003082 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00003083 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3084 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00003085 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003086 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00003087 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3088 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Sebastian Redlada023c2010-08-04 20:40:17 +00003089 if (!SelectorsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003090 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
Sebastian Redlada023c2010-08-04 20:40:17 +00003091 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
3092 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003093 if (TotalNumStatements)
3094 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3095 NumStatementsRead, TotalNumStatements,
3096 ((float)NumStatementsRead/TotalNumStatements * 100));
3097 if (TotalNumMacros)
3098 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3099 NumMacrosRead, TotalNumMacros,
3100 ((float)NumMacrosRead/TotalNumMacros * 100));
3101 if (TotalLexicalDeclContexts)
3102 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3103 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3104 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3105 * 100));
3106 if (TotalVisibleDeclContexts)
3107 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3108 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3109 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3110 * 100));
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003111 if (TotalNumMethodPoolEntries) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00003112 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003113 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
3114 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
Douglas Gregor95c13f52009-04-25 17:48:32 +00003115 * 100));
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003116 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
Douglas Gregor95c13f52009-04-25 17:48:32 +00003117 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003118 std::fprintf(stderr, "\n");
3119}
3120
Douglas Gregora868bbd2009-04-21 22:25:48 +00003121void PCHReader::InitializeSema(Sema &S) {
3122 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003123 S.ExternalSource = this;
3124
Douglas Gregor7cd60f72009-04-22 21:15:06 +00003125 // Makes sure any declarations that were deserialized "too early"
3126 // still get added to the identifier's declaration chains.
3127 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3128 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3129 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003130 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00003131 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00003132
3133 // If there were any tentative definitions, deserialize them and add
Sebastian Redl35351a92010-01-31 22:27:38 +00003134 // them to Sema's list of tentative definitions.
Douglas Gregord4df8652009-04-22 22:02:47 +00003135 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3136 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redl35351a92010-01-31 22:27:38 +00003137 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregord4df8652009-04-22 22:02:47 +00003138 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00003139
Tanya Lattner90073802010-02-12 00:07:30 +00003140 // If there were any unused static functions, deserialize them and add to
3141 // Sema's list of unused static functions.
3142 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
3143 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3144 SemaObj->UnusedStaticFuncs.push_back(FD);
3145 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00003146
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00003147 // If there were any weak undeclared identifiers, deserialize them and add to
3148 // Sema's list of weak undeclared identifiers.
3149 if (!WeakUndeclaredIdentifiers.empty()) {
3150 unsigned Idx = 0;
3151 for (unsigned I = 0, N = WeakUndeclaredIdentifiers[Idx++]; I != N; ++I) {
3152 IdentifierInfo *WeakId = GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
3153 IdentifierInfo *AliasId=GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
3154 SourceLocation Loc = ReadSourceLocation(WeakUndeclaredIdentifiers, Idx);
3155 bool Used = WeakUndeclaredIdentifiers[Idx++];
3156 Sema::WeakInfo WI(AliasId, Loc);
3157 WI.setUsed(Used);
3158 SemaObj->WeakUndeclaredIdentifiers.insert(std::make_pair(WeakId, WI));
3159 }
3160 }
3161
Douglas Gregoracfc76c2009-04-22 22:18:58 +00003162 // If there were any locally-scoped external declarations,
3163 // deserialize them and add them to Sema's table of locally-scoped
3164 // external declarations.
3165 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3166 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3167 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3168 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00003169
3170 // If there were any ext_vector type declarations, deserialize them
3171 // and add them to Sema's vector of such declarations.
3172 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3173 SemaObj->ExtVectorDecls.push_back(
3174 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00003175
3176 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3177 // Can we cut them down before writing them ?
3178
3179 // If there were any VTable uses, deserialize the information and add it
3180 // to Sema's vector and map of VTable uses.
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00003181 if (!VTableUses.empty()) {
3182 unsigned Idx = 0;
3183 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3184 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3185 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3186 bool DefinitionRequired = VTableUses[Idx++];
3187 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3188 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3189 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00003190 }
3191
3192 // If there were any dynamic classes declarations, deserialize them
3193 // and add them to Sema's vector of such declarations.
3194 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3195 SemaObj->DynamicClasses.push_back(
3196 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003197
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00003198 // If there were any pending implicit instantiations, deserialize them
3199 // and add them to Sema's queue of such instantiations.
3200 assert(PendingImplicitInstantiations.size() % 2 == 0 &&
3201 "Expected pairs of entries");
3202 for (unsigned Idx = 0, N = PendingImplicitInstantiations.size(); Idx < N;) {
3203 ValueDecl *D=cast<ValueDecl>(GetDecl(PendingImplicitInstantiations[Idx++]));
3204 SourceLocation Loc = ReadSourceLocation(PendingImplicitInstantiations, Idx);
3205 SemaObj->PendingImplicitInstantiations.push_back(std::make_pair(D, Loc));
3206 }
3207
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003208 // Load the offsets of the declarations that Sema references.
3209 // They will be lazily deserialized when needed.
3210 if (!SemaDeclRefs.empty()) {
3211 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
3212 SemaObj->StdNamespace = SemaDeclRefs[0];
3213 SemaObj->StdBadAlloc = SemaDeclRefs[1];
3214 }
3215
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003216 // If there are @selector references added them to its pool. This is for
3217 // implementation of -Wselector.
Sebastian Redlada023c2010-08-04 20:40:17 +00003218 if (!ReferencedSelectorsData.empty()) {
3219 unsigned int DataSize = ReferencedSelectorsData.size()-1;
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003220 unsigned I = 0;
3221 while (I < DataSize) {
Sebastian Redlada023c2010-08-04 20:40:17 +00003222 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003223 SourceLocation SelLoc =
Sebastian Redlada023c2010-08-04 20:40:17 +00003224 SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003225 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3226 }
3227 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00003228}
3229
3230IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
Sebastian Redl78f51772010-08-02 18:30:12 +00003231 // Try to find this name within our on-disk hash tables. We start with the
3232 // most recent one, since that one contains the most up-to-date info.
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003233 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3234 PCHIdentifierLookupTable *IdTable
Sebastian Redl78f51772010-08-02 18:30:12 +00003235 = (PCHIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
Sebastian Redl5c415f32010-07-22 17:01:13 +00003236 if (!IdTable)
3237 continue;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003238 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3239 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3240 if (Pos == IdTable->end())
3241 continue;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003242
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003243 // Dereferencing the iterator has the effect of building the
3244 // IdentifierInfo node and populating it with the various
3245 // declarations it needs.
Sebastian Redl78f51772010-08-02 18:30:12 +00003246 return *Pos;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003247 }
Sebastian Redl78f51772010-08-02 18:30:12 +00003248 return 0;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003249}
3250
Mike Stump11289f42009-09-09 15:08:12 +00003251std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00003252PCHReader::ReadMethodPool(Selector Sel) {
Sebastian Redlada023c2010-08-04 20:40:17 +00003253 // Find this selector in a hash table. We want to find the most recent entry.
3254 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3255 PerFileData &F = *Chain[I];
3256 if (!F.SelectorLookupTable)
3257 continue;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003258
Sebastian Redlada023c2010-08-04 20:40:17 +00003259 PCHSelectorLookupTable *PoolTable
3260 = (PCHSelectorLookupTable*)F.SelectorLookupTable;
3261 PCHSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
3262 if (Pos != PoolTable->end()) {
3263 ++NumSelectorsRead;
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003264 // FIXME: Not quite happy with the statistics here. We probably should
3265 // disable this tracking when called via LoadSelector.
3266 // Also, should entries without methods count as misses?
3267 ++NumMethodPoolEntriesRead;
Sebastian Redlada023c2010-08-04 20:40:17 +00003268 PCHSelectorLookupTrait::data_type Data = *Pos;
3269 if (DeserializationListener)
3270 DeserializationListener->SelectorRead(Data.ID, Sel);
3271 return std::make_pair(Data.Instance, Data.Factory);
3272 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003273 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003274
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003275 ++NumMethodPoolMisses;
Sebastian Redlada023c2010-08-04 20:40:17 +00003276 return std::pair<ObjCMethodList, ObjCMethodList>();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003277}
3278
Sebastian Redld95a56e2010-08-04 18:21:41 +00003279void PCHReader::LoadSelector(Selector Sel) {
3280 // It would be complicated to avoid reading the methods anyway. So don't.
3281 ReadMethodPool(Sel);
3282}
3283
Douglas Gregor0e149972009-04-25 19:10:14 +00003284void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00003285 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003286 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00003287 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlff4a2952010-07-23 23:49:55 +00003288 if (DeserializationListener)
3289 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003290}
3291
Douglas Gregor1342e842009-07-06 18:54:52 +00003292/// \brief Set the globally-visible declarations associated with the given
3293/// identifier.
3294///
3295/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00003296/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00003297/// them.
3298///
3299/// \param II an IdentifierInfo that refers to one or more globally-visible
3300/// declarations.
3301///
3302/// \param DeclIDs the set of declaration IDs with the name @p II that are
3303/// visible at global scope.
3304///
3305/// \param Nonrecursive should be true to indicate that the caller knows that
3306/// this call is non-recursive, and therefore the globally-visible declarations
3307/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00003308void
3309PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00003310 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3311 bool Nonrecursive) {
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003312 if (NumCurrentElementsDeserializing && !Nonrecursive) {
Douglas Gregor1342e842009-07-06 18:54:52 +00003313 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3314 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3315 PII.II = II;
3316 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3317 PII.DeclIDs.push_back(DeclIDs[I]);
3318 return;
3319 }
Mike Stump11289f42009-09-09 15:08:12 +00003320
Douglas Gregor1342e842009-07-06 18:54:52 +00003321 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3322 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3323 if (SemaObj) {
3324 // Introduce this declaration into the translation-unit scope
3325 // and add it to the declaration chain for this identifier, so
3326 // that (unqualified) name lookup will find it.
3327 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3328 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3329 } else {
3330 // Queue this declaration so that it will be added to the
3331 // translation unit scope and identifier's declaration chain
3332 // once a Sema object is known.
3333 PreloadedDecls.push_back(D);
3334 }
3335 }
3336}
3337
Chris Lattnerc523d8e2009-04-11 21:15:38 +00003338IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003339 if (ID == 0)
3340 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003341
Sebastian Redlc713b962010-07-21 00:46:22 +00003342 if (IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003343 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003344 return 0;
3345 }
Mike Stump11289f42009-09-09 15:08:12 +00003346
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003347 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redlc713b962010-07-21 00:46:22 +00003348 ID -= 1;
3349 if (!IdentifiersLoaded[ID]) {
3350 unsigned Index = ID;
3351 const char *Str = 0;
3352 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3353 PerFileData *F = Chain[N - I - 1];
3354 if (Index < F->LocalNumIdentifiers) {
3355 uint32_t Offset = F->IdentifierOffsets[Index];
3356 Str = F->IdentifierTableData + Offset;
3357 break;
3358 }
3359 Index -= F->LocalNumIdentifiers;
3360 }
3361 assert(Str && "Broken Chain");
Douglas Gregor5287b4e2009-04-25 21:04:17 +00003362
Douglas Gregorab4df582009-04-28 20:01:51 +00003363 // All of the strings in the PCH file are preceded by a 16-bit
3364 // length. Extract that 16-bit length to avoid having to execute
3365 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00003366 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3367 // unsigned integers. This is important to avoid integer overflow when
3368 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00003369 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00003370 unsigned StrLen = (((unsigned) StrLenPtr[0])
3371 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redlc713b962010-07-21 00:46:22 +00003372 IdentifiersLoaded[ID]
Kovarththanan Rajaratnama3b09592010-03-12 10:32:27 +00003373 = &PP->getIdentifierTable().get(Str, StrLen);
Sebastian Redlff4a2952010-07-23 23:49:55 +00003374 if (DeserializationListener)
3375 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003376 }
Mike Stump11289f42009-09-09 15:08:12 +00003377
Sebastian Redlc713b962010-07-21 00:46:22 +00003378 return IdentifiersLoaded[ID];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003379}
3380
Douglas Gregor258ae542009-04-27 06:38:32 +00003381void PCHReader::ReadSLocEntry(unsigned ID) {
3382 ReadSLocEntryRecord(ID);
3383}
3384
Steve Naroff2ddea052009-04-23 10:39:46 +00003385Selector PCHReader::DecodeSelector(unsigned ID) {
3386 if (ID == 0)
3387 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00003388
Sebastian Redlada023c2010-08-04 20:40:17 +00003389 if (ID > SelectorsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003390 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00003391 return Selector();
3392 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003393
Sebastian Redlada023c2010-08-04 20:40:17 +00003394 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00003395 // Load this selector from the selector table.
Sebastian Redlada023c2010-08-04 20:40:17 +00003396 unsigned Idx = ID - 1;
3397 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3398 PerFileData &F = *Chain[N - I - 1];
3399 if (Idx < F.LocalNumSelectors) {
3400 PCHSelectorLookupTrait Trait(*this);
3401 SelectorsLoaded[ID - 1] =
3402 Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0);
3403 if (DeserializationListener)
3404 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
3405 break;
3406 }
3407 Idx -= F.LocalNumSelectors;
3408 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003409 }
3410
Sebastian Redlada023c2010-08-04 20:40:17 +00003411 return SelectorsLoaded[ID - 1];
Steve Naroff2ddea052009-04-23 10:39:46 +00003412}
3413
John McCall75b960e2010-06-01 09:23:16 +00003414Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003415 return DecodeSelector(ID);
3416}
3417
John McCall75b960e2010-06-01 09:23:16 +00003418uint32_t PCHReader::GetNumExternalSelectors() {
Sebastian Redlada023c2010-08-04 20:40:17 +00003419 // ID 0 (the null selector) is considered an external selector.
3420 return getTotalNumSelectors() + 1;
Douglas Gregord720daf2010-04-06 17:30:22 +00003421}
3422
Mike Stump11289f42009-09-09 15:08:12 +00003423DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003424PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3425 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3426 switch (Kind) {
3427 case DeclarationName::Identifier:
3428 return DeclarationName(GetIdentifierInfo(Record, Idx));
3429
3430 case DeclarationName::ObjCZeroArgSelector:
3431 case DeclarationName::ObjCOneArgSelector:
3432 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00003433 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003434
3435 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003436 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003437 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003438
3439 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003440 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003441 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003442
3443 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003444 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003445 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003446
3447 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003448 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003449 (OverloadedOperatorKind)Record[Idx++]);
3450
Alexis Hunt3d221f22009-11-29 07:34:05 +00003451 case DeclarationName::CXXLiteralOperatorName:
3452 return Context->DeclarationNames.getCXXLiteralOperatorName(
3453 GetIdentifierInfo(Record, Idx));
3454
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003455 case DeclarationName::CXXUsingDirective:
3456 return DeclarationName::getUsingDirectiveName();
3457 }
3458
3459 // Required to silence GCC warning
3460 return DeclarationName();
3461}
Douglas Gregor55abb232009-04-10 20:39:37 +00003462
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003463TemplateName
3464PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3465 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3466 switch (Kind) {
3467 case TemplateName::Template:
3468 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3469
3470 case TemplateName::OverloadedTemplate: {
3471 unsigned size = Record[Idx++];
3472 UnresolvedSet<8> Decls;
3473 while (size--)
3474 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3475
3476 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3477 }
3478
3479 case TemplateName::QualifiedTemplate: {
3480 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3481 bool hasTemplKeyword = Record[Idx++];
3482 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3483 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3484 }
3485
3486 case TemplateName::DependentTemplate: {
3487 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3488 if (Record[Idx++]) // isIdentifier
3489 return Context->getDependentTemplateName(NNS,
3490 GetIdentifierInfo(Record, Idx));
3491 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00003492 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003493 }
3494 }
3495
3496 assert(0 && "Unhandled template name kind!");
3497 return TemplateName();
3498}
3499
3500TemplateArgument
Sebastian Redlc67764e2010-07-22 22:43:28 +00003501PCHReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3502 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003503 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3504 case TemplateArgument::Null:
3505 return TemplateArgument();
3506 case TemplateArgument::Type:
3507 return TemplateArgument(GetType(Record[Idx++]));
3508 case TemplateArgument::Declaration:
3509 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidis0b0369a2010-06-28 09:31:34 +00003510 case TemplateArgument::Integral: {
3511 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3512 QualType T = GetType(Record[Idx++]);
3513 return TemplateArgument(Value, T);
3514 }
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003515 case TemplateArgument::Template:
3516 return TemplateArgument(ReadTemplateName(Record, Idx));
3517 case TemplateArgument::Expression:
Sebastian Redlc67764e2010-07-22 22:43:28 +00003518 return TemplateArgument(ReadExpr(DeclsCursor));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003519 case TemplateArgument::Pack: {
3520 unsigned NumArgs = Record[Idx++];
3521 llvm::SmallVector<TemplateArgument, 8> Args;
3522 Args.reserve(NumArgs);
3523 while (NumArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00003524 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003525 TemplateArgument TemplArg;
3526 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3527 return TemplArg;
3528 }
3529 }
3530
3531 assert(0 && "Unhandled template argument kind!");
3532 return TemplateArgument();
3533}
3534
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003535TemplateParameterList *
3536PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3537 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3538 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3539 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3540
3541 unsigned NumParams = Record[Idx++];
3542 llvm::SmallVector<NamedDecl *, 16> Params;
3543 Params.reserve(NumParams);
3544 while (NumParams--)
3545 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3546
3547 TemplateParameterList* TemplateParams =
3548 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3549 Params.data(), Params.size(), RAngleLoc);
3550 return TemplateParams;
3551}
3552
3553void
3554PCHReader::
3555ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
Sebastian Redlc67764e2010-07-22 22:43:28 +00003556 llvm::BitstreamCursor &DeclsCursor,
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003557 const RecordData &Record, unsigned &Idx) {
3558 unsigned NumTemplateArgs = Record[Idx++];
3559 TemplArgs.reserve(NumTemplateArgs);
3560 while (NumTemplateArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00003561 TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003562}
3563
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00003564/// \brief Read a UnresolvedSet structure.
3565void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3566 const RecordData &Record, unsigned &Idx) {
3567 unsigned NumDecls = Record[Idx++];
3568 while (NumDecls--) {
3569 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3570 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3571 Set.addDecl(D, AS);
3572 }
3573}
3574
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003575CXXBaseSpecifier
Nick Lewycky19b9f952010-07-26 16:56:01 +00003576PCHReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
3577 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003578 bool isVirtual = static_cast<bool>(Record[Idx++]);
3579 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3580 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Nick Lewycky19b9f952010-07-26 16:56:01 +00003581 TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003582 SourceRange Range = ReadSourceRange(Record, Idx);
Nick Lewycky19b9f952010-07-26 16:56:01 +00003583 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003584}
3585
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00003586std::pair<CXXBaseOrMemberInitializer **, unsigned>
3587PCHReader::ReadCXXBaseOrMemberInitializers(llvm::BitstreamCursor &Cursor,
3588 const RecordData &Record,
3589 unsigned &Idx) {
3590 CXXBaseOrMemberInitializer **BaseOrMemberInitializers = 0;
3591 unsigned NumInitializers = Record[Idx++];
3592 if (NumInitializers) {
3593 ASTContext &C = *getContext();
3594
3595 BaseOrMemberInitializers
3596 = new (C) CXXBaseOrMemberInitializer*[NumInitializers];
3597 for (unsigned i=0; i != NumInitializers; ++i) {
3598 TypeSourceInfo *BaseClassInfo = 0;
3599 bool IsBaseVirtual = false;
3600 FieldDecl *Member = 0;
3601
3602 bool IsBaseInitializer = Record[Idx++];
3603 if (IsBaseInitializer) {
3604 BaseClassInfo = GetTypeSourceInfo(Cursor, Record, Idx);
3605 IsBaseVirtual = Record[Idx++];
3606 } else {
3607 Member = cast<FieldDecl>(GetDecl(Record[Idx++]));
3608 }
3609 SourceLocation MemberLoc = ReadSourceLocation(Record, Idx);
3610 Expr *Init = ReadExpr(Cursor);
3611 FieldDecl *AnonUnionMember
3612 = cast_or_null<FieldDecl>(GetDecl(Record[Idx++]));
3613 SourceLocation LParenLoc = ReadSourceLocation(Record, Idx);
3614 SourceLocation RParenLoc = ReadSourceLocation(Record, Idx);
3615 bool IsWritten = Record[Idx++];
3616 unsigned SourceOrderOrNumArrayIndices;
3617 llvm::SmallVector<VarDecl *, 8> Indices;
3618 if (IsWritten) {
3619 SourceOrderOrNumArrayIndices = Record[Idx++];
3620 } else {
3621 SourceOrderOrNumArrayIndices = Record[Idx++];
3622 Indices.reserve(SourceOrderOrNumArrayIndices);
3623 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
3624 Indices.push_back(cast<VarDecl>(GetDecl(Record[Idx++])));
3625 }
3626
3627 CXXBaseOrMemberInitializer *BOMInit;
3628 if (IsBaseInitializer) {
3629 BOMInit = new (C) CXXBaseOrMemberInitializer(C, BaseClassInfo,
3630 IsBaseVirtual, LParenLoc,
3631 Init, RParenLoc);
3632 } else if (IsWritten) {
3633 BOMInit = new (C) CXXBaseOrMemberInitializer(C, Member, MemberLoc,
3634 LParenLoc, Init, RParenLoc);
3635 } else {
3636 BOMInit = CXXBaseOrMemberInitializer::Create(C, Member, MemberLoc,
3637 LParenLoc, Init, RParenLoc,
3638 Indices.data(),
3639 Indices.size());
3640 }
3641
3642 BOMInit->setAnonUnionMember(AnonUnionMember);
3643 BaseOrMemberInitializers[i] = BOMInit;
3644 }
3645 }
3646
3647 return std::make_pair(BaseOrMemberInitializers, NumInitializers);
3648}
3649
Chris Lattnerca025db2010-05-07 21:43:38 +00003650NestedNameSpecifier *
3651PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3652 unsigned N = Record[Idx++];
3653 NestedNameSpecifier *NNS = 0, *Prev = 0;
3654 for (unsigned I = 0; I != N; ++I) {
3655 NestedNameSpecifier::SpecifierKind Kind
3656 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3657 switch (Kind) {
3658 case NestedNameSpecifier::Identifier: {
3659 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3660 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3661 break;
3662 }
3663
3664 case NestedNameSpecifier::Namespace: {
3665 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3666 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3667 break;
3668 }
3669
3670 case NestedNameSpecifier::TypeSpec:
3671 case NestedNameSpecifier::TypeSpecWithTemplate: {
3672 Type *T = GetType(Record[Idx++]).getTypePtr();
3673 bool Template = Record[Idx++];
3674 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3675 break;
3676 }
3677
3678 case NestedNameSpecifier::Global: {
3679 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3680 // No associated value, and there can't be a prefix.
3681 break;
3682 }
Chris Lattnerca025db2010-05-07 21:43:38 +00003683 }
Argyrios Kyrtzidisad65c692010-07-07 15:46:30 +00003684 Prev = NNS;
Chris Lattnerca025db2010-05-07 21:43:38 +00003685 }
3686 return NNS;
3687}
3688
3689SourceRange
3690PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar6d3bc082010-06-02 15:47:10 +00003691 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3692 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3693 return SourceRange(beg, end);
Chris Lattnerca025db2010-05-07 21:43:38 +00003694}
3695
Douglas Gregor1daeb692009-04-13 18:14:40 +00003696/// \brief Read an integral value
3697llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3698 unsigned BitWidth = Record[Idx++];
3699 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3700 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3701 Idx += NumWords;
3702 return Result;
3703}
3704
3705/// \brief Read a signed integral value
3706llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3707 bool isUnsigned = Record[Idx++];
3708 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3709}
3710
Douglas Gregore0a3a512009-04-14 21:55:33 +00003711/// \brief Read a floating-point value
3712llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00003713 return llvm::APFloat(ReadAPInt(Record, Idx));
3714}
3715
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003716// \brief Read a string
3717std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3718 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00003719 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003720 Idx += Len;
3721 return Result;
3722}
3723
Chris Lattnercba86142010-05-10 00:25:06 +00003724CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3725 unsigned &Idx) {
3726 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3727 return CXXTemporary::Create(*Context, Decl);
3728}
3729
Douglas Gregor55abb232009-04-10 20:39:37 +00003730DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00003731 return Diag(SourceLocation(), DiagID);
3732}
3733
3734DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003735 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00003736}
Douglas Gregora9af1d12009-04-17 00:04:06 +00003737
Douglas Gregora868bbd2009-04-21 22:25:48 +00003738/// \brief Retrieve the identifier table associated with the
3739/// preprocessor.
3740IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003741 assert(PP && "Forgot to set Preprocessor ?");
3742 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00003743}
3744
Douglas Gregora9af1d12009-04-17 00:04:06 +00003745/// \brief Record that the given ID maps to the given switch-case
3746/// statement.
3747void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3748 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3749 SwitchCaseStmts[ID] = SC;
3750}
3751
3752/// \brief Retrieve the switch-case statement with the given ID.
3753SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3754 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3755 return SwitchCaseStmts[ID];
3756}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003757
3758/// \brief Record that the given label statement has been
3759/// deserialized and has the given ID.
3760void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00003761 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003762 "Deserialized label twice");
3763 LabelStmts[ID] = S;
3764
3765 // If we've already seen any goto statements that point to this
3766 // label, resolve them now.
3767 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3768 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3769 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3770 Goto->second->setLabel(S);
3771 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00003772
3773 // If we've already seen any address-label statements that point to
3774 // this label, resolve them now.
3775 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00003776 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00003777 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00003778 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00003779 AddrLabel != AddrLabels.second; ++AddrLabel)
3780 AddrLabel->second->setLabel(S);
3781 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003782}
3783
3784/// \brief Set the label of the given statement to the label
3785/// identified by ID.
3786///
3787/// Depending on the order in which the label and other statements
3788/// referencing that label occur, this operation may complete
3789/// immediately (updating the statement) or it may queue the
3790/// statement to be back-patched later.
3791void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3792 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3793 if (Label != LabelStmts.end()) {
3794 // We've already seen this label, so set the label of the goto and
3795 // we're done.
3796 S->setLabel(Label->second);
3797 } else {
3798 // We haven't seen this label yet, so add this goto to the set of
3799 // unresolved goto statements.
3800 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3801 }
3802}
Douglas Gregor779d8652009-04-17 18:58:21 +00003803
3804/// \brief Set the label of the given expression to the label
3805/// identified by ID.
3806///
3807/// Depending on the order in which the label and other statements
3808/// referencing that label occur, this operation may complete
3809/// immediately (updating the statement) or it may queue the
3810/// statement to be back-patched later.
3811void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3812 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3813 if (Label != LabelStmts.end()) {
3814 // We've already seen this label, so set the label of the
3815 // label-address expression and we're done.
3816 S->setLabel(Label->second);
3817 } else {
3818 // We haven't seen this label yet, so add this label-address
3819 // expression to the set of unresolved label-address expressions.
3820 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3821 }
3822}
Douglas Gregor1342e842009-07-06 18:54:52 +00003823
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003824void PCHReader::FinishedDeserializing() {
3825 assert(NumCurrentElementsDeserializing &&
3826 "FinishedDeserializing not paired with StartedDeserializing");
3827 if (NumCurrentElementsDeserializing == 1) {
Douglas Gregor1342e842009-07-06 18:54:52 +00003828 // If any identifiers with corresponding top-level declarations have
3829 // been loaded, load those declarations now.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003830 while (!PendingIdentifierInfos.empty()) {
3831 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
3832 PendingIdentifierInfos.front().DeclIDs, true);
3833 PendingIdentifierInfos.pop_front();
Douglas Gregor1342e842009-07-06 18:54:52 +00003834 }
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003835
3836 // We are not in recursive loading, so it's safe to pass the "interesting"
3837 // decls to the consumer.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003838 if (Consumer)
3839 PassInterestingDeclsToConsumer();
Douglas Gregor1342e842009-07-06 18:54:52 +00003840 }
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003841 --NumCurrentElementsDeserializing;
Douglas Gregor1342e842009-07-06 18:54:52 +00003842}