blob: ffc12cc729bc6b2c92d7b1ab01821b2a44b0095b [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 Gregora868bbd2009-04-21 22:25:48 +000018#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
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),
424 NumMacrosRead(0), NumSelectorsRead(0), NumSelectorMisses(0),
425 TotalNumMacros(0), NumLexicalDeclContextsRead(0),
426 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
427 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000428 RelocatablePCH = false;
429}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000430
431PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000432 Diagnostic &Diags, const char *isysroot,
433 bool DisableValidation)
Sebastian Redl85b2a6a2010-07-14 23:45:08 +0000434 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
Sebastian Redl34522812010-07-16 17:50:48 +0000435 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
Sebastian Redlada023c2010-08-04 20:40:17 +0000436 isysroot(isysroot), DisableValidation(DisableValidation), NumStatHits(0),
437 NumStatMisses(0), NumSLocEntriesRead(0), TotalNumSLocEntries(0),
438 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
439 NumSelectorsRead(0), NumSelectorMisses(0), TotalNumMacros(0),
440 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
441 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
442 NumCurrentElementsDeserializing(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000443 RelocatablePCH = false;
444}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000445
Sebastian Redl34522812010-07-16 17:50:48 +0000446PCHReader::~PCHReader() {
447 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
448 delete Chain[e - i - 1];
449}
450
451PCHReader::PerFileData::PerFileData()
Sebastian Redl9e687992010-07-19 22:06:55 +0000452 : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
Sebastian Redlbd1b5be2010-07-19 22:28:42 +0000453 LocalNumDecls(0), DeclOffsets(0), LocalNumIdentifiers(0),
Sebastian Redlfa061442010-07-21 20:07:32 +0000454 IdentifierOffsets(0), IdentifierTableData(0), IdentifierLookupTable(0),
455 LocalNumMacroDefinitions(0), MacroDefinitionOffsets(0),
Sebastian Redlada023c2010-08-04 20:40:17 +0000456 NumPreallocatedPreprocessingEntities(0), SelectorLookupTable(0),
457 SelectorLookupTableData(0), SelectorOffsets(0), LocalNumSelectors(0)
Sebastian Redl34522812010-07-16 17:50:48 +0000458{}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000459
Sebastian Redl07a89a82010-07-30 00:29:29 +0000460void
461PCHReader::setDeserializationListener(PCHDeserializationListener *Listener) {
462 DeserializationListener = Listener;
463 if (DeserializationListener)
464 DeserializationListener->SetReader(this);
465}
466
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000467
Douglas Gregora868bbd2009-04-21 22:25:48 +0000468namespace {
Sebastian Redlada023c2010-08-04 20:40:17 +0000469class PCHSelectorLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000470 PCHReader &Reader;
471
472public:
Sebastian Redl834bb972010-08-04 17:20:04 +0000473 struct data_type {
474 pch::SelectorID ID;
475 ObjCMethodList Instance, Factory;
476 };
Douglas Gregorc78d3462009-04-24 21:10:55 +0000477
478 typedef Selector external_key_type;
479 typedef external_key_type internal_key_type;
480
Sebastian Redlada023c2010-08-04 20:40:17 +0000481 explicit PCHSelectorLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Douglas Gregorc78d3462009-04-24 21:10:55 +0000483 static bool EqualKey(const internal_key_type& a,
484 const internal_key_type& b) {
485 return a == b;
486 }
Mike Stump11289f42009-09-09 15:08:12 +0000487
Douglas Gregorc78d3462009-04-24 21:10:55 +0000488 static unsigned ComputeHash(Selector Sel) {
489 unsigned N = Sel.getNumArgs();
490 if (N == 0)
491 ++N;
492 unsigned R = 5381;
493 for (unsigned I = 0; I != N; ++I)
494 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000495 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000496 return R;
497 }
Mike Stump11289f42009-09-09 15:08:12 +0000498
Douglas Gregorc78d3462009-04-24 21:10:55 +0000499 // This hopefully will just get inlined and removed by the optimizer.
500 static const internal_key_type&
501 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000502
Douglas Gregorc78d3462009-04-24 21:10:55 +0000503 static std::pair<unsigned, unsigned>
504 ReadKeyDataLength(const unsigned char*& d) {
505 using namespace clang::io;
506 unsigned KeyLen = ReadUnalignedLE16(d);
507 unsigned DataLen = ReadUnalignedLE16(d);
508 return std::make_pair(KeyLen, DataLen);
509 }
Mike Stump11289f42009-09-09 15:08:12 +0000510
Douglas Gregor95c13f52009-04-25 17:48:32 +0000511 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000512 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000513 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000514 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000515 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000516 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
517 if (N == 0)
518 return SelTable.getNullarySelector(FirstII);
519 else if (N == 1)
520 return SelTable.getUnarySelector(FirstII);
521
522 llvm::SmallVector<IdentifierInfo *, 16> Args;
523 Args.push_back(FirstII);
524 for (unsigned I = 1; I != N; ++I)
525 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
526
Douglas Gregor038c3382009-05-22 22:45:36 +0000527 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000528 }
Mike Stump11289f42009-09-09 15:08:12 +0000529
Douglas Gregorc78d3462009-04-24 21:10:55 +0000530 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
531 using namespace clang::io;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000532
533 data_type Result;
534
Sebastian Redl834bb972010-08-04 17:20:04 +0000535 Result.ID = ReadUnalignedLE32(d);
536 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
537 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
538
Douglas Gregorc78d3462009-04-24 21:10:55 +0000539 // Load instance methods
540 ObjCMethodList *Prev = 0;
541 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000542 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000543 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Sebastian Redl834bb972010-08-04 17:20:04 +0000544 if (!Result.Instance.Method) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000545 // This is the first method, which is the easy case.
Sebastian Redl834bb972010-08-04 17:20:04 +0000546 Result.Instance.Method = Method;
547 Prev = &Result.Instance;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000548 continue;
549 }
550
Ted Kremenekda4abf12010-02-11 00:53:01 +0000551 ObjCMethodList *Mem =
552 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
553 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000554 Prev = Prev->Next;
555 }
556
557 // Load factory methods
558 Prev = 0;
559 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000560 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000561 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Sebastian Redl834bb972010-08-04 17:20:04 +0000562 if (!Result.Factory.Method) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000563 // This is the first method, which is the easy case.
Sebastian Redl834bb972010-08-04 17:20:04 +0000564 Result.Factory.Method = Method;
565 Prev = &Result.Factory;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000566 continue;
567 }
568
Ted Kremenekda4abf12010-02-11 00:53:01 +0000569 ObjCMethodList *Mem =
570 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
571 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000572 Prev = Prev->Next;
573 }
574
575 return Result;
576 }
577};
Mike Stump11289f42009-09-09 15:08:12 +0000578
579} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000580
581/// \brief The on-disk hash table used for the global method pool.
Sebastian Redlada023c2010-08-04 20:40:17 +0000582typedef OnDiskChainedHashTable<PCHSelectorLookupTrait>
583 PCHSelectorLookupTable;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000584
585namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000586class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000587 PCHReader &Reader;
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000588 llvm::BitstreamCursor &Stream;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000589
590 // If we know the IdentifierInfo in advance, it is here and we will
591 // not build a new one. Used when deserializing information about an
592 // identifier that was constructed before the PCH file was read.
593 IdentifierInfo *KnownII;
594
595public:
596 typedef IdentifierInfo * data_type;
597
598 typedef const std::pair<const char*, unsigned> external_key_type;
599
600 typedef external_key_type internal_key_type;
601
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000602 PCHIdentifierLookupTrait(PCHReader &Reader, llvm::BitstreamCursor &Stream,
603 IdentifierInfo *II = 0)
604 : Reader(Reader), Stream(Stream), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000605
Douglas Gregora868bbd2009-04-21 22:25:48 +0000606 static bool EqualKey(const internal_key_type& a,
607 const internal_key_type& b) {
608 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
609 : false;
610 }
Mike Stump11289f42009-09-09 15:08:12 +0000611
Douglas Gregora868bbd2009-04-21 22:25:48 +0000612 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000613 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000614 }
Mike Stump11289f42009-09-09 15:08:12 +0000615
Douglas Gregora868bbd2009-04-21 22:25:48 +0000616 // This hopefully will just get inlined and removed by the optimizer.
617 static const internal_key_type&
618 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000619
Douglas Gregora868bbd2009-04-21 22:25:48 +0000620 static std::pair<unsigned, unsigned>
621 ReadKeyDataLength(const unsigned char*& d) {
622 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000623 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000624 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000625 return std::make_pair(KeyLen, DataLen);
626 }
Mike Stump11289f42009-09-09 15:08:12 +0000627
Douglas Gregora868bbd2009-04-21 22:25:48 +0000628 static std::pair<const char*, unsigned>
629 ReadKey(const unsigned char* d, unsigned n) {
630 assert(n >= 2 && d[n-1] == '\0');
631 return std::make_pair((const char*) d, n-1);
632 }
Mike Stump11289f42009-09-09 15:08:12 +0000633
634 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000635 const unsigned char* d,
636 unsigned DataLen) {
637 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000638 pch::IdentID ID = ReadUnalignedLE32(d);
639 bool IsInteresting = ID & 0x01;
640
641 // Wipe out the "is interesting" bit.
642 ID = ID >> 1;
643
644 if (!IsInteresting) {
Sebastian Redl98912122010-07-27 23:01:28 +0000645 // For uninteresting identifiers, just build the IdentifierInfo
Douglas Gregor1d583f22009-04-28 21:18:29 +0000646 // and associate it with the persistent ID.
647 IdentifierInfo *II = KnownII;
648 if (!II)
Sebastian Redl07a89a82010-07-30 00:29:29 +0000649 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregor1d583f22009-04-28 21:18:29 +0000650 Reader.SetIdentifierInfo(ID, II);
Sebastian Redl07a89a82010-07-30 00:29:29 +0000651 II->setIsFromPCH();
Douglas Gregor1d583f22009-04-28 21:18:29 +0000652 return II;
653 }
654
Douglas Gregorb9256522009-04-28 21:32:13 +0000655 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000656 bool CPlusPlusOperatorKeyword = Bits & 0x01;
657 Bits >>= 1;
658 bool Poisoned = Bits & 0x01;
659 Bits >>= 1;
660 bool ExtensionToken = Bits & 0x01;
661 Bits >>= 1;
662 bool hasMacroDefinition = Bits & 0x01;
663 Bits >>= 1;
664 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
665 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000666
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000667 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000668 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000669
670 // Build the IdentifierInfo itself and link the identifier ID with
671 // the new IdentifierInfo.
672 IdentifierInfo *II = KnownII;
673 if (!II)
Sebastian Redl07a89a82010-07-30 00:29:29 +0000674 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000675 Reader.SetIdentifierInfo(ID, II);
676
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000677 // Set or check the various bits in the IdentifierInfo structure.
678 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000679 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000680 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000681 "Incorrect extension token flag");
682 (void)ExtensionToken;
683 II->setIsPoisoned(Poisoned);
684 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
685 "Incorrect C++ operator keyword flag");
686 (void)CPlusPlusOperatorKeyword;
687
Douglas Gregorc3366a52009-04-21 23:56:24 +0000688 // If this identifier is a macro, deserialize the macro
689 // definition.
690 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000691 uint32_t Offset = ReadUnalignedLE32(d);
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000692 Reader.ReadMacroRecord(Stream, Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000693 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000694 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000695
696 // Read all of the declarations visible at global scope with this
697 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000698 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000699 if (DataLen > 0) {
700 llvm::SmallVector<uint32_t, 4> DeclIDs;
701 for (; DataLen > 0; DataLen -= 4)
702 DeclIDs.push_back(ReadUnalignedLE32(d));
703 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000704 }
Mike Stump11289f42009-09-09 15:08:12 +0000705
Sebastian Redl07a89a82010-07-30 00:29:29 +0000706 II->setIsFromPCH();
Douglas Gregora868bbd2009-04-21 22:25:48 +0000707 return II;
708 }
709};
Mike Stump11289f42009-09-09 15:08:12 +0000710
711} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000712
713/// \brief The on-disk hash table used to contain information about
714/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000715typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000716 PCHIdentifierLookupTable;
717
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000718void PCHReader::Error(const char *Msg) {
719 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000720}
721
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000722/// \brief Check the contents of the concatenation of all predefines buffers in
723/// the PCH chain against the contents of the predefines buffer of the current
724/// compiler invocation.
Douglas Gregor92863e42009-04-10 23:10:45 +0000725///
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000726/// The contents should be the same. If not, then some command-line option
727/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregor92863e42009-04-10 23:10:45 +0000728///
729/// \returns true if there was a mismatch (in which case the PCH file
730/// should be ignored), or false otherwise.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000731bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000732 if (Listener)
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000733 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000734 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000735 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000736 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000737}
738
Douglas Gregorc5046832009-04-27 18:38:38 +0000739//===----------------------------------------------------------------------===//
740// Source Manager Deserialization
741//===----------------------------------------------------------------------===//
742
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000743/// \brief Read the line table in the source manager block.
744/// \returns true if ther was an error.
Sebastian Redlb293a452010-07-20 21:20:32 +0000745bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000746 unsigned Idx = 0;
747 LineTableInfo &LineTable = SourceMgr.getLineTable();
748
749 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000750 std::map<int, int> FileIDs;
751 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000752 // Extract the file name
753 unsigned FilenameLen = Record[Idx++];
754 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
755 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000756 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000757 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000758 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000759 }
760
761 // Parse the line entries
762 std::vector<LineEntry> Entries;
763 while (Idx < Record.size()) {
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000764 int FID = Record[Idx++];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000765
766 // Extract the line entries
767 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000768 assert(NumEntries && "Numentries is 00000");
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000769 Entries.clear();
770 Entries.reserve(NumEntries);
771 for (unsigned I = 0; I != NumEntries; ++I) {
772 unsigned FileOffset = Record[Idx++];
773 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000774 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump11289f42009-09-09 15:08:12 +0000775 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000776 = (SrcMgr::CharacteristicKind)Record[Idx++];
777 unsigned IncludeOffset = Record[Idx++];
778 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
779 FileKind, IncludeOffset));
780 }
781 LineTable.AddEntry(FID, Entries);
782 }
783
784 return false;
785}
786
Douglas Gregorc5046832009-04-27 18:38:38 +0000787namespace {
788
Benjamin Kramer16634c22009-11-28 10:07:24 +0000789class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000790public:
791 const bool hasStat;
792 const ino_t ino;
793 const dev_t dev;
794 const mode_t mode;
795 const time_t mtime;
796 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000797
Douglas Gregorc5046832009-04-27 18:38:38 +0000798 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000799 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
800
Douglas Gregorc5046832009-04-27 18:38:38 +0000801 PCHStatData()
802 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
803};
804
Benjamin Kramer16634c22009-11-28 10:07:24 +0000805class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000806 public:
807 typedef const char *external_key_type;
808 typedef const char *internal_key_type;
809
810 typedef PCHStatData data_type;
811
812 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000813 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000814 }
815
816 static internal_key_type GetInternalKey(const char *path) { return path; }
817
818 static bool EqualKey(internal_key_type a, internal_key_type b) {
819 return strcmp(a, b) == 0;
820 }
821
822 static std::pair<unsigned, unsigned>
823 ReadKeyDataLength(const unsigned char*& d) {
824 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
825 unsigned DataLen = (unsigned) *d++;
826 return std::make_pair(KeyLen + 1, DataLen);
827 }
828
829 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
830 return (const char *)d;
831 }
832
833 static data_type ReadData(const internal_key_type, const unsigned char *d,
834 unsigned /*DataLen*/) {
835 using namespace clang::io;
836
837 if (*d++ == 1)
838 return data_type();
839
840 ino_t ino = (ino_t) ReadUnalignedLE32(d);
841 dev_t dev = (dev_t) ReadUnalignedLE32(d);
842 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000843 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000844 off_t size = (off_t) ReadUnalignedLE64(d);
845 return data_type(ino, dev, mode, mtime, size);
846 }
847};
848
849/// \brief stat() cache for precompiled headers.
850///
851/// This cache is very similar to the stat cache used by pretokenized
852/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000853class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000854 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
855 CacheTy *Cache;
856
857 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000858public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000859 PCHStatCache(const unsigned char *Buckets,
860 const unsigned char *Base,
861 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000862 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000863 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
864 Cache = CacheTy::Create(Buckets, Base);
865 }
866
867 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000868
Douglas Gregorc5046832009-04-27 18:38:38 +0000869 int stat(const char *path, struct stat *buf) {
870 // Do the lookup for the file's data in the PCH file.
871 CacheTy::iterator I = Cache->find(path);
872
873 // If we don't get a hit in the PCH file just forward to 'stat'.
874 if (I == Cache->end()) {
875 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000876 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000877 }
Mike Stump11289f42009-09-09 15:08:12 +0000878
Douglas Gregorc5046832009-04-27 18:38:38 +0000879 ++NumStatHits;
880 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000881
Douglas Gregorc5046832009-04-27 18:38:38 +0000882 if (!Data.hasStat)
883 return 1;
884
885 buf->st_ino = Data.ino;
886 buf->st_dev = Data.dev;
887 buf->st_mtime = Data.mtime;
888 buf->st_mode = Data.mode;
889 buf->st_size = Data.size;
890 return 0;
891 }
892};
893} // end anonymous namespace
894
895
Sebastian Redl393f8b72010-07-19 20:52:06 +0000896/// \brief Read a source manager block
897PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000898 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000899
Sebastian Redl393f8b72010-07-19 20:52:06 +0000900 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl34522812010-07-16 17:50:48 +0000901
Douglas Gregor258ae542009-04-27 06:38:32 +0000902 // Set the source-location entry cursor to the current position in
903 // the stream. This cursor will be used to read the contents of the
904 // source manager block initially, and then lazily read
905 // source-location entries as needed.
Sebastian Redl393f8b72010-07-19 20:52:06 +0000906 SLocEntryCursor = F.Stream;
Douglas Gregor258ae542009-04-27 06:38:32 +0000907
908 // The stream itself is going to skip over the source manager block.
Sebastian Redl393f8b72010-07-19 20:52:06 +0000909 if (F.Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000910 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000911 return Failure;
912 }
913
914 // Enter the source manager block.
915 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000916 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000917 return Failure;
918 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000919
Douglas Gregora7f71a92009-04-10 03:52:48 +0000920 RecordData Record;
921 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000922 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000923 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000924 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000925 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000926 return Failure;
927 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000928 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000929 }
Mike Stump11289f42009-09-09 15:08:12 +0000930
Douglas Gregora7f71a92009-04-10 03:52:48 +0000931 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
932 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000933 SLocEntryCursor.ReadSubBlockID();
934 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000935 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000936 return Failure;
937 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000938 continue;
939 }
Mike Stump11289f42009-09-09 15:08:12 +0000940
Douglas Gregora7f71a92009-04-10 03:52:48 +0000941 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000942 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000943 continue;
944 }
Mike Stump11289f42009-09-09 15:08:12 +0000945
Douglas Gregora7f71a92009-04-10 03:52:48 +0000946 // Read a record.
947 const char *BlobStart;
948 unsigned BlobLen;
949 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000950 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000951 default: // Default behavior: ignore.
952 break;
953
Chris Lattner184e65d2009-04-14 23:22:57 +0000954 case pch::SM_LINE_TABLE:
Sebastian Redlb293a452010-07-20 21:20:32 +0000955 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000956 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000957 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000958
Douglas Gregor258ae542009-04-27 06:38:32 +0000959 case pch::SM_SLOC_FILE_ENTRY:
960 case pch::SM_SLOC_BUFFER_ENTRY:
961 case pch::SM_SLOC_INSTANTIATION_ENTRY:
962 // Once we hit one of the source location entries, we're done.
963 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000964 }
965 }
966}
967
Sebastian Redl06750302010-07-20 21:50:20 +0000968/// \brief Get a cursor that's correctly positioned for reading the source
969/// location entry with the given ID.
970llvm::BitstreamCursor &PCHReader::SLocCursorForID(unsigned ID) {
971 assert(ID != 0 && ID <= TotalNumSLocEntries &&
972 "SLocCursorForID should only be called for real IDs.");
973
974 ID -= 1;
975 PerFileData *F = 0;
976 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
977 F = Chain[N - I - 1];
978 if (ID < F->LocalNumSLocEntries)
979 break;
980 ID -= F->LocalNumSLocEntries;
981 }
982 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
983
984 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
985 return F->SLocEntryCursor;
986}
987
Douglas Gregor258ae542009-04-27 06:38:32 +0000988/// \brief Read in the source location entry with the given ID.
989PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
990 if (ID == 0)
991 return Success;
992
993 if (ID > TotalNumSLocEntries) {
994 Error("source location entry ID out-of-range for PCH file");
995 return Failure;
996 }
997
Sebastian Redl06750302010-07-20 21:50:20 +0000998 llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
Sebastian Redl34522812010-07-16 17:50:48 +0000999
Douglas Gregor258ae542009-04-27 06:38:32 +00001000 ++NumSLocEntriesRead;
Douglas Gregor258ae542009-04-27 06:38:32 +00001001 unsigned Code = SLocEntryCursor.ReadCode();
1002 if (Code == llvm::bitc::END_BLOCK ||
1003 Code == llvm::bitc::ENTER_SUBBLOCK ||
1004 Code == llvm::bitc::DEFINE_ABBREV) {
1005 Error("incorrectly-formatted source location entry in PCH file");
1006 return Failure;
1007 }
1008
Douglas Gregor258ae542009-04-27 06:38:32 +00001009 RecordData Record;
1010 const char *BlobStart;
1011 unsigned BlobLen;
1012 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1013 default:
1014 Error("incorrectly-formatted source location entry in PCH file");
1015 return Failure;
1016
1017 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001018 std::string Filename(BlobStart, BlobStart + BlobLen);
1019 MaybeAddSystemRootToFilename(Filename);
1020 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +00001021 if (File == 0) {
1022 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001023 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +00001024 ErrorStr += "' referenced by PCH file";
1025 Error(ErrorStr.c_str());
1026 return Failure;
1027 }
Mike Stump11289f42009-09-09 15:08:12 +00001028
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001029 if (Record.size() < 10) {
Ted Kremenekabb1ddd2010-03-18 21:23:05 +00001030 Error("source location entry is incorrect");
1031 return Failure;
1032 }
1033
Douglas Gregorce3a8292010-07-27 00:27:13 +00001034 if (!DisableValidation &&
1035 ((off_t)Record[4] != File->getSize()
Douglas Gregor08288f22010-04-09 15:54:22 +00001036#if !defined(LLVM_ON_WIN32)
1037 // In our regression testing, the Windows file system seems to
1038 // have inconsistent modification times that sometimes
1039 // erroneously trigger this error-handling path.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001040 || (time_t)Record[5] != File->getModificationTime()
Douglas Gregor08288f22010-04-09 15:54:22 +00001041#endif
Douglas Gregorce3a8292010-07-27 00:27:13 +00001042 )) {
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001043 Diag(diag::err_fe_pch_file_modified)
1044 << Filename;
1045 return Failure;
1046 }
1047
Douglas Gregor258ae542009-04-27 06:38:32 +00001048 FileID FID = SourceMgr.createFileID(File,
1049 SourceLocation::getFromRawEncoding(Record[1]),
1050 (SrcMgr::CharacteristicKind)Record[2],
1051 ID, Record[0]);
1052 if (Record[3])
1053 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1054 .setHasLineDirectives();
1055
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001056 // Reconstruct header-search information for this file.
1057 HeaderFileInfo HFI;
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001058 HFI.isImport = Record[6];
1059 HFI.DirInfo = Record[7];
1060 HFI.NumIncludes = Record[8];
1061 HFI.ControllingMacroID = Record[9];
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001062 if (Listener)
1063 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor258ae542009-04-27 06:38:32 +00001064 break;
1065 }
1066
1067 case pch::SM_SLOC_BUFFER_ENTRY: {
1068 const char *Name = BlobStart;
1069 unsigned Offset = Record[0];
1070 unsigned Code = SLocEntryCursor.ReadCode();
1071 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001072 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +00001073 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001074
1075 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1076 Error("PCH record has invalid code");
1077 return Failure;
1078 }
1079
Douglas Gregor258ae542009-04-27 06:38:32 +00001080 llvm::MemoryBuffer *Buffer
Chris Lattner58c79342010-04-05 22:42:27 +00001081 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1082 Name);
Douglas Gregor258ae542009-04-27 06:38:32 +00001083 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +00001084
Douglas Gregore6648fb2009-04-28 20:33:11 +00001085 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl75fbb3b2010-07-14 17:49:11 +00001086 PCHPredefinesBlock Block = {
1087 BufferID,
1088 llvm::StringRef(BlobStart, BlobLen - 1)
1089 };
1090 PCHPredefinesBuffers.push_back(Block);
Douglas Gregore6648fb2009-04-28 20:33:11 +00001091 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001092
1093 break;
1094 }
1095
1096 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +00001097 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +00001098 = SourceLocation::getFromRawEncoding(Record[1]);
1099 SourceMgr.createInstantiationLoc(SpellingLoc,
1100 SourceLocation::getFromRawEncoding(Record[2]),
1101 SourceLocation::getFromRawEncoding(Record[3]),
1102 Record[4],
1103 ID,
1104 Record[0]);
1105 break;
Mike Stump11289f42009-09-09 15:08:12 +00001106 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001107 }
1108
1109 return Success;
1110}
1111
Chris Lattnere78a6be2009-04-27 01:05:14 +00001112/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1113/// specified cursor. Read the abbreviations that are at the top of the block
1114/// and then leave the cursor pointing into the block.
1115bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1116 unsigned BlockID) {
1117 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001118 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001119 return Failure;
1120 }
Mike Stump11289f42009-09-09 15:08:12 +00001121
Chris Lattnere78a6be2009-04-27 01:05:14 +00001122 while (true) {
1123 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001124
Chris Lattnere78a6be2009-04-27 01:05:14 +00001125 // We expect all abbrevs to be at the start of the block.
1126 if (Code != llvm::bitc::DEFINE_ABBREV)
1127 return false;
1128 Cursor.ReadAbbrevRecord();
1129 }
1130}
1131
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001132void PCHReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001133 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +00001134
Douglas Gregorc3366a52009-04-21 23:56:24 +00001135 // Keep track of where we are in the stream, then jump back there
1136 // after reading this macro.
1137 SavedStreamPosition SavedPosition(Stream);
1138
1139 Stream.JumpToBit(Offset);
1140 RecordData Record;
1141 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1142 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001143
Douglas Gregorc3366a52009-04-21 23:56:24 +00001144 while (true) {
1145 unsigned Code = Stream.ReadCode();
1146 switch (Code) {
1147 case llvm::bitc::END_BLOCK:
1148 return;
1149
1150 case llvm::bitc::ENTER_SUBBLOCK:
1151 // No known subblocks, always skip them.
1152 Stream.ReadSubBlockID();
1153 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001154 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001155 return;
1156 }
1157 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001158
Douglas Gregorc3366a52009-04-21 23:56:24 +00001159 case llvm::bitc::DEFINE_ABBREV:
1160 Stream.ReadAbbrevRecord();
1161 continue;
1162 default: break;
1163 }
1164
1165 // Read a record.
1166 Record.clear();
1167 pch::PreprocessorRecordTypes RecType =
1168 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1169 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001170 case pch::PP_MACRO_OBJECT_LIKE:
1171 case pch::PP_MACRO_FUNCTION_LIKE: {
1172 // If we already have a macro, that means that we've hit the end
1173 // of the definition of the macro we were looking for. We're
1174 // done.
1175 if (Macro)
1176 return;
1177
1178 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1179 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001180 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001181 return;
1182 }
1183 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1184 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001185
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001186 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001187 MI->setIsUsed(isUsed);
Sebastian Redl98912122010-07-27 23:01:28 +00001188 MI->setIsFromPCH();
Mike Stump11289f42009-09-09 15:08:12 +00001189
Douglas Gregoraae92242010-03-19 21:51:54 +00001190 unsigned NextIndex = 3;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001191 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1192 // Decode function-like macro info.
1193 bool isC99VarArgs = Record[3];
1194 bool isGNUVarArgs = Record[4];
1195 MacroArgs.clear();
1196 unsigned NumArgs = Record[5];
Douglas Gregoraae92242010-03-19 21:51:54 +00001197 NextIndex = 6 + NumArgs;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001198 for (unsigned i = 0; i != NumArgs; ++i)
1199 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1200
1201 // Install function-like macro info.
1202 MI->setIsFunctionLike();
1203 if (isC99VarArgs) MI->setIsC99Varargs();
1204 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001205 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001206 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001207 }
1208
1209 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001210 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001211
1212 // Remember that we saw this macro last so that we add the tokens that
1213 // form its body to it.
1214 Macro = MI;
Douglas Gregoraae92242010-03-19 21:51:54 +00001215
1216 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1217 // We have a macro definition. Load it now.
1218 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1219 getMacroDefinition(Record[NextIndex]));
1220 }
1221
Douglas Gregorc3366a52009-04-21 23:56:24 +00001222 ++NumMacrosRead;
1223 break;
1224 }
Mike Stump11289f42009-09-09 15:08:12 +00001225
Douglas Gregorc3366a52009-04-21 23:56:24 +00001226 case pch::PP_TOKEN: {
1227 // If we see a TOKEN before a PP_MACRO_*, then the file is
1228 // erroneous, just pretend we didn't see this.
1229 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001230
Douglas Gregorc3366a52009-04-21 23:56:24 +00001231 Token Tok;
1232 Tok.startToken();
1233 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1234 Tok.setLength(Record[1]);
1235 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1236 Tok.setIdentifierInfo(II);
1237 Tok.setKind((tok::TokenKind)Record[3]);
1238 Tok.setFlag((Token::TokenFlags)Record[4]);
1239 Macro->AddTokenToBody(Tok);
1240 break;
1241 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001242
1243 case pch::PP_MACRO_INSTANTIATION: {
1244 // If we already have a macro, that means that we've hit the end
1245 // of the definition of the macro we were looking for. We're
1246 // done.
1247 if (Macro)
1248 return;
1249
1250 if (!PP->getPreprocessingRecord()) {
1251 Error("missing preprocessing record in PCH file");
1252 return;
1253 }
1254
1255 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1256 if (PPRec.getPreprocessedEntity(Record[0]))
1257 return;
1258
1259 MacroInstantiation *MI
1260 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1261 SourceRange(
1262 SourceLocation::getFromRawEncoding(Record[1]),
1263 SourceLocation::getFromRawEncoding(Record[2])),
1264 getMacroDefinition(Record[4]));
1265 PPRec.SetPreallocatedEntity(Record[0], MI);
1266 return;
1267 }
1268
1269 case pch::PP_MACRO_DEFINITION: {
1270 // If we already have a macro, that means that we've hit the end
1271 // of the definition of the macro we were looking for. We're
1272 // done.
1273 if (Macro)
1274 return;
1275
1276 if (!PP->getPreprocessingRecord()) {
1277 Error("missing preprocessing record in PCH file");
1278 return;
1279 }
1280
1281 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1282 if (PPRec.getPreprocessedEntity(Record[0]))
1283 return;
1284
1285 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1286 Error("out-of-bounds macro definition record");
1287 return;
1288 }
1289
1290 MacroDefinition *MD
1291 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1292 SourceLocation::getFromRawEncoding(Record[5]),
1293 SourceRange(
1294 SourceLocation::getFromRawEncoding(Record[2]),
1295 SourceLocation::getFromRawEncoding(Record[3])));
1296 PPRec.SetPreallocatedEntity(Record[0], MD);
1297 MacroDefinitionsLoaded[Record[1]] = MD;
1298 return;
1299 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001300 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001301 }
1302}
1303
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001304void PCHReader::ReadDefinedMacros() {
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001305 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1306 llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
Sebastian Redl34522812010-07-16 17:50:48 +00001307
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001308 // If there was no preprocessor block, skip this file.
1309 if (!MacroCursor.getBitStreamReader())
1310 continue;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001311
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001312 llvm::BitstreamCursor Cursor = MacroCursor;
1313 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1314 Error("malformed preprocessor block record in PCH file");
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001315 return;
1316 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001317
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001318 RecordData Record;
1319 while (true) {
1320 unsigned Code = Cursor.ReadCode();
1321 if (Code == llvm::bitc::END_BLOCK) {
1322 if (Cursor.ReadBlockEnd()) {
1323 Error("error at end of preprocessor block in PCH file");
1324 return;
1325 }
1326 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001327 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001328
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001329 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1330 // No known subblocks, always skip them.
1331 Cursor.ReadSubBlockID();
1332 if (Cursor.SkipBlock()) {
1333 Error("malformed block record in PCH file");
1334 return;
1335 }
1336 continue;
1337 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001338
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001339 if (Code == llvm::bitc::DEFINE_ABBREV) {
1340 Cursor.ReadAbbrevRecord();
1341 continue;
1342 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001343
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001344 // Read a record.
1345 const char *BlobStart;
1346 unsigned BlobLen;
1347 Record.clear();
1348 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1349 default: // Default behavior: ignore.
1350 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001351
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001352 case pch::PP_MACRO_OBJECT_LIKE:
1353 case pch::PP_MACRO_FUNCTION_LIKE:
1354 DecodeIdentifierInfo(Record[0]);
1355 break;
1356
1357 case pch::PP_TOKEN:
1358 // Ignore tokens.
1359 break;
Douglas Gregoraae92242010-03-19 21:51:54 +00001360
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001361 case pch::PP_MACRO_INSTANTIATION:
1362 case pch::PP_MACRO_DEFINITION:
1363 // Read the macro record.
1364 ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1365 break;
1366 }
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001367 }
1368 }
1369}
1370
Douglas Gregoraae92242010-03-19 21:51:54 +00001371MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1372 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1373 return 0;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001374
1375 if (!MacroDefinitionsLoaded[ID]) {
1376 unsigned Index = ID;
1377 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1378 PerFileData &F = *Chain[N - I - 1];
1379 if (Index < F.LocalNumMacroDefinitions) {
1380 ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1381 break;
1382 }
1383 Index -= F.LocalNumMacroDefinitions;
1384 }
1385 assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1386 }
1387
Douglas Gregoraae92242010-03-19 21:51:54 +00001388 return MacroDefinitionsLoaded[ID];
1389}
1390
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001391/// \brief If we are loading a relocatable PCH file, and the filename is
1392/// not an absolute path, add the system root to the beginning of the file
1393/// name.
1394void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1395 // If this is not a relocatable PCH file, there's nothing to do.
1396 if (!RelocatablePCH)
1397 return;
Mike Stump11289f42009-09-09 15:08:12 +00001398
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001399 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001400 return;
1401
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001402 if (isysroot == 0) {
1403 // If no system root was given, default to '/'
1404 Filename.insert(Filename.begin(), '/');
1405 return;
1406 }
Mike Stump11289f42009-09-09 15:08:12 +00001407
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001408 unsigned Length = strlen(isysroot);
1409 if (isysroot[Length - 1] != '/')
1410 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001411
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001412 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1413}
1414
Mike Stump11289f42009-09-09 15:08:12 +00001415PCHReader::PCHReadResult
Sebastian Redl2abc0382010-07-16 20:41:52 +00001416PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl34522812010-07-16 17:50:48 +00001417 llvm::BitstreamCursor &Stream = F.Stream;
1418
Douglas Gregor55abb232009-04-10 20:39:37 +00001419 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001420 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001421 return Failure;
1422 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001423
1424 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001425 RecordData Record;
Sebastian Redl393f8b72010-07-19 20:52:06 +00001426 bool First = true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001427 while (!Stream.AtEndOfStream()) {
1428 unsigned Code = Stream.ReadCode();
1429 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001430 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001431 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001432 return Failure;
1433 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001434
Douglas Gregor55abb232009-04-10 20:39:37 +00001435 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001436 }
1437
1438 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1439 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001440 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001441 // We lazily load the decls block, but we want to set up the
1442 // DeclsCursor cursor to point into it. Clone our current bitcode
1443 // cursor to it, enter the block and read the abbrevs in that block.
1444 // With the main cursor, we just skip over it.
Sebastian Redl34522812010-07-16 17:50:48 +00001445 F.DeclsCursor = Stream;
Chris Lattnere78a6be2009-04-27 01:05:14 +00001446 if (Stream.SkipBlock() || // Skip with the main cursor.
1447 // Read the abbrevs.
Sebastian Redl34522812010-07-16 17:50:48 +00001448 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001449 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001450 return Failure;
1451 }
1452 break;
Mike Stump11289f42009-09-09 15:08:12 +00001453
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001454 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl34522812010-07-16 17:50:48 +00001455 F.MacroCursor = Stream;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001456 if (PP)
1457 PP->setExternalSource(this);
1458
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001459 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001460 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001461 return Failure;
1462 }
1463 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001464
Douglas Gregora7f71a92009-04-10 03:52:48 +00001465 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl393f8b72010-07-19 20:52:06 +00001466 switch (ReadSourceManagerBlock(F)) {
Douglas Gregor92863e42009-04-10 23:10:45 +00001467 case Success:
1468 break;
1469
1470 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001471 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001472 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001473
1474 case IgnorePCH:
1475 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001476 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001477 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001478 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00001479 First = false;
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001480 continue;
1481 }
1482
1483 if (Code == llvm::bitc::DEFINE_ABBREV) {
1484 Stream.ReadAbbrevRecord();
1485 continue;
1486 }
1487
1488 // Read and process a record.
1489 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001490 const char *BlobStart = 0;
1491 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001492 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001493 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001494 default: // Default behavior: ignore.
1495 break;
1496
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001497 case pch::METADATA: {
Douglas Gregorce3a8292010-07-27 00:27:13 +00001498 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001499 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1500 : diag::warn_pch_version_too_new);
1501 return IgnorePCH;
1502 }
1503
1504 RelocatablePCH = Record[4];
1505 if (Listener) {
1506 std::string TargetTriple(BlobStart, BlobLen);
1507 if (Listener->ReadTargetTriple(TargetTriple))
1508 return IgnorePCH;
1509 }
1510 break;
1511 }
1512
1513 case pch::CHAINED_METADATA: {
Sebastian Redl393f8b72010-07-19 20:52:06 +00001514 if (!First) {
1515 Error("CHAINED_METADATA is not first record in block");
1516 return Failure;
1517 }
Douglas Gregorce3a8292010-07-27 00:27:13 +00001518 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001519 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1520 : diag::warn_pch_version_too_new);
1521 return IgnorePCH;
1522 }
1523
1524 // Load the chained file.
1525 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1526 case Failure: return Failure;
1527 // If we have to ignore the dependency, we'll have to ignore this too.
1528 case IgnorePCH: return IgnorePCH;
1529 case Success: break;
1530 }
1531 break;
1532 }
1533
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001534 case pch::TYPE_OFFSET:
Sebastian Redl9e687992010-07-19 22:06:55 +00001535 if (F.LocalNumTypes != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001536 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001537 return Failure;
1538 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001539 F.TypeOffsets = (const uint32_t *)BlobStart;
1540 F.LocalNumTypes = Record[0];
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001541 break;
1542
1543 case pch::DECL_OFFSET:
Sebastian Redl9e687992010-07-19 22:06:55 +00001544 if (F.LocalNumDecls != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001545 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001546 return Failure;
1547 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001548 F.DeclOffsets = (const uint32_t *)BlobStart;
1549 F.LocalNumDecls = Record[0];
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001550 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001551
Sebastian Redl4b1f4902010-07-27 18:24:41 +00001552 case pch::TU_UPDATE_LEXICAL: {
1553 DeclContextInfo Info = {
1554 /* No visible information */ 0, 0,
1555 reinterpret_cast<const pch::DeclID *>(BlobStart),
1556 BlobLen / sizeof(pch::DeclID)
1557 };
1558 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1559 break;
1560 }
1561
Argyrios Kyrtzidis839bbac2010-08-03 17:30:10 +00001562 case pch::REDECLS_UPDATE_LATEST: {
1563 assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
1564 for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
1565 pch::DeclID First = Record[i], Latest = Record[i+1];
1566 assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
1567 Latest > FirstLatestDeclIDs[First]) &&
1568 "The new latest is supposed to come after the previous latest");
1569 FirstLatestDeclIDs[First] = Latest;
1570 }
1571 break;
1572 }
1573
Douglas Gregor55abb232009-04-10 20:39:37 +00001574 case pch::LANGUAGE_OPTIONS:
Douglas Gregorce3a8292010-07-27 00:27:13 +00001575 if (ParseLanguageOptions(Record) && !DisableValidation)
Douglas Gregor55abb232009-04-10 20:39:37 +00001576 return IgnorePCH;
1577 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001578
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001579 case pch::IDENTIFIER_TABLE:
Sebastian Redl393f8b72010-07-19 20:52:06 +00001580 F.IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001581 if (Record[0]) {
Sebastian Redl393f8b72010-07-19 20:52:06 +00001582 F.IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001583 = PCHIdentifierLookupTable::Create(
Sebastian Redl393f8b72010-07-19 20:52:06 +00001584 (const unsigned char *)F.IdentifierTableData + Record[0],
1585 (const unsigned char *)F.IdentifierTableData,
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001586 PCHIdentifierLookupTrait(*this, F.Stream));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001587 if (PP)
1588 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001589 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001590 break;
1591
1592 case pch::IDENTIFIER_OFFSET:
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001593 if (F.LocalNumIdentifiers != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001594 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001595 return Failure;
1596 }
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001597 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1598 F.LocalNumIdentifiers = Record[0];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001599 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001600
1601 case pch::EXTERNAL_DEFINITIONS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001602 // Optimization for the first block.
1603 if (ExternalDefinitions.empty())
1604 ExternalDefinitions.swap(Record);
1605 else
1606 ExternalDefinitions.insert(ExternalDefinitions.end(),
1607 Record.begin(), Record.end());
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001608 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001609
Douglas Gregor652d82a2009-04-18 05:55:16 +00001610 case pch::SPECIAL_TYPES:
Sebastian Redlb293a452010-07-20 21:20:32 +00001611 // Optimization for the first block
1612 if (SpecialTypes.empty())
1613 SpecialTypes.swap(Record);
1614 else
1615 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
Douglas Gregor652d82a2009-04-18 05:55:16 +00001616 break;
1617
Douglas Gregor08f01292009-04-17 22:13:46 +00001618 case pch::STATISTICS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001619 TotalNumStatements += Record[0];
1620 TotalNumMacros += Record[1];
1621 TotalLexicalDeclContexts += Record[2];
1622 TotalVisibleDeclContexts += Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001623 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001624
Douglas Gregord4df8652009-04-22 22:02:47 +00001625 case pch::TENTATIVE_DEFINITIONS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001626 // Optimization for the first block.
1627 if (TentativeDefinitions.empty())
1628 TentativeDefinitions.swap(Record);
1629 else
1630 TentativeDefinitions.insert(TentativeDefinitions.end(),
1631 Record.begin(), Record.end());
Douglas Gregord4df8652009-04-22 22:02:47 +00001632 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001633
Tanya Lattner90073802010-02-12 00:07:30 +00001634 case pch::UNUSED_STATIC_FUNCS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001635 // Optimization for the first block.
1636 if (UnusedStaticFuncs.empty())
1637 UnusedStaticFuncs.swap(Record);
1638 else
1639 UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
1640 Record.begin(), Record.end());
Tanya Lattner90073802010-02-12 00:07:30 +00001641 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001642
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001643 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001644 // Optimization for the first block.
1645 if (LocallyScopedExternalDecls.empty())
1646 LocallyScopedExternalDecls.swap(Record);
1647 else
1648 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1649 Record.begin(), Record.end());
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001650 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001651
Douglas Gregor95c13f52009-04-25 17:48:32 +00001652 case pch::SELECTOR_OFFSETS:
Sebastian Redla19a67f2010-08-03 21:58:15 +00001653 F.SelectorOffsets = (const uint32_t *)BlobStart;
Sebastian Redlada023c2010-08-04 20:40:17 +00001654 F.LocalNumSelectors = Record[0];
Douglas Gregor95c13f52009-04-25 17:48:32 +00001655 break;
1656
Douglas Gregorc78d3462009-04-24 21:10:55 +00001657 case pch::METHOD_POOL:
Sebastian Redlada023c2010-08-04 20:40:17 +00001658 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
Douglas Gregor95c13f52009-04-25 17:48:32 +00001659 if (Record[0])
Sebastian Redlada023c2010-08-04 20:40:17 +00001660 F.SelectorLookupTable
1661 = PCHSelectorLookupTable::Create(
1662 F.SelectorLookupTableData + Record[0],
1663 F.SelectorLookupTableData,
1664 PCHSelectorLookupTrait(*this));
Douglas Gregorc78d3462009-04-24 21:10:55 +00001665 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001666
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001667 case pch::REFERENCED_SELECTOR_POOL: {
Sebastian Redlada023c2010-08-04 20:40:17 +00001668 ReferencedSelectorsData.insert(ReferencedSelectorsData.end(),
1669 Record.begin(), Record.end());
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001670 break;
Sebastian Redl66c5eef2010-07-27 00:17:23 +00001671 }
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001672
Douglas Gregoreda6a892009-04-26 00:07:37 +00001673 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001674 if (!Record.empty() && Listener)
1675 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001676 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001677
1678 case pch::SOURCE_LOCATION_OFFSETS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001679 F.SLocOffsets = (const uint32_t *)BlobStart;
1680 F.LocalNumSLocEntries = Record[0];
1681 // We cannot delay this until all PCHs are loaded, because then source
1682 // location preloads would also have to be delayed.
1683 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregord54f3a12009-10-05 21:07:28 +00001684 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001685 break;
1686
1687 case pch::SOURCE_LOCATION_PRELOADS:
1688 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1689 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1690 if (Result != Success)
1691 return Result;
1692 }
1693 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001694
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001695 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001696 PCHStatCache *MyStatCache =
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001697 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1698 (const unsigned char *)BlobStart,
1699 NumStatHits, NumStatMisses);
1700 FileMgr.addStatCache(MyStatCache);
Sebastian Redl34522812010-07-16 17:50:48 +00001701 F.StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001702 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001703 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001704
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001705 case pch::EXT_VECTOR_DECLS:
Sebastian Redl04f5c312010-07-28 21:38:49 +00001706 // Optimization for the first block.
1707 if (ExtVectorDecls.empty())
1708 ExtVectorDecls.swap(Record);
1709 else
1710 ExtVectorDecls.insert(ExtVectorDecls.end(),
1711 Record.begin(), Record.end());
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001712 break;
1713
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00001714 case pch::VTABLE_USES:
1715 if (!VTableUses.empty()) {
1716 Error("duplicate VTABLE_USES record in PCH file");
1717 return Failure;
1718 }
1719 VTableUses.swap(Record);
1720 break;
1721
1722 case pch::DYNAMIC_CLASSES:
1723 if (!DynamicClasses.empty()) {
1724 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1725 return Failure;
1726 }
1727 DynamicClasses.swap(Record);
1728 break;
1729
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001730 case pch::SEMA_DECL_REFS:
1731 if (!SemaDeclRefs.empty()) {
1732 Error("duplicate SEMA_DECL_REFS record in PCH file");
1733 return Failure;
1734 }
1735 SemaDeclRefs.swap(Record);
1736 break;
1737
Douglas Gregor45fe0362009-05-12 01:31:05 +00001738 case pch::ORIGINAL_FILE_NAME:
Sebastian Redlb293a452010-07-20 21:20:32 +00001739 // The primary PCH will be the last to get here, so it will be the one
1740 // that's used.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001741 ActualOriginalFileName.assign(BlobStart, BlobLen);
1742 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001743 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001744 break;
Mike Stump11289f42009-09-09 15:08:12 +00001745
Ted Kremenek17437132010-01-22 20:59:36 +00001746 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek8bd09292010-02-12 23:31:14 +00001747 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek2377a0e2010-01-22 20:55:35 +00001748 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001749 if (llvm::StringRef(CurBranch) != PCHBranch && !DisableValidation) {
Douglas Gregord54f3a12009-10-05 21:07:28 +00001750 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1751 return IgnorePCH;
1752 }
1753 break;
1754 }
Sebastian Redlfa061442010-07-21 20:07:32 +00001755
Douglas Gregoraae92242010-03-19 21:51:54 +00001756 case pch::MACRO_DEFINITION_OFFSETS:
Sebastian Redlfa061442010-07-21 20:07:32 +00001757 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1758 F.NumPreallocatedPreprocessingEntities = Record[0];
1759 F.LocalNumMacroDefinitions = Record[1];
Douglas Gregoraae92242010-03-19 21:51:54 +00001760 break;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001761 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00001762 First = false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001763 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001764 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001765 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001766}
1767
Douglas Gregor92863e42009-04-10 23:10:45 +00001768PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001769 switch(ReadPCHCore(FileName)) {
Sebastian Redl2abc0382010-07-16 20:41:52 +00001770 case Failure: return Failure;
1771 case IgnorePCH: return IgnorePCH;
1772 case Success: break;
1773 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001774
1775 // Here comes stuff that we only do once the entire chain is loaded.
1776
Sebastian Redlb293a452010-07-20 21:20:32 +00001777 // Allocate space for loaded identifiers, decls and types.
Sebastian Redlfa061442010-07-21 20:07:32 +00001778 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
Sebastian Redlada023c2010-08-04 20:40:17 +00001779 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0,
1780 TotalNumSelectors = 0;
Sebastian Redl9e687992010-07-19 22:06:55 +00001781 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001782 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
Sebastian Redl9e687992010-07-19 22:06:55 +00001783 TotalNumTypes += Chain[I]->LocalNumTypes;
1784 TotalNumDecls += Chain[I]->LocalNumDecls;
Sebastian Redlfa061442010-07-21 20:07:32 +00001785 TotalNumPreallocatedPreprocessingEntities +=
1786 Chain[I]->NumPreallocatedPreprocessingEntities;
1787 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
Sebastian Redlada023c2010-08-04 20:40:17 +00001788 TotalNumSelectors += Chain[I]->LocalNumSelectors;
Sebastian Redl9e687992010-07-19 22:06:55 +00001789 }
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001790 IdentifiersLoaded.resize(TotalNumIdentifiers);
Sebastian Redl9e687992010-07-19 22:06:55 +00001791 TypesLoaded.resize(TotalNumTypes);
1792 DeclsLoaded.resize(TotalNumDecls);
Sebastian Redlfa061442010-07-21 20:07:32 +00001793 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
1794 if (PP) {
1795 if (TotalNumIdentifiers > 0)
1796 PP->getHeaderSearchInfo().SetExternalLookup(this);
1797 if (TotalNumPreallocatedPreprocessingEntities > 0) {
1798 if (!PP->getPreprocessingRecord())
1799 PP->createPreprocessingRecord();
1800 PP->getPreprocessingRecord()->SetExternalSource(*this,
1801 TotalNumPreallocatedPreprocessingEntities);
1802 }
1803 }
Sebastian Redlada023c2010-08-04 20:40:17 +00001804 SelectorsLoaded.resize(TotalNumSelectors);
Sebastian Redl9e687992010-07-19 22:06:55 +00001805
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001806 // Check the predefines buffers.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001807 if (!DisableValidation && CheckPredefinesBuffers())
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001808 return IgnorePCH;
1809
1810 if (PP) {
1811 // Initialization of keywords and pragmas occurs before the
1812 // PCH file is read, so there may be some identifiers that were
1813 // loaded into the IdentifierTable before we intercepted the
1814 // creation of identifiers. Iterate through the list of known
1815 // identifiers and determine whether we have to establish
1816 // preprocessor definitions or top-level identifier declaration
1817 // chains for those identifiers.
1818 //
1819 // We copy the IdentifierInfo pointers to a small vector first,
1820 // since de-serializing declarations or macro definitions can add
1821 // new entries into the identifier table, invalidating the
1822 // iterators.
1823 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1824 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1825 IdEnd = PP->getIdentifierTable().end();
1826 Id != IdEnd; ++Id)
1827 Identifiers.push_back(Id->second);
Sebastian Redlfa061442010-07-21 20:07:32 +00001828 // We need to search the tables in all files.
Sebastian Redlfa061442010-07-21 20:07:32 +00001829 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1830 PCHIdentifierLookupTable *IdTable
1831 = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
Sebastian Redl5c415f32010-07-22 17:01:13 +00001832 // Not all PCH files necessarily have identifier tables, only the useful
1833 // ones.
1834 if (!IdTable)
1835 continue;
Sebastian Redlfa061442010-07-21 20:07:32 +00001836 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1837 IdentifierInfo *II = Identifiers[I];
1838 // Look in the on-disk hash tables for an entry for this identifier
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001839 PCHIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
Sebastian Redlfa061442010-07-21 20:07:32 +00001840 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
Sebastian Redlb293a452010-07-20 21:20:32 +00001841 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1842 if (Pos == IdTable->end())
1843 continue;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001844
Sebastian Redlb293a452010-07-20 21:20:32 +00001845 // Dereferencing the iterator has the effect of populating the
1846 // IdentifierInfo node with the various declarations it needs.
1847 (void)*Pos;
1848 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001849 }
1850 }
1851
1852 if (Context)
1853 InitializeContext(*Context);
1854
1855 return Success;
1856}
1857
1858PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1859 Chain.push_back(new PerFileData());
Sebastian Redl34522812010-07-16 17:50:48 +00001860 PerFileData &F = *Chain.back();
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001861
1862 // Set the PCH file name.
1863 F.FileName = FileName;
1864
1865 // Open the PCH file.
1866 //
1867 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1868 std::string ErrStr;
1869 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1870 if (!F.Buffer) {
1871 Error(ErrStr.c_str());
1872 return IgnorePCH;
1873 }
1874
1875 // Initialize the stream
1876 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1877 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl34522812010-07-16 17:50:48 +00001878 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001879 Stream.init(F.StreamFile);
Sebastian Redlfa061442010-07-21 20:07:32 +00001880 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001881
1882 // Sniff for the signature.
1883 if (Stream.Read(8) != 'C' ||
1884 Stream.Read(8) != 'P' ||
1885 Stream.Read(8) != 'C' ||
1886 Stream.Read(8) != 'H') {
1887 Diag(diag::err_not_a_pch_file) << FileName;
1888 return Failure;
1889 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001890
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001891 while (!Stream.AtEndOfStream()) {
1892 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001893
Douglas Gregor92863e42009-04-10 23:10:45 +00001894 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001895 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001896 return Failure;
1897 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001898
1899 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001900
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001901 // We only know the PCH subblock ID.
1902 switch (BlockID) {
1903 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001904 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001905 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001906 return Failure;
1907 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001908 break;
1909 case pch::PCH_BLOCK_ID:
Sebastian Redl2abc0382010-07-16 20:41:52 +00001910 switch (ReadPCHBlock(F)) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001911 case Success:
1912 break;
1913
1914 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001915 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001916
1917 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001918 // FIXME: We could consider reading through to the end of this
1919 // PCH block, skipping subblocks, to see if there are other
1920 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001921
1922 // Clear out any preallocated source location entries, so that
1923 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001924 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001925
1926 // Remove the stat cache.
Sebastian Redl34522812010-07-16 17:50:48 +00001927 if (F.StatCache)
1928 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001929
Douglas Gregor92863e42009-04-10 23:10:45 +00001930 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001931 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001932 break;
1933 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001934 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001935 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001936 return Failure;
1937 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001938 break;
1939 }
Mike Stump11289f42009-09-09 15:08:12 +00001940 }
1941
Sebastian Redl2abc0382010-07-16 20:41:52 +00001942 return Success;
1943}
1944
Douglas Gregoraae92242010-03-19 21:51:54 +00001945void PCHReader::setPreprocessor(Preprocessor &pp) {
1946 PP = &pp;
Sebastian Redlfa061442010-07-21 20:07:32 +00001947
1948 unsigned TotalNum = 0;
1949 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
1950 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
1951 if (TotalNum) {
Douglas Gregoraae92242010-03-19 21:51:54 +00001952 if (!PP->getPreprocessingRecord())
1953 PP->createPreprocessingRecord();
Sebastian Redlfa061442010-07-21 20:07:32 +00001954 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
Douglas Gregoraae92242010-03-19 21:51:54 +00001955 }
1956}
1957
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001958void PCHReader::InitializeContext(ASTContext &Ctx) {
1959 Context = &Ctx;
1960 assert(Context && "Passed null context!");
1961
1962 assert(PP && "Forgot to set Preprocessor ?");
1963 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1964 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001965 PP->setExternalSource(this);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001966
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001967 // Load the translation unit declaration
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00001968 GetTranslationUnitDecl();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001969
1970 // Load the special types.
1971 Context->setBuiltinVaListType(
1972 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1973 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1974 Context->setObjCIdType(GetType(Id));
1975 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1976 Context->setObjCSelType(GetType(Sel));
1977 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1978 Context->setObjCProtoType(GetType(Proto));
1979 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1980 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001981
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001982 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1983 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001984 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001985 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1986 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001987 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1988 QualType FileType = GetType(File);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001989 if (FileType.isNull()) {
1990 Error("FILE type is NULL");
1991 return;
1992 }
John McCall9dd450b2009-09-21 23:43:11 +00001993 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001994 Context->setFILEDecl(Typedef->getDecl());
1995 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001996 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001997 if (!Tag) {
1998 Error("Invalid FILE type in PCH file");
1999 return;
2000 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00002001 Context->setFILEDecl(Tag->getDecl());
2002 }
2003 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00002004 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
2005 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002006 if (Jmp_bufType.isNull()) {
2007 Error("jmp_bug type is NULL");
2008 return;
2009 }
John McCall9dd450b2009-09-21 23:43:11 +00002010 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00002011 Context->setjmp_bufDecl(Typedef->getDecl());
2012 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002013 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002014 if (!Tag) {
2015 Error("Invalid jmp_bug type in PCH file");
2016 return;
2017 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00002018 Context->setjmp_bufDecl(Tag->getDecl());
2019 }
2020 }
2021 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
2022 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002023 if (Sigjmp_bufType.isNull()) {
2024 Error("sigjmp_buf type is NULL");
2025 return;
2026 }
John McCall9dd450b2009-09-21 23:43:11 +00002027 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00002028 Context->setsigjmp_bufDecl(Typedef->getDecl());
2029 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002030 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00002031 assert(Tag && "Invalid sigjmp_buf type in PCH file");
2032 Context->setsigjmp_bufDecl(Tag->getDecl());
2033 }
2034 }
Mike Stump11289f42009-09-09 15:08:12 +00002035 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00002036 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2037 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00002038 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00002039 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2040 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpd0153282009-10-20 02:12:22 +00002041 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2042 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002043 if (unsigned String
2044 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2045 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002046 if (unsigned ObjCSelRedef
2047 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2048 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2049 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
2050 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +00002051
2052 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
2053 Context->setInt128Installed();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002054}
2055
Douglas Gregor45fe0362009-05-12 01:31:05 +00002056/// \brief Retrieve the name of the original source file name
2057/// directly from the PCH file, without actually loading the PCH
2058/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00002059std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
2060 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00002061 // Open the PCH file.
2062 std::string ErrStr;
2063 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2064 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
2065 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002066 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002067 return std::string();
2068 }
2069
2070 // Initialize the stream
2071 llvm::BitstreamReader StreamFile;
2072 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00002073 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00002074 (const unsigned char *)Buffer->getBufferEnd());
2075 Stream.init(StreamFile);
2076
2077 // Sniff for the signature.
2078 if (Stream.Read(8) != 'C' ||
2079 Stream.Read(8) != 'P' ||
2080 Stream.Read(8) != 'C' ||
2081 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002082 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002083 return std::string();
2084 }
2085
2086 RecordData Record;
2087 while (!Stream.AtEndOfStream()) {
2088 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00002089
Douglas Gregor45fe0362009-05-12 01:31:05 +00002090 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2091 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00002092
Douglas Gregor45fe0362009-05-12 01:31:05 +00002093 // We only know the PCH subblock ID.
2094 switch (BlockID) {
2095 case pch::PCH_BLOCK_ID:
2096 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002097 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002098 return std::string();
2099 }
2100 break;
Mike Stump11289f42009-09-09 15:08:12 +00002101
Douglas Gregor45fe0362009-05-12 01:31:05 +00002102 default:
2103 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002104 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002105 return std::string();
2106 }
2107 break;
2108 }
2109 continue;
2110 }
2111
2112 if (Code == llvm::bitc::END_BLOCK) {
2113 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002114 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002115 return std::string();
2116 }
2117 continue;
2118 }
2119
2120 if (Code == llvm::bitc::DEFINE_ABBREV) {
2121 Stream.ReadAbbrevRecord();
2122 continue;
2123 }
2124
2125 Record.clear();
2126 const char *BlobStart = 0;
2127 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002128 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00002129 == pch::ORIGINAL_FILE_NAME)
2130 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00002131 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00002132
2133 return std::string();
2134}
2135
Douglas Gregor55abb232009-04-10 20:39:37 +00002136/// \brief Parse the record that corresponds to a LangOptions data
2137/// structure.
2138///
2139/// This routine compares the language options used to generate the
2140/// PCH file against the language options set for the current
2141/// compilation. For each option, we classify differences between the
2142/// two compiler states as either "benign" or "important". Benign
2143/// differences don't matter, and we accept them without complaint
2144/// (and without modifying the language options). Differences between
2145/// the states for important options cause the PCH file to be
2146/// unusable, so we emit a warning and return true to indicate that
2147/// there was an error.
2148///
2149/// \returns true if the PCH file is unacceptable, false otherwise.
2150bool PCHReader::ParseLanguageOptions(
2151 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002152 if (Listener) {
2153 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00002154
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002155 #define PARSE_LANGOPT(Option) \
2156 LangOpts.Option = Record[Idx]; \
2157 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00002158
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002159 unsigned Idx = 0;
2160 PARSE_LANGOPT(Trigraphs);
2161 PARSE_LANGOPT(BCPLComment);
2162 PARSE_LANGOPT(DollarIdents);
2163 PARSE_LANGOPT(AsmPreprocessor);
2164 PARSE_LANGOPT(GNUMode);
Chandler Carruthe03aa552010-04-17 20:17:31 +00002165 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002166 PARSE_LANGOPT(ImplicitInt);
2167 PARSE_LANGOPT(Digraphs);
2168 PARSE_LANGOPT(HexFloats);
2169 PARSE_LANGOPT(C99);
2170 PARSE_LANGOPT(Microsoft);
2171 PARSE_LANGOPT(CPlusPlus);
2172 PARSE_LANGOPT(CPlusPlus0x);
2173 PARSE_LANGOPT(CXXOperatorNames);
2174 PARSE_LANGOPT(ObjC1);
2175 PARSE_LANGOPT(ObjC2);
2176 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00002177 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian62c56022010-04-22 21:01:59 +00002178 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002179 PARSE_LANGOPT(PascalStrings);
2180 PARSE_LANGOPT(WritableStrings);
2181 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00002182 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002183 PARSE_LANGOPT(Exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +00002184 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002185 PARSE_LANGOPT(NeXTRuntime);
2186 PARSE_LANGOPT(Freestanding);
2187 PARSE_LANGOPT(NoBuiltin);
2188 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00002189 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002190 PARSE_LANGOPT(Blocks);
2191 PARSE_LANGOPT(EmitAllDecls);
2192 PARSE_LANGOPT(MathErrno);
Chris Lattner51924e512010-06-26 21:25:03 +00002193 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2194 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002195 PARSE_LANGOPT(HeinousExtensions);
2196 PARSE_LANGOPT(Optimize);
2197 PARSE_LANGOPT(OptimizeSize);
2198 PARSE_LANGOPT(Static);
2199 PARSE_LANGOPT(PICLevel);
2200 PARSE_LANGOPT(GNUInline);
2201 PARSE_LANGOPT(NoInline);
2202 PARSE_LANGOPT(AccessControl);
2203 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00002204 PARSE_LANGOPT(ShortWChar);
Chris Lattner51924e512010-06-26 21:25:03 +00002205 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2206 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbar143021e2009-09-21 04:16:19 +00002207 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattner51924e512010-06-26 21:25:03 +00002208 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002209 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00002210 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00002211 PARSE_LANGOPT(CatchUndefined);
2212 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002213 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00002214
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002215 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00002216 }
Douglas Gregor55abb232009-04-10 20:39:37 +00002217
2218 return false;
2219}
2220
Douglas Gregoraae92242010-03-19 21:51:54 +00002221void PCHReader::ReadPreprocessedEntities() {
2222 ReadDefinedMacros();
2223}
2224
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002225/// \brief Get the correct cursor and offset for loading a type.
2226PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
2227 PerFileData *F = 0;
2228 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2229 F = Chain[N - I - 1];
2230 if (Index < F->LocalNumTypes)
2231 break;
2232 Index -= F->LocalNumTypes;
2233 }
2234 assert(F && F->LocalNumTypes > Index && "Broken chain");
Sebastian Redlb2831db2010-07-20 22:55:31 +00002235 return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002236}
2237
2238/// \brief Read and return the type with the given index..
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002239///
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002240/// The index is the type ID, shifted and minus the number of predefs. This
2241/// routine actually reads the record corresponding to the type at the given
2242/// location. It is a helper routine for GetType, which deals with reading type
2243/// IDs.
2244QualType PCHReader::ReadTypeRecord(unsigned Index) {
2245 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redlb2831db2010-07-20 22:55:31 +00002246 llvm::BitstreamCursor &DeclsCursor = *Loc.first;
Sebastian Redl34522812010-07-16 17:50:48 +00002247
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002248 // Keep track of where we are in the stream, then jump back there
2249 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00002250 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002251
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002252 ReadingKindTracker ReadingKind(Read_Type, *this);
2253
Douglas Gregor1342e842009-07-06 18:54:52 +00002254 // Note that we are loading a type record.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00002255 Deserializing AType(this);
Mike Stump11289f42009-09-09 15:08:12 +00002256
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002257 DeclsCursor.JumpToBit(Loc.second);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002258 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00002259 unsigned Code = DeclsCursor.ReadCode();
2260 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00002261 case pch::TYPE_EXT_QUAL: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002262 if (Record.size() != 2) {
2263 Error("Incorrect encoding of extended qualifier type");
2264 return QualType();
2265 }
Douglas Gregor455b8f42009-04-15 22:00:08 +00002266 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00002267 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2268 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00002269 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002270
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002271 case pch::TYPE_COMPLEX: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002272 if (Record.size() != 1) {
2273 Error("Incorrect encoding of complex type");
2274 return QualType();
2275 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002276 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002277 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002278 }
2279
2280 case pch::TYPE_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002281 if (Record.size() != 1) {
2282 Error("Incorrect encoding of pointer type");
2283 return QualType();
2284 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002285 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002286 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002287 }
2288
2289 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002290 if (Record.size() != 1) {
2291 Error("Incorrect encoding of block pointer type");
2292 return QualType();
2293 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002294 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002295 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002296 }
2297
2298 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002299 if (Record.size() != 1) {
2300 Error("Incorrect encoding of lvalue reference type");
2301 return QualType();
2302 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002303 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002304 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002305 }
2306
2307 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002308 if (Record.size() != 1) {
2309 Error("Incorrect encoding of rvalue reference type");
2310 return QualType();
2311 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002312 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002313 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002314 }
2315
2316 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidisee776bc2010-07-02 11:55:15 +00002317 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002318 Error("Incorrect encoding of member pointer type");
2319 return QualType();
2320 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002321 QualType PointeeType = GetType(Record[0]);
2322 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002323 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002324 }
2325
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002326 case pch::TYPE_CONSTANT_ARRAY: {
2327 QualType ElementType = GetType(Record[0]);
2328 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2329 unsigned IndexTypeQuals = Record[2];
2330 unsigned Idx = 3;
2331 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00002332 return Context->getConstantArrayType(ElementType, Size,
2333 ASM, IndexTypeQuals);
2334 }
2335
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002336 case pch::TYPE_INCOMPLETE_ARRAY: {
2337 QualType ElementType = GetType(Record[0]);
2338 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2339 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00002340 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002341 }
2342
2343 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002344 QualType ElementType = GetType(Record[0]);
2345 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2346 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00002347 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2348 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Sebastian Redlc67764e2010-07-22 22:43:28 +00002349 return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
Douglas Gregor04318252009-07-06 15:59:29 +00002350 ASM, IndexTypeQuals,
2351 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002352 }
2353
2354 case pch::TYPE_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002355 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002356 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002357 return QualType();
2358 }
2359
2360 QualType ElementType = GetType(Record[0]);
2361 unsigned NumElements = Record[1];
Chris Lattner37141f42010-06-23 06:00:24 +00002362 unsigned AltiVecSpec = Record[2];
2363 return Context->getVectorType(ElementType, NumElements,
2364 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002365 }
2366
2367 case pch::TYPE_EXT_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002368 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002369 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002370 return QualType();
2371 }
2372
2373 QualType ElementType = GetType(Record[0]);
2374 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00002375 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002376 }
2377
2378 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002379 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002380 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002381 return QualType();
2382 }
2383 QualType ResultType = GetType(Record[0]);
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002384 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002385 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002386 }
2387
2388 case pch::TYPE_FUNCTION_PROTO: {
2389 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00002390 bool NoReturn = Record[1];
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002391 unsigned RegParm = Record[2];
2392 CallingConv CallConv = (CallingConv)Record[3];
2393 unsigned Idx = 4;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002394 unsigned NumParams = Record[Idx++];
2395 llvm::SmallVector<QualType, 16> ParamTypes;
2396 for (unsigned I = 0; I != NumParams; ++I)
2397 ParamTypes.push_back(GetType(Record[Idx++]));
2398 bool isVariadic = Record[Idx++];
2399 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002400 bool hasExceptionSpec = Record[Idx++];
2401 bool hasAnyExceptionSpec = Record[Idx++];
2402 unsigned NumExceptions = Record[Idx++];
2403 llvm::SmallVector<QualType, 2> Exceptions;
2404 for (unsigned I = 0; I != NumExceptions; ++I)
2405 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00002406 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002407 isVariadic, Quals, hasExceptionSpec,
2408 hasAnyExceptionSpec, NumExceptions,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002409 Exceptions.data(),
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002410 FunctionType::ExtInfo(NoReturn, RegParm,
2411 CallConv));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002412 }
2413
John McCallb96ec562009-12-04 22:46:56 +00002414 case pch::TYPE_UNRESOLVED_USING:
2415 return Context->getTypeDeclType(
2416 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2417
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002418 case pch::TYPE_TYPEDEF: {
2419 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002420 Error("incorrect encoding of typedef type");
2421 return QualType();
2422 }
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002423 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2424 QualType Canonical = GetType(Record[1]);
2425 return Context->getTypedefType(Decl, Canonical);
2426 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002427
2428 case pch::TYPE_TYPEOF_EXPR:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002429 return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002430
2431 case pch::TYPE_TYPEOF: {
2432 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002433 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002434 return QualType();
2435 }
2436 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002437 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002438 }
Mike Stump11289f42009-09-09 15:08:12 +00002439
Anders Carlsson81df7b82009-06-24 19:06:50 +00002440 case pch::TYPE_DECLTYPE:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002441 return Context->getDecltypeType(ReadExpr(DeclsCursor));
Anders Carlsson81df7b82009-06-24 19:06:50 +00002442
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002443 case pch::TYPE_RECORD: {
2444 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002445 Error("incorrect encoding of record type");
2446 return QualType();
2447 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002448 bool IsDependent = Record[0];
2449 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2450 T->Dependent = IsDependent;
2451 return T;
2452 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002453
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002454 case pch::TYPE_ENUM: {
2455 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002456 Error("incorrect encoding of enum type");
2457 return QualType();
2458 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002459 bool IsDependent = Record[0];
2460 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2461 T->Dependent = IsDependent;
2462 return T;
2463 }
Douglas Gregor1daeb692009-04-13 18:14:40 +00002464
John McCallfcc33b02009-09-05 00:15:47 +00002465 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002466 unsigned Idx = 0;
2467 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2468 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2469 QualType NamedType = GetType(Record[Idx++]);
2470 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCallfcc33b02009-09-05 00:15:47 +00002471 }
2472
Steve Naroffc277ad12009-07-18 15:33:26 +00002473 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00002474 unsigned Idx = 0;
2475 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002476 return Context->getObjCInterfaceType(ItfD);
2477 }
2478
2479 case pch::TYPE_OBJC_OBJECT: {
2480 unsigned Idx = 0;
2481 QualType Base = GetType(Record[Idx++]);
Chris Lattner587cbe12009-04-22 06:45:28 +00002482 unsigned NumProtos = Record[Idx++];
2483 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2484 for (unsigned I = 0; I != NumProtos; ++I)
2485 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCall8b07ec22010-05-15 11:32:37 +00002486 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00002487 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002488
Steve Narofffb4330f2009-06-17 22:40:22 +00002489 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00002490 unsigned Idx = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002491 QualType Pointee = GetType(Record[Idx++]);
2492 return Context->getObjCObjectPointerType(Pointee);
Chris Lattner6e054af2009-04-22 06:40:03 +00002493 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00002494
John McCallcebee162009-10-18 09:09:24 +00002495 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2496 unsigned Idx = 0;
2497 QualType Parm = GetType(Record[Idx++]);
2498 QualType Replacement = GetType(Record[Idx++]);
2499 return
2500 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2501 Replacement);
2502 }
John McCalle78aac42010-03-10 03:28:59 +00002503
2504 case pch::TYPE_INJECTED_CLASS_NAME: {
2505 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2506 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidisdab33c52010-07-02 11:55:20 +00002507 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2508 // for PCH reading, too much interdependencies.
2509 return
2510 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCalle78aac42010-03-10 03:28:59 +00002511 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002512
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002513 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2514 unsigned Idx = 0;
2515 unsigned Depth = Record[Idx++];
2516 unsigned Index = Record[Idx++];
2517 bool Pack = Record[Idx++];
2518 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2519 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2520 }
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002521
2522 case pch::TYPE_DEPENDENT_NAME: {
2523 unsigned Idx = 0;
2524 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2525 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2526 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidise9290952010-07-02 11:55:24 +00002527 QualType Canon = GetType(Record[Idx++]);
2528 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002529 }
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002530
2531 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2532 unsigned Idx = 0;
2533 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2534 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2535 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2536 unsigned NumArgs = Record[Idx++];
2537 llvm::SmallVector<TemplateArgument, 8> Args;
2538 Args.reserve(NumArgs);
2539 while (NumArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00002540 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002541 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2542 Args.size(), Args.data());
2543 }
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00002544
2545 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2546 unsigned Idx = 0;
2547
2548 // ArrayType
2549 QualType ElementType = GetType(Record[Idx++]);
2550 ArrayType::ArraySizeModifier ASM
2551 = (ArrayType::ArraySizeModifier)Record[Idx++];
2552 unsigned IndexTypeQuals = Record[Idx++];
2553
2554 // DependentSizedArrayType
Sebastian Redlc67764e2010-07-22 22:43:28 +00002555 Expr *NumElts = ReadExpr(DeclsCursor);
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00002556 SourceRange Brackets = ReadSourceRange(Record, Idx);
2557
2558 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2559 IndexTypeQuals, Brackets);
2560 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002561
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002562 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2563 unsigned Idx = 0;
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002564 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002565 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002566 llvm::SmallVector<TemplateArgument, 8> Args;
Sebastian Redlc67764e2010-07-22 22:43:28 +00002567 ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00002568 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002569 QualType T;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002570 if (Canon.isNull())
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002571 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2572 Args.size());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002573 else
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002574 T = Context->getTemplateSpecializationType(Name, Args.data(),
2575 Args.size(), Canon);
2576 T->Dependent = IsDependent;
2577 return T;
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002578 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002579 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002580 // Suppress a GCC warning
2581 return QualType();
2582}
2583
John McCall8f115c62009-10-16 21:56:05 +00002584namespace {
2585
2586class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2587 PCHReader &Reader;
Sebastian Redlc67764e2010-07-22 22:43:28 +00002588 llvm::BitstreamCursor &DeclsCursor;
John McCall8f115c62009-10-16 21:56:05 +00002589 const PCHReader::RecordData &Record;
2590 unsigned &Idx;
2591
2592public:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002593 TypeLocReader(PCHReader &Reader, llvm::BitstreamCursor &Cursor,
2594 const PCHReader::RecordData &Record, unsigned &Idx)
2595 : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
John McCall8f115c62009-10-16 21:56:05 +00002596
John McCall17001972009-10-18 01:05:36 +00002597 // We want compile-time assurance that we've enumerated all of
2598 // these, so unfortunately we have to declare them first, then
2599 // define them out-of-line.
2600#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002601#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002602 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002603#include "clang/AST/TypeLocNodes.def"
2604
John McCall17001972009-10-18 01:05:36 +00002605 void VisitFunctionTypeLoc(FunctionTypeLoc);
2606 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002607};
2608
2609}
2610
John McCall17001972009-10-18 01:05:36 +00002611void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002612 // nothing to do
2613}
John McCall17001972009-10-18 01:05:36 +00002614void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +00002615 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2616 if (TL.needsExtraLocalData()) {
2617 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2618 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2619 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2620 TL.setModeAttr(Record[Idx++]);
2621 }
John McCall8f115c62009-10-16 21:56:05 +00002622}
John McCall17001972009-10-18 01:05:36 +00002623void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2624 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002625}
John McCall17001972009-10-18 01:05:36 +00002626void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2627 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002628}
John McCall17001972009-10-18 01:05:36 +00002629void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2630 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002631}
John McCall17001972009-10-18 01:05:36 +00002632void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2633 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002634}
John McCall17001972009-10-18 01:05:36 +00002635void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2636 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002637}
John McCall17001972009-10-18 01:05:36 +00002638void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2639 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002640}
John McCall17001972009-10-18 01:05:36 +00002641void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2642 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2643 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002644 if (Record[Idx++])
Sebastian Redlc67764e2010-07-22 22:43:28 +00002645 TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
Douglas Gregor12bfa382009-10-17 00:13:19 +00002646 else
John McCall17001972009-10-18 01:05:36 +00002647 TL.setSizeExpr(0);
2648}
2649void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2650 VisitArrayTypeLoc(TL);
2651}
2652void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2653 VisitArrayTypeLoc(TL);
2654}
2655void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2656 VisitArrayTypeLoc(TL);
2657}
2658void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2659 DependentSizedArrayTypeLoc TL) {
2660 VisitArrayTypeLoc(TL);
2661}
2662void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2663 DependentSizedExtVectorTypeLoc TL) {
2664 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2665}
2666void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2667 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2668}
2669void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2670 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2671}
2672void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2673 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2674 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2675 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002676 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002677 }
2678}
2679void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2680 VisitFunctionTypeLoc(TL);
2681}
2682void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2683 VisitFunctionTypeLoc(TL);
2684}
John McCallb96ec562009-12-04 22:46:56 +00002685void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2686 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2687}
John McCall17001972009-10-18 01:05:36 +00002688void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2689 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2690}
2691void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002692 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2693 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2694 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002695}
2696void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002697 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2698 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2699 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Sebastian Redlc67764e2010-07-22 22:43:28 +00002700 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002701}
2702void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2703 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2704}
2705void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2706 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2707}
2708void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2709 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2710}
John McCall17001972009-10-18 01:05:36 +00002711void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2712 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2713}
John McCallcebee162009-10-18 09:09:24 +00002714void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2715 SubstTemplateTypeParmTypeLoc TL) {
2716 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2717}
John McCall17001972009-10-18 01:05:36 +00002718void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2719 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002720 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2721 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2722 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2723 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2724 TL.setArgLocInfo(i,
2725 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002726 DeclsCursor, Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002727}
Abramo Bagnara6150c882010-05-11 21:36:43 +00002728void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002729 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2730 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002731}
John McCalle78aac42010-03-10 03:28:59 +00002732void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2733 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2734}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002735void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002736 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2737 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002738 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2739}
John McCallc392f372010-06-11 00:33:02 +00002740void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2741 DependentTemplateSpecializationTypeLoc TL) {
2742 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2743 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2744 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2745 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2746 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2747 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2748 TL.setArgLocInfo(I,
2749 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002750 DeclsCursor, Record, Idx));
John McCallc392f372010-06-11 00:33:02 +00002751}
John McCall17001972009-10-18 01:05:36 +00002752void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2753 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002754}
2755void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2756 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall17001972009-10-18 01:05:36 +00002757 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2758 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2759 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2760 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002761}
John McCallfc93cf92009-10-22 22:37:11 +00002762void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2763 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallfc93cf92009-10-22 22:37:11 +00002764}
John McCall8f115c62009-10-16 21:56:05 +00002765
Sebastian Redlc67764e2010-07-22 22:43:28 +00002766TypeSourceInfo *PCHReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2767 const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002768 unsigned &Idx) {
2769 QualType InfoTy = GetType(Record[Idx++]);
2770 if (InfoTy.isNull())
2771 return 0;
2772
John McCallbcd03502009-12-07 02:54:59 +00002773 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
Sebastian Redlc67764e2010-07-22 22:43:28 +00002774 TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002775 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002776 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002777 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002778}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002779
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002780QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002781 unsigned FastQuals = ID & Qualifiers::FastMask;
2782 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002783
2784 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2785 QualType T;
2786 switch ((pch::PredefinedTypeIDs)Index) {
2787 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002788 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2789 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002790
2791 case pch::PREDEF_TYPE_CHAR_U_ID:
2792 case pch::PREDEF_TYPE_CHAR_S_ID:
2793 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002794 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002795 break;
2796
Chris Lattner8575daa2009-04-27 21:45:14 +00002797 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2798 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2799 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2800 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2801 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002802 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002803 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2804 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2805 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2806 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2807 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2808 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002809 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002810 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2811 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2812 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2813 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2814 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002815 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002816 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2817 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002818 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2819 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002820 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002821 }
2822
2823 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002824 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002825 }
2826
2827 Index -= pch::NUM_PREDEF_TYPE_IDS;
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002828 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl409183f2010-07-14 20:26:45 +00002829 if (TypesLoaded[Index].isNull()) {
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002830 TypesLoaded[Index] = ReadTypeRecord(Index);
Sebastian Redl409183f2010-07-14 20:26:45 +00002831 TypesLoaded[Index]->setFromPCH();
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002832 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002833 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2834 TypesLoaded[Index]);
Sebastian Redl409183f2010-07-14 20:26:45 +00002835 }
Mike Stump11289f42009-09-09 15:08:12 +00002836
John McCall8ccfcb52009-09-24 19:53:00 +00002837 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002838}
2839
John McCall0ad16662009-10-29 08:12:44 +00002840TemplateArgumentLocInfo
2841PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Sebastian Redlc67764e2010-07-22 22:43:28 +00002842 llvm::BitstreamCursor &DeclsCursor,
John McCall0ad16662009-10-29 08:12:44 +00002843 const RecordData &Record,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002844 unsigned &Index) {
John McCall0ad16662009-10-29 08:12:44 +00002845 switch (Kind) {
2846 case TemplateArgument::Expression:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002847 return ReadExpr(DeclsCursor);
John McCall0ad16662009-10-29 08:12:44 +00002848 case TemplateArgument::Type:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002849 return GetTypeSourceInfo(DeclsCursor, Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002850 case TemplateArgument::Template: {
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002851 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2852 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2853 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002854 }
John McCall0ad16662009-10-29 08:12:44 +00002855 case TemplateArgument::Null:
2856 case TemplateArgument::Integral:
2857 case TemplateArgument::Declaration:
2858 case TemplateArgument::Pack:
2859 return TemplateArgumentLocInfo();
2860 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002861 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002862 return TemplateArgumentLocInfo();
2863}
2864
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002865TemplateArgumentLoc
Sebastian Redlc67764e2010-07-22 22:43:28 +00002866PCHReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
2867 const RecordData &Record, unsigned &Index) {
2868 TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002869
2870 if (Arg.getKind() == TemplateArgument::Expression) {
2871 if (Record[Index++]) // bool InfoHasSameExpr.
2872 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2873 }
2874 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002875 DeclsCursor,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002876 Record, Index));
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00002877}
2878
John McCall75b960e2010-06-01 09:23:16 +00002879Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2880 return GetDecl(ID);
2881}
2882
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002883TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002884 if (!DeclsLoaded[0]) {
Argyrios Kyrtzidis839bbac2010-08-03 17:30:10 +00002885 ReadDeclRecord(0, 0);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002886 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002887 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002888 }
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002889
2890 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2891}
2892
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002893Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002894 if (ID == 0)
2895 return 0;
2896
Douglas Gregor745ed142009-04-25 18:35:21 +00002897 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002898 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002899 return 0;
2900 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002901
Douglas Gregor745ed142009-04-25 18:35:21 +00002902 unsigned Index = ID - 1;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002903 if (!DeclsLoaded[Index]) {
Argyrios Kyrtzidis839bbac2010-08-03 17:30:10 +00002904 ReadDeclRecord(Index, ID);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002905 if (DeserializationListener)
2906 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2907 }
Douglas Gregor745ed142009-04-25 18:35:21 +00002908
2909 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002910}
2911
Chris Lattner9c28af02009-04-27 05:46:25 +00002912/// \brief Resolve the offset of a statement into a statement.
2913///
2914/// This operation will read a new statement from the external
2915/// source each time it is called, and is meant to be used via a
2916/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall75b960e2010-06-01 09:23:16 +00002917Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Sebastian Redl5c415f32010-07-22 17:01:13 +00002918 // Offset here is a global offset across the entire chain.
2919 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2920 PerFileData &F = *Chain[N - I - 1];
2921 if (Offset < F.SizeInBits) {
2922 // Since we know that this statement is part of a decl, make sure to use
2923 // the decl cursor to read it.
2924 F.DeclsCursor.JumpToBit(Offset);
2925 return ReadStmtFromStream(F.DeclsCursor);
2926 }
2927 Offset -= F.SizeInBits;
2928 }
2929 llvm_unreachable("Broken chain");
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002930}
2931
John McCall75b960e2010-06-01 09:23:16 +00002932bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2933 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002934 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002935 "DeclContext has no lexical decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002936
Sebastian Redl5c415f32010-07-22 17:01:13 +00002937 // There might be lexical decls in multiple parts of the chain, for the TU
2938 // at least.
2939 DeclContextInfos &Infos = DeclContextOffsets[DC];
2940 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2941 I != E; ++I) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002942 // IDs can be 0 if this context doesn't contain declarations.
2943 if (!I->LexicalDecls)
Sebastian Redl5c415f32010-07-22 17:01:13 +00002944 continue;
Sebastian Redl5c415f32010-07-22 17:01:13 +00002945
2946 // Load all of the declaration IDs
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002947 for (const pch::DeclID *ID = I->LexicalDecls,
2948 *IDE = ID + I->NumLexicalDecls;
2949 ID != IDE; ++ID)
2950 Decls.push_back(GetDecl(*ID));
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002951 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002952
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002953 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002954 return false;
2955}
2956
John McCall75b960e2010-06-01 09:23:16 +00002957DeclContext::lookup_result
2958PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2959 DeclarationName Name) {
Mike Stump11289f42009-09-09 15:08:12 +00002960 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002961 "DeclContext has no visible decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002962
John McCall75b960e2010-06-01 09:23:16 +00002963 llvm::SmallVector<VisibleDeclaration, 64> Decls;
Sebastian Redl5c415f32010-07-22 17:01:13 +00002964 // There might be lexical decls in multiple parts of the chain, for the TU
2965 // and namespaces.
2966 DeclContextInfos &Infos = DeclContextOffsets[DC];
2967 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2968 I != E; ++I) {
2969 uint64_t Offset = I->OffsetToVisibleDecls;
2970 if (Offset == 0)
2971 continue;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002972
Sebastian Redl5c415f32010-07-22 17:01:13 +00002973 llvm::BitstreamCursor &DeclsCursor = *I->Stream;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002974
Sebastian Redl5c415f32010-07-22 17:01:13 +00002975 // Keep track of where we are in the stream, then jump back there
2976 // after reading this context.
2977 SavedStreamPosition SavedPosition(DeclsCursor);
2978
2979 // Load the record containing all of the declarations visible in
2980 // this context.
2981 DeclsCursor.JumpToBit(Offset);
2982 RecordData Record;
2983 unsigned Code = DeclsCursor.ReadCode();
2984 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2985 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2986 Error("Expected visible block");
2987 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2988 DeclContext::lookup_iterator());
2989 }
2990
2991 if (Record.empty())
2992 continue;
2993
2994 unsigned Idx = 0;
2995 while (Idx < Record.size()) {
2996 Decls.push_back(VisibleDeclaration());
2997 Decls.back().Name = ReadDeclarationName(Record, Idx);
2998
2999 unsigned Size = Record[Idx++];
3000 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
3001 LoadedDecls.reserve(Size);
3002 for (unsigned J = 0; J < Size; ++J)
3003 LoadedDecls.push_back(Record[Idx++]);
3004 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003005 }
3006
Douglas Gregora57c3ab2009-04-22 22:34:57 +00003007 ++NumVisibleDeclContextsRead;
John McCall75b960e2010-06-01 09:23:16 +00003008
3009 SetExternalVisibleDecls(DC, Decls);
3010 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003011}
3012
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003013void PCHReader::PassInterestingDeclsToConsumer() {
3014 assert(Consumer);
3015 while (!InterestingDecls.empty()) {
3016 DeclGroupRef DG(InterestingDecls.front());
3017 InterestingDecls.pop_front();
3018 Consumer->HandleTopLevelDecl(DG);
3019 }
3020}
3021
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003022void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00003023 this->Consumer = Consumer;
3024
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003025 if (!Consumer)
3026 return;
3027
3028 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003029 // Force deserialization of this decl, which will cause it to be queued for
3030 // passing to the consumer.
Daniel Dunbar865c2a72009-09-17 03:06:44 +00003031 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003032 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00003033
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003034 PassInterestingDeclsToConsumer();
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003035}
3036
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003037void PCHReader::PrintStats() {
3038 std::fprintf(stderr, "*** PCH Statistics:\n");
3039
Mike Stump11289f42009-09-09 15:08:12 +00003040 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00003041 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00003042 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00003043 unsigned NumDeclsLoaded
3044 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3045 (Decl *)0);
3046 unsigned NumIdentifiersLoaded
3047 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3048 IdentifiersLoaded.end(),
3049 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00003050 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00003051 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3052 SelectorsLoaded.end(),
3053 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00003054
Douglas Gregorc5046832009-04-27 18:38:38 +00003055 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
3056 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00003057 if (TotalNumSLocEntries)
3058 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
3059 NumSLocEntriesRead, TotalNumSLocEntries,
3060 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00003061 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003062 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00003063 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3064 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3065 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003066 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00003067 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3068 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00003069 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003070 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00003071 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3072 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Sebastian Redlada023c2010-08-04 20:40:17 +00003073 if (!SelectorsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003074 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
Sebastian Redlada023c2010-08-04 20:40:17 +00003075 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
3076 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003077 if (TotalNumStatements)
3078 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3079 NumStatementsRead, TotalNumStatements,
3080 ((float)NumStatementsRead/TotalNumStatements * 100));
3081 if (TotalNumMacros)
3082 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3083 NumMacrosRead, TotalNumMacros,
3084 ((float)NumMacrosRead/TotalNumMacros * 100));
3085 if (TotalLexicalDeclContexts)
3086 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3087 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3088 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3089 * 100));
3090 if (TotalVisibleDeclContexts)
3091 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3092 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3093 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3094 * 100));
Sebastian Redlada023c2010-08-04 20:40:17 +00003095#if 0
3096 if (TotalSelectorsInSelector) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00003097 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
Sebastian Redlada023c2010-08-04 20:40:17 +00003098 NumSelectorSelectorsRead, TotalSelectorsInSelector,
3099 ((float)NumSelectorSelectorsRead/TotalSelectorsInSelector
Douglas Gregor95c13f52009-04-25 17:48:32 +00003100 * 100));
Sebastian Redlada023c2010-08-04 20:40:17 +00003101 std::fprintf(stderr, " %u method pool misses\n", NumSelectorMisses);
Douglas Gregor95c13f52009-04-25 17:48:32 +00003102 }
Sebastian Redlada023c2010-08-04 20:40:17 +00003103#endif
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003104 std::fprintf(stderr, "\n");
3105}
3106
Douglas Gregora868bbd2009-04-21 22:25:48 +00003107void PCHReader::InitializeSema(Sema &S) {
3108 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003109 S.ExternalSource = this;
3110
Douglas Gregor7cd60f72009-04-22 21:15:06 +00003111 // Makes sure any declarations that were deserialized "too early"
3112 // still get added to the identifier's declaration chains.
3113 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3114 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3115 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003116 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00003117 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00003118
3119 // If there were any tentative definitions, deserialize them and add
Sebastian Redl35351a92010-01-31 22:27:38 +00003120 // them to Sema's list of tentative definitions.
Douglas Gregord4df8652009-04-22 22:02:47 +00003121 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3122 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redl35351a92010-01-31 22:27:38 +00003123 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregord4df8652009-04-22 22:02:47 +00003124 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00003125
Tanya Lattner90073802010-02-12 00:07:30 +00003126 // If there were any unused static functions, deserialize them and add to
3127 // Sema's list of unused static functions.
3128 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
3129 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3130 SemaObj->UnusedStaticFuncs.push_back(FD);
3131 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00003132
3133 // If there were any locally-scoped external declarations,
3134 // deserialize them and add them to Sema's table of locally-scoped
3135 // external declarations.
3136 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3137 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3138 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3139 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00003140
3141 // If there were any ext_vector type declarations, deserialize them
3142 // and add them to Sema's vector of such declarations.
3143 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3144 SemaObj->ExtVectorDecls.push_back(
3145 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00003146
3147 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3148 // Can we cut them down before writing them ?
3149
3150 // If there were any VTable uses, deserialize the information and add it
3151 // to Sema's vector and map of VTable uses.
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00003152 if (!VTableUses.empty()) {
3153 unsigned Idx = 0;
3154 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3155 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3156 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3157 bool DefinitionRequired = VTableUses[Idx++];
3158 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3159 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3160 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00003161 }
3162
3163 // If there were any dynamic classes declarations, deserialize them
3164 // and add them to Sema's vector of such declarations.
3165 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3166 SemaObj->DynamicClasses.push_back(
3167 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003168
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003169 // Load the offsets of the declarations that Sema references.
3170 // They will be lazily deserialized when needed.
3171 if (!SemaDeclRefs.empty()) {
3172 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
3173 SemaObj->StdNamespace = SemaDeclRefs[0];
3174 SemaObj->StdBadAlloc = SemaDeclRefs[1];
3175 }
3176
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003177 // If there are @selector references added them to its pool. This is for
3178 // implementation of -Wselector.
Sebastian Redlada023c2010-08-04 20:40:17 +00003179 if (!ReferencedSelectorsData.empty()) {
3180 unsigned int DataSize = ReferencedSelectorsData.size()-1;
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003181 unsigned I = 0;
3182 while (I < DataSize) {
Sebastian Redlada023c2010-08-04 20:40:17 +00003183 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003184 SourceLocation SelLoc =
Sebastian Redlada023c2010-08-04 20:40:17 +00003185 SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003186 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3187 }
3188 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00003189}
3190
3191IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
Sebastian Redl78f51772010-08-02 18:30:12 +00003192 // Try to find this name within our on-disk hash tables. We start with the
3193 // most recent one, since that one contains the most up-to-date info.
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003194 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3195 PCHIdentifierLookupTable *IdTable
Sebastian Redl78f51772010-08-02 18:30:12 +00003196 = (PCHIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
Sebastian Redl5c415f32010-07-22 17:01:13 +00003197 if (!IdTable)
3198 continue;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003199 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3200 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3201 if (Pos == IdTable->end())
3202 continue;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003203
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003204 // Dereferencing the iterator has the effect of building the
3205 // IdentifierInfo node and populating it with the various
3206 // declarations it needs.
Sebastian Redl78f51772010-08-02 18:30:12 +00003207 return *Pos;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003208 }
Sebastian Redl78f51772010-08-02 18:30:12 +00003209 return 0;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003210}
3211
Mike Stump11289f42009-09-09 15:08:12 +00003212std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00003213PCHReader::ReadMethodPool(Selector Sel) {
Sebastian Redlada023c2010-08-04 20:40:17 +00003214 // Find this selector in a hash table. We want to find the most recent entry.
3215 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3216 PerFileData &F = *Chain[I];
3217 if (!F.SelectorLookupTable)
3218 continue;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003219
Sebastian Redlada023c2010-08-04 20:40:17 +00003220 PCHSelectorLookupTable *PoolTable
3221 = (PCHSelectorLookupTable*)F.SelectorLookupTable;
3222 PCHSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
3223 if (Pos != PoolTable->end()) {
3224 ++NumSelectorsRead;
3225 PCHSelectorLookupTrait::data_type Data = *Pos;
3226 if (DeserializationListener)
3227 DeserializationListener->SelectorRead(Data.ID, Sel);
3228 return std::make_pair(Data.Instance, Data.Factory);
3229 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003230 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003231
Sebastian Redlada023c2010-08-04 20:40:17 +00003232 ++NumSelectorMisses;
3233 return std::pair<ObjCMethodList, ObjCMethodList>();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003234}
3235
Sebastian Redld95a56e2010-08-04 18:21:41 +00003236void PCHReader::LoadSelector(Selector Sel) {
3237 // It would be complicated to avoid reading the methods anyway. So don't.
3238 ReadMethodPool(Sel);
3239}
3240
Douglas Gregor0e149972009-04-25 19:10:14 +00003241void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00003242 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003243 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00003244 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlff4a2952010-07-23 23:49:55 +00003245 if (DeserializationListener)
3246 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003247}
3248
Douglas Gregor1342e842009-07-06 18:54:52 +00003249/// \brief Set the globally-visible declarations associated with the given
3250/// identifier.
3251///
3252/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00003253/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00003254/// them.
3255///
3256/// \param II an IdentifierInfo that refers to one or more globally-visible
3257/// declarations.
3258///
3259/// \param DeclIDs the set of declaration IDs with the name @p II that are
3260/// visible at global scope.
3261///
3262/// \param Nonrecursive should be true to indicate that the caller knows that
3263/// this call is non-recursive, and therefore the globally-visible declarations
3264/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00003265void
3266PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00003267 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3268 bool Nonrecursive) {
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003269 if (NumCurrentElementsDeserializing && !Nonrecursive) {
Douglas Gregor1342e842009-07-06 18:54:52 +00003270 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3271 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3272 PII.II = II;
3273 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3274 PII.DeclIDs.push_back(DeclIDs[I]);
3275 return;
3276 }
Mike Stump11289f42009-09-09 15:08:12 +00003277
Douglas Gregor1342e842009-07-06 18:54:52 +00003278 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3279 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3280 if (SemaObj) {
3281 // Introduce this declaration into the translation-unit scope
3282 // and add it to the declaration chain for this identifier, so
3283 // that (unqualified) name lookup will find it.
3284 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3285 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3286 } else {
3287 // Queue this declaration so that it will be added to the
3288 // translation unit scope and identifier's declaration chain
3289 // once a Sema object is known.
3290 PreloadedDecls.push_back(D);
3291 }
3292 }
3293}
3294
Chris Lattnerc523d8e2009-04-11 21:15:38 +00003295IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003296 if (ID == 0)
3297 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003298
Sebastian Redlc713b962010-07-21 00:46:22 +00003299 if (IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003300 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003301 return 0;
3302 }
Mike Stump11289f42009-09-09 15:08:12 +00003303
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003304 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redlc713b962010-07-21 00:46:22 +00003305 ID -= 1;
3306 if (!IdentifiersLoaded[ID]) {
3307 unsigned Index = ID;
3308 const char *Str = 0;
3309 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3310 PerFileData *F = Chain[N - I - 1];
3311 if (Index < F->LocalNumIdentifiers) {
3312 uint32_t Offset = F->IdentifierOffsets[Index];
3313 Str = F->IdentifierTableData + Offset;
3314 break;
3315 }
3316 Index -= F->LocalNumIdentifiers;
3317 }
3318 assert(Str && "Broken Chain");
Douglas Gregor5287b4e2009-04-25 21:04:17 +00003319
Douglas Gregorab4df582009-04-28 20:01:51 +00003320 // All of the strings in the PCH file are preceded by a 16-bit
3321 // length. Extract that 16-bit length to avoid having to execute
3322 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00003323 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3324 // unsigned integers. This is important to avoid integer overflow when
3325 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00003326 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00003327 unsigned StrLen = (((unsigned) StrLenPtr[0])
3328 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redlc713b962010-07-21 00:46:22 +00003329 IdentifiersLoaded[ID]
Kovarththanan Rajaratnama3b09592010-03-12 10:32:27 +00003330 = &PP->getIdentifierTable().get(Str, StrLen);
Sebastian Redlff4a2952010-07-23 23:49:55 +00003331 if (DeserializationListener)
3332 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003333 }
Mike Stump11289f42009-09-09 15:08:12 +00003334
Sebastian Redlc713b962010-07-21 00:46:22 +00003335 return IdentifiersLoaded[ID];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003336}
3337
Douglas Gregor258ae542009-04-27 06:38:32 +00003338void PCHReader::ReadSLocEntry(unsigned ID) {
3339 ReadSLocEntryRecord(ID);
3340}
3341
Steve Naroff2ddea052009-04-23 10:39:46 +00003342Selector PCHReader::DecodeSelector(unsigned ID) {
3343 if (ID == 0)
3344 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00003345
Sebastian Redlada023c2010-08-04 20:40:17 +00003346 if (ID > SelectorsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003347 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00003348 return Selector();
3349 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003350
Sebastian Redlada023c2010-08-04 20:40:17 +00003351 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00003352 // Load this selector from the selector table.
Sebastian Redlada023c2010-08-04 20:40:17 +00003353 unsigned Idx = ID - 1;
3354 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3355 PerFileData &F = *Chain[N - I - 1];
3356 if (Idx < F.LocalNumSelectors) {
3357 PCHSelectorLookupTrait Trait(*this);
3358 SelectorsLoaded[ID - 1] =
3359 Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0);
3360 if (DeserializationListener)
3361 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
3362 break;
3363 }
3364 Idx -= F.LocalNumSelectors;
3365 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003366 }
3367
Sebastian Redlada023c2010-08-04 20:40:17 +00003368 return SelectorsLoaded[ID - 1];
Steve Naroff2ddea052009-04-23 10:39:46 +00003369}
3370
John McCall75b960e2010-06-01 09:23:16 +00003371Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003372 return DecodeSelector(ID);
3373}
3374
John McCall75b960e2010-06-01 09:23:16 +00003375uint32_t PCHReader::GetNumExternalSelectors() {
Sebastian Redlada023c2010-08-04 20:40:17 +00003376 // ID 0 (the null selector) is considered an external selector.
3377 return getTotalNumSelectors() + 1;
Douglas Gregord720daf2010-04-06 17:30:22 +00003378}
3379
Mike Stump11289f42009-09-09 15:08:12 +00003380DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003381PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3382 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3383 switch (Kind) {
3384 case DeclarationName::Identifier:
3385 return DeclarationName(GetIdentifierInfo(Record, Idx));
3386
3387 case DeclarationName::ObjCZeroArgSelector:
3388 case DeclarationName::ObjCOneArgSelector:
3389 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00003390 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003391
3392 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003393 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003394 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003395
3396 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003397 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003398 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003399
3400 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003401 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003402 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003403
3404 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003405 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003406 (OverloadedOperatorKind)Record[Idx++]);
3407
Alexis Hunt3d221f22009-11-29 07:34:05 +00003408 case DeclarationName::CXXLiteralOperatorName:
3409 return Context->DeclarationNames.getCXXLiteralOperatorName(
3410 GetIdentifierInfo(Record, Idx));
3411
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003412 case DeclarationName::CXXUsingDirective:
3413 return DeclarationName::getUsingDirectiveName();
3414 }
3415
3416 // Required to silence GCC warning
3417 return DeclarationName();
3418}
Douglas Gregor55abb232009-04-10 20:39:37 +00003419
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003420TemplateName
3421PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3422 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3423 switch (Kind) {
3424 case TemplateName::Template:
3425 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3426
3427 case TemplateName::OverloadedTemplate: {
3428 unsigned size = Record[Idx++];
3429 UnresolvedSet<8> Decls;
3430 while (size--)
3431 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3432
3433 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3434 }
3435
3436 case TemplateName::QualifiedTemplate: {
3437 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3438 bool hasTemplKeyword = Record[Idx++];
3439 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3440 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3441 }
3442
3443 case TemplateName::DependentTemplate: {
3444 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3445 if (Record[Idx++]) // isIdentifier
3446 return Context->getDependentTemplateName(NNS,
3447 GetIdentifierInfo(Record, Idx));
3448 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00003449 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003450 }
3451 }
3452
3453 assert(0 && "Unhandled template name kind!");
3454 return TemplateName();
3455}
3456
3457TemplateArgument
Sebastian Redlc67764e2010-07-22 22:43:28 +00003458PCHReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3459 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003460 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3461 case TemplateArgument::Null:
3462 return TemplateArgument();
3463 case TemplateArgument::Type:
3464 return TemplateArgument(GetType(Record[Idx++]));
3465 case TemplateArgument::Declaration:
3466 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidis0b0369a2010-06-28 09:31:34 +00003467 case TemplateArgument::Integral: {
3468 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3469 QualType T = GetType(Record[Idx++]);
3470 return TemplateArgument(Value, T);
3471 }
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003472 case TemplateArgument::Template:
3473 return TemplateArgument(ReadTemplateName(Record, Idx));
3474 case TemplateArgument::Expression:
Sebastian Redlc67764e2010-07-22 22:43:28 +00003475 return TemplateArgument(ReadExpr(DeclsCursor));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003476 case TemplateArgument::Pack: {
3477 unsigned NumArgs = Record[Idx++];
3478 llvm::SmallVector<TemplateArgument, 8> Args;
3479 Args.reserve(NumArgs);
3480 while (NumArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00003481 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003482 TemplateArgument TemplArg;
3483 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3484 return TemplArg;
3485 }
3486 }
3487
3488 assert(0 && "Unhandled template argument kind!");
3489 return TemplateArgument();
3490}
3491
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003492TemplateParameterList *
3493PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3494 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3495 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3496 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3497
3498 unsigned NumParams = Record[Idx++];
3499 llvm::SmallVector<NamedDecl *, 16> Params;
3500 Params.reserve(NumParams);
3501 while (NumParams--)
3502 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3503
3504 TemplateParameterList* TemplateParams =
3505 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3506 Params.data(), Params.size(), RAngleLoc);
3507 return TemplateParams;
3508}
3509
3510void
3511PCHReader::
3512ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
Sebastian Redlc67764e2010-07-22 22:43:28 +00003513 llvm::BitstreamCursor &DeclsCursor,
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003514 const RecordData &Record, unsigned &Idx) {
3515 unsigned NumTemplateArgs = Record[Idx++];
3516 TemplArgs.reserve(NumTemplateArgs);
3517 while (NumTemplateArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00003518 TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003519}
3520
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00003521/// \brief Read a UnresolvedSet structure.
3522void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3523 const RecordData &Record, unsigned &Idx) {
3524 unsigned NumDecls = Record[Idx++];
3525 while (NumDecls--) {
3526 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3527 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3528 Set.addDecl(D, AS);
3529 }
3530}
3531
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003532CXXBaseSpecifier
Nick Lewycky19b9f952010-07-26 16:56:01 +00003533PCHReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
3534 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003535 bool isVirtual = static_cast<bool>(Record[Idx++]);
3536 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3537 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Nick Lewycky19b9f952010-07-26 16:56:01 +00003538 TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003539 SourceRange Range = ReadSourceRange(Record, Idx);
Nick Lewycky19b9f952010-07-26 16:56:01 +00003540 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003541}
3542
Chris Lattnerca025db2010-05-07 21:43:38 +00003543NestedNameSpecifier *
3544PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3545 unsigned N = Record[Idx++];
3546 NestedNameSpecifier *NNS = 0, *Prev = 0;
3547 for (unsigned I = 0; I != N; ++I) {
3548 NestedNameSpecifier::SpecifierKind Kind
3549 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3550 switch (Kind) {
3551 case NestedNameSpecifier::Identifier: {
3552 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3553 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3554 break;
3555 }
3556
3557 case NestedNameSpecifier::Namespace: {
3558 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3559 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3560 break;
3561 }
3562
3563 case NestedNameSpecifier::TypeSpec:
3564 case NestedNameSpecifier::TypeSpecWithTemplate: {
3565 Type *T = GetType(Record[Idx++]).getTypePtr();
3566 bool Template = Record[Idx++];
3567 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3568 break;
3569 }
3570
3571 case NestedNameSpecifier::Global: {
3572 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3573 // No associated value, and there can't be a prefix.
3574 break;
3575 }
Chris Lattnerca025db2010-05-07 21:43:38 +00003576 }
Argyrios Kyrtzidisad65c692010-07-07 15:46:30 +00003577 Prev = NNS;
Chris Lattnerca025db2010-05-07 21:43:38 +00003578 }
3579 return NNS;
3580}
3581
3582SourceRange
3583PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar6d3bc082010-06-02 15:47:10 +00003584 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3585 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3586 return SourceRange(beg, end);
Chris Lattnerca025db2010-05-07 21:43:38 +00003587}
3588
Douglas Gregor1daeb692009-04-13 18:14:40 +00003589/// \brief Read an integral value
3590llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3591 unsigned BitWidth = Record[Idx++];
3592 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3593 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3594 Idx += NumWords;
3595 return Result;
3596}
3597
3598/// \brief Read a signed integral value
3599llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3600 bool isUnsigned = Record[Idx++];
3601 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3602}
3603
Douglas Gregore0a3a512009-04-14 21:55:33 +00003604/// \brief Read a floating-point value
3605llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00003606 return llvm::APFloat(ReadAPInt(Record, Idx));
3607}
3608
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003609// \brief Read a string
3610std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3611 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00003612 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003613 Idx += Len;
3614 return Result;
3615}
3616
Chris Lattnercba86142010-05-10 00:25:06 +00003617CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3618 unsigned &Idx) {
3619 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3620 return CXXTemporary::Create(*Context, Decl);
3621}
3622
Douglas Gregor55abb232009-04-10 20:39:37 +00003623DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00003624 return Diag(SourceLocation(), DiagID);
3625}
3626
3627DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003628 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00003629}
Douglas Gregora9af1d12009-04-17 00:04:06 +00003630
Douglas Gregora868bbd2009-04-21 22:25:48 +00003631/// \brief Retrieve the identifier table associated with the
3632/// preprocessor.
3633IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003634 assert(PP && "Forgot to set Preprocessor ?");
3635 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00003636}
3637
Douglas Gregora9af1d12009-04-17 00:04:06 +00003638/// \brief Record that the given ID maps to the given switch-case
3639/// statement.
3640void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3641 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3642 SwitchCaseStmts[ID] = SC;
3643}
3644
3645/// \brief Retrieve the switch-case statement with the given ID.
3646SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3647 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3648 return SwitchCaseStmts[ID];
3649}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003650
3651/// \brief Record that the given label statement has been
3652/// deserialized and has the given ID.
3653void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00003654 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003655 "Deserialized label twice");
3656 LabelStmts[ID] = S;
3657
3658 // If we've already seen any goto statements that point to this
3659 // label, resolve them now.
3660 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3661 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3662 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3663 Goto->second->setLabel(S);
3664 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00003665
3666 // If we've already seen any address-label statements that point to
3667 // this label, resolve them now.
3668 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00003669 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00003670 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00003671 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00003672 AddrLabel != AddrLabels.second; ++AddrLabel)
3673 AddrLabel->second->setLabel(S);
3674 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003675}
3676
3677/// \brief Set the label of the given statement to the label
3678/// identified by ID.
3679///
3680/// Depending on the order in which the label and other statements
3681/// referencing that label occur, this operation may complete
3682/// immediately (updating the statement) or it may queue the
3683/// statement to be back-patched later.
3684void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3685 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3686 if (Label != LabelStmts.end()) {
3687 // We've already seen this label, so set the label of the goto and
3688 // we're done.
3689 S->setLabel(Label->second);
3690 } else {
3691 // We haven't seen this label yet, so add this goto to the set of
3692 // unresolved goto statements.
3693 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3694 }
3695}
Douglas Gregor779d8652009-04-17 18:58:21 +00003696
3697/// \brief Set the label of the given expression to the label
3698/// identified by ID.
3699///
3700/// Depending on the order in which the label and other statements
3701/// referencing that label occur, this operation may complete
3702/// immediately (updating the statement) or it may queue the
3703/// statement to be back-patched later.
3704void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3705 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3706 if (Label != LabelStmts.end()) {
3707 // We've already seen this label, so set the label of the
3708 // label-address expression and we're done.
3709 S->setLabel(Label->second);
3710 } else {
3711 // We haven't seen this label yet, so add this label-address
3712 // expression to the set of unresolved label-address expressions.
3713 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3714 }
3715}
Douglas Gregor1342e842009-07-06 18:54:52 +00003716
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003717void PCHReader::FinishedDeserializing() {
3718 assert(NumCurrentElementsDeserializing &&
3719 "FinishedDeserializing not paired with StartedDeserializing");
3720 if (NumCurrentElementsDeserializing == 1) {
Douglas Gregor1342e842009-07-06 18:54:52 +00003721 // If any identifiers with corresponding top-level declarations have
3722 // been loaded, load those declarations now.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003723 while (!PendingIdentifierInfos.empty()) {
3724 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
3725 PendingIdentifierInfos.front().DeclIDs, true);
3726 PendingIdentifierInfos.pop_front();
Douglas Gregor1342e842009-07-06 18:54:52 +00003727 }
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003728
3729 // We are not in recursive loading, so it's safe to pass the "interesting"
3730 // decls to the consumer.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003731 if (Consumer)
3732 PassInterestingDeclsToConsumer();
Douglas Gregor1342e842009-07-06 18:54:52 +00003733 }
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003734 --NumCurrentElementsDeserializing;
Douglas Gregor1342e842009-07-06 18:54:52 +00003735}