blob: 00aee491d644753f808ae74a08ad476ccdfd1b85 [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();
173 for (;;) {
174 // Compare the current pieces.
175 if (LR.size() == RR.size()) {
176 // If they're the same length, it's pretty easy.
177 if (LR != RR)
178 return false;
179 // Both pieces are done, advance.
180 ++LI;
181 ++RI;
182 // If either string is done, they're both done, since they're the same
183 // length.
184 if (LI == LN) {
185 assert(RI == RN && "Strings not the same length after all?");
186 return true;
187 }
188 LR = L[LI];
189 RR = R[RI].Data;
190 } else if (LR.size() < RR.size()) {
191 // Right piece is longer.
192 if (!RR.startswith(LR))
193 return false;
194 ++LI;
195 assert(LI != LN && "Strings not the same length after all?");
196 RR = RR.substr(LR.size());
197 LR = L[LI];
198 } else {
199 // Left piece is longer.
200 if (!LR.startswith(RR))
201 return false;
202 ++RI;
203 assert(RI != RN && "Strings not the same length after all?");
204 LR = LR.substr(RR.size());
205 RR = R[RI].Data;
206 }
207 }
208}
209
210static std::pair<FileID, llvm::StringRef::size_type>
211FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
212 std::pair<FileID, llvm::StringRef::size_type> Res;
213 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
214 Res.second = Buffers[I].Data.find(MacroDef);
215 if (Res.second != llvm::StringRef::npos) {
216 Res.first = Buffers[I].BufferID;
217 break;
218 }
219 }
220 return Res;
221}
222
223bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000224 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000225 std::string &SuggestedPredefines) {
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000226 // We are in the context of an implicit include, so the predefines buffer will
227 // have a #include entry for the PCH file itself (as normalized by the
228 // preprocessor initialization). Find it and skip over it in the checking
229 // below.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000230 llvm::SmallString<256> PCHInclude;
231 PCHInclude += "#include \"";
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000232 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000233 PCHInclude += "\"\n";
234 std::pair<llvm::StringRef,llvm::StringRef> Split =
235 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
236 llvm::StringRef Left = Split.first, Right = Split.second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000237 if (Left == PP.getPredefines()) {
238 Error("Missing PCH include entry!");
239 return true;
240 }
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000241
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000242 // If the concatenation of all the PCH buffers is equal to the adjusted
243 // command line, we're done.
244 // We build a SmallVector of the command line here, because we'll eventually
245 // need to support an arbitrary amount of pieces anyway (when we have chained
246 // PCH reading).
247 llvm::SmallVector<llvm::StringRef, 2> CommandLine;
248 CommandLine.push_back(Left);
249 CommandLine.push_back(Right);
250 if (EqualConcatenations(CommandLine, Buffers))
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000251 return false;
252
253 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000254
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000255 // The predefines buffers are different. Determine what the differences are,
256 // and whether they require us to reject the PCH file.
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000257 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000258 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
259 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000260
261 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
262 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
263 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000264
Daniel Dunbar499baed2009-11-11 05:26:28 +0000265 // Sort both sets of predefined buffer lines, since we allow some extra
266 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000267 std::sort(CmdLineLines.begin(), CmdLineLines.end());
268 std::sort(PCHLines.begin(), PCHLines.end());
269
Daniel Dunbar499baed2009-11-11 05:26:28 +0000270 // Determine which predefines that were used to build the PCH file are missing
271 // from the command line.
272 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000273 std::set_difference(PCHLines.begin(), PCHLines.end(),
274 CmdLineLines.begin(), CmdLineLines.end(),
275 std::back_inserter(MissingPredefines));
276
277 bool MissingDefines = false;
278 bool ConflictingDefines = false;
279 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000280 llvm::StringRef Missing = MissingPredefines[I];
281 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000282 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
283 return true;
284 }
Mike Stump11289f42009-09-09 15:08:12 +0000285
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000286 // This is a macro definition. Determine the name of the macro we're
287 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000288 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000289 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000290 = Missing.find_first_of("( \n\r", StartOfMacroName);
291 assert(EndOfMacroName != std::string::npos &&
292 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000293 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000294
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000295 // Determine whether this macro was given a different definition on the
296 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000297 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000298 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000299 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000300 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
301 MacroDefStart);
302 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000303 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000304 // Different macro; we're done.
305 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000306 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000307 }
Mike Stump11289f42009-09-09 15:08:12 +0000308
309 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000310 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000311 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000312 (*ConflictPos)[MacroDefLen] != '(')
313 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000314
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000315 // We found a conflicting macro definition.
316 break;
317 }
Mike Stump11289f42009-09-09 15:08:12 +0000318
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000319 if (ConflictPos != CmdLineLines.end()) {
320 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
321 << MacroName;
322
323 // Show the definition of this macro within the PCH file.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000324 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
325 FindMacro(Buffers, Missing);
326 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
327 SourceLocation PCHMissingLoc =
328 SourceMgr.getLocForStartOfFile(MacroLoc.first)
329 .getFileLocWithOffset(MacroLoc.second);
Daniel Dunbar499baed2009-11-11 05:26:28 +0000330 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000331
332 ConflictingDefines = true;
333 continue;
334 }
Mike Stump11289f42009-09-09 15:08:12 +0000335
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000336 // If the macro doesn't conflict, then we'll just pick up the macro
337 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000338 if (ConflictingDefines)
339 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000340
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000341 if (!MissingDefines) {
342 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
343 MissingDefines = true;
344 }
345
346 // Show the definition of this macro within the PCH file.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000347 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
348 FindMacro(Buffers, Missing);
349 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
350 SourceLocation PCHMissingLoc =
351 SourceMgr.getLocForStartOfFile(MacroLoc.first)
352 .getFileLocWithOffset(MacroLoc.second);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000353 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
354 }
Mike Stump11289f42009-09-09 15:08:12 +0000355
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000356 if (ConflictingDefines)
357 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000358
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000359 // Determine what predefines were introduced based on command-line
360 // parameters that were not present when building the PCH
361 // file. Extra #defines are okay, so long as the identifiers being
362 // defined were not used within the precompiled header.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000363 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000364 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
365 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000366 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000367 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000368 llvm::StringRef &Extra = ExtraPredefines[I];
369 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000370 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
371 return true;
372 }
373
374 // This is an extra macro definition. Determine the name of the
375 // macro we're defining.
376 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000377 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000378 = Extra.find_first_of("( \n\r", StartOfMacroName);
379 assert(EndOfMacroName != std::string::npos &&
380 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000381 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000382
383 // Check whether this name was used somewhere in the PCH file. If
384 // so, defining it as a macro could change behavior, so we reject
385 // the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000386 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000387 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000388 return true;
389 }
390
391 // Add this definition to the suggested predefines buffer.
392 SuggestedPredefines += Extra;
393 SuggestedPredefines += '\n';
394 }
395
396 // If we get here, it's because the predefines buffer had compatible
397 // contents. Accept the PCH file.
398 return false;
399}
400
Douglas Gregor5712ebc2010-03-16 16:35:32 +0000401void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
402 unsigned ID) {
403 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
404 ++NumHeaderInfos;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000405}
406
407void PCHValidator::ReadCounter(unsigned Value) {
408 PP.setCounterValue(Value);
409}
410
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000411//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000412// PCH reader implementation
413//===----------------------------------------------------------------------===//
414
Mike Stump11289f42009-09-09 15:08:12 +0000415PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
416 const char *isysroot)
Sebastian Redl85b2a6a2010-07-14 23:45:08 +0000417 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
418 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
419 Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
420 StatCache(0), Consumer(0), IdentifierTableData(0), IdentifierLookupTable(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000421 IdentifierOffsets(0),
422 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
423 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000424 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregor9507d462010-03-19 22:13:20 +0000425 NumPreallocatedPreprocessingEntities(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000426 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump11289f42009-09-09 15:08:12 +0000427 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000428 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000429 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000430 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000431 RelocatablePCH = false;
432}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000433
434PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000435 Diagnostic &Diags, const char *isysroot)
Sebastian Redl85b2a6a2010-07-14 23:45:08 +0000436 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
437 Diags(Diags), SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000438 IdentifierTableData(0), IdentifierLookupTable(0),
439 IdentifierOffsets(0),
440 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
441 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000442 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregor9507d462010-03-19 22:13:20 +0000443 NumPreallocatedPreprocessingEntities(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000444 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump11289f42009-09-09 15:08:12 +0000445 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000446 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000447 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000448 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000449 RelocatablePCH = false;
450}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000451
452PCHReader::~PCHReader() {}
453
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000454
Douglas Gregora868bbd2009-04-21 22:25:48 +0000455namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000456class PCHMethodPoolLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000457 PCHReader &Reader;
458
459public:
460 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
461
462 typedef Selector external_key_type;
463 typedef external_key_type internal_key_type;
464
465 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000466
Douglas Gregorc78d3462009-04-24 21:10:55 +0000467 static bool EqualKey(const internal_key_type& a,
468 const internal_key_type& b) {
469 return a == b;
470 }
Mike Stump11289f42009-09-09 15:08:12 +0000471
Douglas Gregorc78d3462009-04-24 21:10:55 +0000472 static unsigned ComputeHash(Selector Sel) {
473 unsigned N = Sel.getNumArgs();
474 if (N == 0)
475 ++N;
476 unsigned R = 5381;
477 for (unsigned I = 0; I != N; ++I)
478 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000479 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000480 return R;
481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Douglas Gregorc78d3462009-04-24 21:10:55 +0000483 // This hopefully will just get inlined and removed by the optimizer.
484 static const internal_key_type&
485 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000486
Douglas Gregorc78d3462009-04-24 21:10:55 +0000487 static std::pair<unsigned, unsigned>
488 ReadKeyDataLength(const unsigned char*& d) {
489 using namespace clang::io;
490 unsigned KeyLen = ReadUnalignedLE16(d);
491 unsigned DataLen = ReadUnalignedLE16(d);
492 return std::make_pair(KeyLen, DataLen);
493 }
Mike Stump11289f42009-09-09 15:08:12 +0000494
Douglas Gregor95c13f52009-04-25 17:48:32 +0000495 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000496 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000497 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000498 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000499 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000500 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
501 if (N == 0)
502 return SelTable.getNullarySelector(FirstII);
503 else if (N == 1)
504 return SelTable.getUnarySelector(FirstII);
505
506 llvm::SmallVector<IdentifierInfo *, 16> Args;
507 Args.push_back(FirstII);
508 for (unsigned I = 1; I != N; ++I)
509 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
510
Douglas Gregor038c3382009-05-22 22:45:36 +0000511 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000512 }
Mike Stump11289f42009-09-09 15:08:12 +0000513
Douglas Gregorc78d3462009-04-24 21:10:55 +0000514 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
515 using namespace clang::io;
516 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
517 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
518
519 data_type Result;
520
521 // Load instance methods
522 ObjCMethodList *Prev = 0;
523 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000524 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000525 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
526 if (!Result.first.Method) {
527 // This is the first method, which is the easy case.
528 Result.first.Method = Method;
529 Prev = &Result.first;
530 continue;
531 }
532
Ted Kremenekda4abf12010-02-11 00:53:01 +0000533 ObjCMethodList *Mem =
534 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
535 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000536 Prev = Prev->Next;
537 }
538
539 // Load factory methods
540 Prev = 0;
541 for (unsigned I = 0; I != NumFactoryMethods; ++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)));
544 if (!Result.second.Method) {
545 // This is the first method, which is the easy case.
546 Result.second.Method = Method;
547 Prev = &Result.second;
548 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 return Result;
558 }
559};
Mike Stump11289f42009-09-09 15:08:12 +0000560
561} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000562
563/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000564typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000565 PCHMethodPoolLookupTable;
566
567namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000568class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000569 PCHReader &Reader;
570
571 // If we know the IdentifierInfo in advance, it is here and we will
572 // not build a new one. Used when deserializing information about an
573 // identifier that was constructed before the PCH file was read.
574 IdentifierInfo *KnownII;
575
576public:
577 typedef IdentifierInfo * data_type;
578
579 typedef const std::pair<const char*, unsigned> external_key_type;
580
581 typedef external_key_type internal_key_type;
582
Mike Stump11289f42009-09-09 15:08:12 +0000583 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregora868bbd2009-04-21 22:25:48 +0000584 : Reader(Reader), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000585
Douglas Gregora868bbd2009-04-21 22:25:48 +0000586 static bool EqualKey(const internal_key_type& a,
587 const internal_key_type& b) {
588 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
589 : false;
590 }
Mike Stump11289f42009-09-09 15:08:12 +0000591
Douglas Gregora868bbd2009-04-21 22:25:48 +0000592 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000593 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000594 }
Mike Stump11289f42009-09-09 15:08:12 +0000595
Douglas Gregora868bbd2009-04-21 22:25:48 +0000596 // This hopefully will just get inlined and removed by the optimizer.
597 static const internal_key_type&
598 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000599
Douglas Gregora868bbd2009-04-21 22:25:48 +0000600 static std::pair<unsigned, unsigned>
601 ReadKeyDataLength(const unsigned char*& d) {
602 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000603 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000604 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000605 return std::make_pair(KeyLen, DataLen);
606 }
Mike Stump11289f42009-09-09 15:08:12 +0000607
Douglas Gregora868bbd2009-04-21 22:25:48 +0000608 static std::pair<const char*, unsigned>
609 ReadKey(const unsigned char* d, unsigned n) {
610 assert(n >= 2 && d[n-1] == '\0');
611 return std::make_pair((const char*) d, n-1);
612 }
Mike Stump11289f42009-09-09 15:08:12 +0000613
614 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000615 const unsigned char* d,
616 unsigned DataLen) {
617 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000618 pch::IdentID ID = ReadUnalignedLE32(d);
619 bool IsInteresting = ID & 0x01;
620
621 // Wipe out the "is interesting" bit.
622 ID = ID >> 1;
623
624 if (!IsInteresting) {
625 // For unintersting identifiers, just build the IdentifierInfo
626 // and associate it with the persistent ID.
627 IdentifierInfo *II = KnownII;
628 if (!II)
629 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
630 k.first, k.first + k.second);
631 Reader.SetIdentifierInfo(ID, II);
632 return II;
633 }
634
Douglas Gregorb9256522009-04-28 21:32:13 +0000635 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000636 bool CPlusPlusOperatorKeyword = Bits & 0x01;
637 Bits >>= 1;
638 bool Poisoned = Bits & 0x01;
639 Bits >>= 1;
640 bool ExtensionToken = Bits & 0x01;
641 Bits >>= 1;
642 bool hasMacroDefinition = Bits & 0x01;
643 Bits >>= 1;
644 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
645 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000646
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000647 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000648 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000649
650 // Build the IdentifierInfo itself and link the identifier ID with
651 // the new IdentifierInfo.
652 IdentifierInfo *II = KnownII;
653 if (!II)
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000654 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
655 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000656 Reader.SetIdentifierInfo(ID, II);
657
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000658 // Set or check the various bits in the IdentifierInfo structure.
659 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000660 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000661 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000662 "Incorrect extension token flag");
663 (void)ExtensionToken;
664 II->setIsPoisoned(Poisoned);
665 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
666 "Incorrect C++ operator keyword flag");
667 (void)CPlusPlusOperatorKeyword;
668
Douglas Gregorc3366a52009-04-21 23:56:24 +0000669 // If this identifier is a macro, deserialize the macro
670 // definition.
671 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000672 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregorc3366a52009-04-21 23:56:24 +0000673 Reader.ReadMacroRecord(Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000674 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000675 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000676
677 // Read all of the declarations visible at global scope with this
678 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000679 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000680 if (DataLen > 0) {
681 llvm::SmallVector<uint32_t, 4> DeclIDs;
682 for (; DataLen > 0; DataLen -= 4)
683 DeclIDs.push_back(ReadUnalignedLE32(d));
684 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000685 }
Mike Stump11289f42009-09-09 15:08:12 +0000686
Douglas Gregora868bbd2009-04-21 22:25:48 +0000687 return II;
688 }
689};
Mike Stump11289f42009-09-09 15:08:12 +0000690
691} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000692
693/// \brief The on-disk hash table used to contain information about
694/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000695typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000696 PCHIdentifierLookupTable;
697
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000698void PCHReader::Error(const char *Msg) {
699 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000700}
701
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000702/// \brief Check the contents of the concatenation of all predefines buffers in
703/// the PCH chain against the contents of the predefines buffer of the current
704/// compiler invocation.
Douglas Gregor92863e42009-04-10 23:10:45 +0000705///
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000706/// The contents should be the same. If not, then some command-line option
707/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregor92863e42009-04-10 23:10:45 +0000708///
709/// \returns true if there was a mismatch (in which case the PCH file
710/// should be ignored), or false otherwise.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000711bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000712 if (Listener)
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000713 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000714 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000715 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000716 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000717}
718
Douglas Gregorc5046832009-04-27 18:38:38 +0000719//===----------------------------------------------------------------------===//
720// Source Manager Deserialization
721//===----------------------------------------------------------------------===//
722
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000723/// \brief Read the line table in the source manager block.
724/// \returns true if ther was an error.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000725bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000726 unsigned Idx = 0;
727 LineTableInfo &LineTable = SourceMgr.getLineTable();
728
729 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000730 std::map<int, int> FileIDs;
731 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000732 // Extract the file name
733 unsigned FilenameLen = Record[Idx++];
734 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
735 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000736 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000737 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000738 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000739 }
740
741 // Parse the line entries
742 std::vector<LineEntry> Entries;
743 while (Idx < Record.size()) {
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000744 int FID = Record[Idx++];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000745
746 // Extract the line entries
747 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000748 assert(NumEntries && "Numentries is 00000");
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000749 Entries.clear();
750 Entries.reserve(NumEntries);
751 for (unsigned I = 0; I != NumEntries; ++I) {
752 unsigned FileOffset = Record[Idx++];
753 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000754 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump11289f42009-09-09 15:08:12 +0000755 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000756 = (SrcMgr::CharacteristicKind)Record[Idx++];
757 unsigned IncludeOffset = Record[Idx++];
758 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
759 FileKind, IncludeOffset));
760 }
761 LineTable.AddEntry(FID, Entries);
762 }
763
764 return false;
765}
766
Douglas Gregorc5046832009-04-27 18:38:38 +0000767namespace {
768
Benjamin Kramer16634c22009-11-28 10:07:24 +0000769class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000770public:
771 const bool hasStat;
772 const ino_t ino;
773 const dev_t dev;
774 const mode_t mode;
775 const time_t mtime;
776 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000777
Douglas Gregorc5046832009-04-27 18:38:38 +0000778 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000779 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
780
Douglas Gregorc5046832009-04-27 18:38:38 +0000781 PCHStatData()
782 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
783};
784
Benjamin Kramer16634c22009-11-28 10:07:24 +0000785class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000786 public:
787 typedef const char *external_key_type;
788 typedef const char *internal_key_type;
789
790 typedef PCHStatData data_type;
791
792 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000793 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000794 }
795
796 static internal_key_type GetInternalKey(const char *path) { return path; }
797
798 static bool EqualKey(internal_key_type a, internal_key_type b) {
799 return strcmp(a, b) == 0;
800 }
801
802 static std::pair<unsigned, unsigned>
803 ReadKeyDataLength(const unsigned char*& d) {
804 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
805 unsigned DataLen = (unsigned) *d++;
806 return std::make_pair(KeyLen + 1, DataLen);
807 }
808
809 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
810 return (const char *)d;
811 }
812
813 static data_type ReadData(const internal_key_type, const unsigned char *d,
814 unsigned /*DataLen*/) {
815 using namespace clang::io;
816
817 if (*d++ == 1)
818 return data_type();
819
820 ino_t ino = (ino_t) ReadUnalignedLE32(d);
821 dev_t dev = (dev_t) ReadUnalignedLE32(d);
822 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000823 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000824 off_t size = (off_t) ReadUnalignedLE64(d);
825 return data_type(ino, dev, mode, mtime, size);
826 }
827};
828
829/// \brief stat() cache for precompiled headers.
830///
831/// This cache is very similar to the stat cache used by pretokenized
832/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000833class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000834 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
835 CacheTy *Cache;
836
837 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000838public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000839 PCHStatCache(const unsigned char *Buckets,
840 const unsigned char *Base,
841 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000842 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000843 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
844 Cache = CacheTy::Create(Buckets, Base);
845 }
846
847 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000848
Douglas Gregorc5046832009-04-27 18:38:38 +0000849 int stat(const char *path, struct stat *buf) {
850 // Do the lookup for the file's data in the PCH file.
851 CacheTy::iterator I = Cache->find(path);
852
853 // If we don't get a hit in the PCH file just forward to 'stat'.
854 if (I == Cache->end()) {
855 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000856 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000857 }
Mike Stump11289f42009-09-09 15:08:12 +0000858
Douglas Gregorc5046832009-04-27 18:38:38 +0000859 ++NumStatHits;
860 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000861
Douglas Gregorc5046832009-04-27 18:38:38 +0000862 if (!Data.hasStat)
863 return 1;
864
865 buf->st_ino = Data.ino;
866 buf->st_dev = Data.dev;
867 buf->st_mtime = Data.mtime;
868 buf->st_mode = Data.mode;
869 buf->st_size = Data.size;
870 return 0;
871 }
872};
873} // end anonymous namespace
874
875
Douglas Gregora7f71a92009-04-10 03:52:48 +0000876/// \brief Read the source manager block
Douglas Gregor92863e42009-04-10 23:10:45 +0000877PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000878 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000879
880 // Set the source-location entry cursor to the current position in
881 // the stream. This cursor will be used to read the contents of the
882 // source manager block initially, and then lazily read
883 // source-location entries as needed.
884 SLocEntryCursor = Stream;
885
886 // The stream itself is going to skip over the source manager block.
887 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000888 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000889 return Failure;
890 }
891
892 // Enter the source manager block.
893 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000894 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000895 return Failure;
896 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000897
Douglas Gregora7f71a92009-04-10 03:52:48 +0000898 RecordData Record;
899 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000900 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000901 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000902 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000903 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000904 return Failure;
905 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000906 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000907 }
Mike Stump11289f42009-09-09 15:08:12 +0000908
Douglas Gregora7f71a92009-04-10 03:52:48 +0000909 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
910 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000911 SLocEntryCursor.ReadSubBlockID();
912 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000913 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000914 return Failure;
915 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000916 continue;
917 }
Mike Stump11289f42009-09-09 15:08:12 +0000918
Douglas Gregora7f71a92009-04-10 03:52:48 +0000919 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000920 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000921 continue;
922 }
Mike Stump11289f42009-09-09 15:08:12 +0000923
Douglas Gregora7f71a92009-04-10 03:52:48 +0000924 // Read a record.
925 const char *BlobStart;
926 unsigned BlobLen;
927 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000928 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000929 default: // Default behavior: ignore.
930 break;
931
Chris Lattner184e65d2009-04-14 23:22:57 +0000932 case pch::SM_LINE_TABLE:
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000933 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000934 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000935 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000936
Douglas Gregor258ae542009-04-27 06:38:32 +0000937 case pch::SM_SLOC_FILE_ENTRY:
938 case pch::SM_SLOC_BUFFER_ENTRY:
939 case pch::SM_SLOC_INSTANTIATION_ENTRY:
940 // Once we hit one of the source location entries, we're done.
941 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000942 }
943 }
944}
945
Douglas Gregor258ae542009-04-27 06:38:32 +0000946/// \brief Read in the source location entry with the given ID.
947PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
948 if (ID == 0)
949 return Success;
950
951 if (ID > TotalNumSLocEntries) {
952 Error("source location entry ID out-of-range for PCH file");
953 return Failure;
954 }
955
956 ++NumSLocEntriesRead;
957 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
958 unsigned Code = SLocEntryCursor.ReadCode();
959 if (Code == llvm::bitc::END_BLOCK ||
960 Code == llvm::bitc::ENTER_SUBBLOCK ||
961 Code == llvm::bitc::DEFINE_ABBREV) {
962 Error("incorrectly-formatted source location entry in PCH file");
963 return Failure;
964 }
965
Douglas Gregor258ae542009-04-27 06:38:32 +0000966 RecordData Record;
967 const char *BlobStart;
968 unsigned BlobLen;
969 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
970 default:
971 Error("incorrectly-formatted source location entry in PCH file");
972 return Failure;
973
974 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000975 std::string Filename(BlobStart, BlobStart + BlobLen);
976 MaybeAddSystemRootToFilename(Filename);
977 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000978 if (File == 0) {
979 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000980 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000981 ErrorStr += "' referenced by PCH file";
982 Error(ErrorStr.c_str());
983 return Failure;
984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
Douglas Gregorb41ca8f2010-03-21 22:49:54 +0000986 if (Record.size() < 10) {
Ted Kremenekabb1ddd2010-03-18 21:23:05 +0000987 Error("source location entry is incorrect");
988 return Failure;
989 }
990
Douglas Gregor08288f22010-04-09 15:54:22 +0000991 if ((off_t)Record[4] != File->getSize()
992#if !defined(LLVM_ON_WIN32)
993 // In our regression testing, the Windows file system seems to
994 // have inconsistent modification times that sometimes
995 // erroneously trigger this error-handling path.
996 || (time_t)Record[5] != File->getModificationTime()
997#endif
998 ) {
Douglas Gregorb41ca8f2010-03-21 22:49:54 +0000999 Diag(diag::err_fe_pch_file_modified)
1000 << Filename;
1001 return Failure;
1002 }
1003
Douglas Gregor258ae542009-04-27 06:38:32 +00001004 FileID FID = SourceMgr.createFileID(File,
1005 SourceLocation::getFromRawEncoding(Record[1]),
1006 (SrcMgr::CharacteristicKind)Record[2],
1007 ID, Record[0]);
1008 if (Record[3])
1009 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1010 .setHasLineDirectives();
1011
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001012 // Reconstruct header-search information for this file.
1013 HeaderFileInfo HFI;
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001014 HFI.isImport = Record[6];
1015 HFI.DirInfo = Record[7];
1016 HFI.NumIncludes = Record[8];
1017 HFI.ControllingMacroID = Record[9];
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001018 if (Listener)
1019 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor258ae542009-04-27 06:38:32 +00001020 break;
1021 }
1022
1023 case pch::SM_SLOC_BUFFER_ENTRY: {
1024 const char *Name = BlobStart;
1025 unsigned Offset = Record[0];
1026 unsigned Code = SLocEntryCursor.ReadCode();
1027 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001028 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +00001029 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001030
1031 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1032 Error("PCH record has invalid code");
1033 return Failure;
1034 }
1035
Douglas Gregor258ae542009-04-27 06:38:32 +00001036 llvm::MemoryBuffer *Buffer
Chris Lattner58c79342010-04-05 22:42:27 +00001037 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1038 Name);
Douglas Gregor258ae542009-04-27 06:38:32 +00001039 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +00001040
Douglas Gregore6648fb2009-04-28 20:33:11 +00001041 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl75fbb3b2010-07-14 17:49:11 +00001042 PCHPredefinesBlock Block = {
1043 BufferID,
1044 llvm::StringRef(BlobStart, BlobLen - 1)
1045 };
1046 PCHPredefinesBuffers.push_back(Block);
Douglas Gregore6648fb2009-04-28 20:33:11 +00001047 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001048
1049 break;
1050 }
1051
1052 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +00001053 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +00001054 = SourceLocation::getFromRawEncoding(Record[1]);
1055 SourceMgr.createInstantiationLoc(SpellingLoc,
1056 SourceLocation::getFromRawEncoding(Record[2]),
1057 SourceLocation::getFromRawEncoding(Record[3]),
1058 Record[4],
1059 ID,
1060 Record[0]);
1061 break;
Mike Stump11289f42009-09-09 15:08:12 +00001062 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001063 }
1064
1065 return Success;
1066}
1067
Chris Lattnere78a6be2009-04-27 01:05:14 +00001068/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1069/// specified cursor. Read the abbreviations that are at the top of the block
1070/// and then leave the cursor pointing into the block.
1071bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1072 unsigned BlockID) {
1073 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001074 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001075 return Failure;
1076 }
Mike Stump11289f42009-09-09 15:08:12 +00001077
Chris Lattnere78a6be2009-04-27 01:05:14 +00001078 while (true) {
1079 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattnere78a6be2009-04-27 01:05:14 +00001081 // We expect all abbrevs to be at the start of the block.
1082 if (Code != llvm::bitc::DEFINE_ABBREV)
1083 return false;
1084 Cursor.ReadAbbrevRecord();
1085 }
1086}
1087
Douglas Gregorc3366a52009-04-21 23:56:24 +00001088void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001089 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +00001090
Douglas Gregorc3366a52009-04-21 23:56:24 +00001091 // Keep track of where we are in the stream, then jump back there
1092 // after reading this macro.
1093 SavedStreamPosition SavedPosition(Stream);
1094
1095 Stream.JumpToBit(Offset);
1096 RecordData Record;
1097 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1098 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001099
Douglas Gregorc3366a52009-04-21 23:56:24 +00001100 while (true) {
1101 unsigned Code = Stream.ReadCode();
1102 switch (Code) {
1103 case llvm::bitc::END_BLOCK:
1104 return;
1105
1106 case llvm::bitc::ENTER_SUBBLOCK:
1107 // No known subblocks, always skip them.
1108 Stream.ReadSubBlockID();
1109 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001110 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001111 return;
1112 }
1113 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001114
Douglas Gregorc3366a52009-04-21 23:56:24 +00001115 case llvm::bitc::DEFINE_ABBREV:
1116 Stream.ReadAbbrevRecord();
1117 continue;
1118 default: break;
1119 }
1120
1121 // Read a record.
1122 Record.clear();
1123 pch::PreprocessorRecordTypes RecType =
1124 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1125 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001126 case pch::PP_MACRO_OBJECT_LIKE:
1127 case pch::PP_MACRO_FUNCTION_LIKE: {
1128 // If we already have a macro, that means that we've hit the end
1129 // of the definition of the macro we were looking for. We're
1130 // done.
1131 if (Macro)
1132 return;
1133
1134 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1135 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001136 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001137 return;
1138 }
1139 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1140 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001141
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001142 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001143 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001144
Douglas Gregoraae92242010-03-19 21:51:54 +00001145 unsigned NextIndex = 3;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001146 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1147 // Decode function-like macro info.
1148 bool isC99VarArgs = Record[3];
1149 bool isGNUVarArgs = Record[4];
1150 MacroArgs.clear();
1151 unsigned NumArgs = Record[5];
Douglas Gregoraae92242010-03-19 21:51:54 +00001152 NextIndex = 6 + NumArgs;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001153 for (unsigned i = 0; i != NumArgs; ++i)
1154 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1155
1156 // Install function-like macro info.
1157 MI->setIsFunctionLike();
1158 if (isC99VarArgs) MI->setIsC99Varargs();
1159 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001160 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001161 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001162 }
1163
1164 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001165 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001166
1167 // Remember that we saw this macro last so that we add the tokens that
1168 // form its body to it.
1169 Macro = MI;
Douglas Gregoraae92242010-03-19 21:51:54 +00001170
1171 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1172 // We have a macro definition. Load it now.
1173 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1174 getMacroDefinition(Record[NextIndex]));
1175 }
1176
Douglas Gregorc3366a52009-04-21 23:56:24 +00001177 ++NumMacrosRead;
1178 break;
1179 }
Mike Stump11289f42009-09-09 15:08:12 +00001180
Douglas Gregorc3366a52009-04-21 23:56:24 +00001181 case pch::PP_TOKEN: {
1182 // If we see a TOKEN before a PP_MACRO_*, then the file is
1183 // erroneous, just pretend we didn't see this.
1184 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001185
Douglas Gregorc3366a52009-04-21 23:56:24 +00001186 Token Tok;
1187 Tok.startToken();
1188 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1189 Tok.setLength(Record[1]);
1190 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1191 Tok.setIdentifierInfo(II);
1192 Tok.setKind((tok::TokenKind)Record[3]);
1193 Tok.setFlag((Token::TokenFlags)Record[4]);
1194 Macro->AddTokenToBody(Tok);
1195 break;
1196 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001197
1198 case pch::PP_MACRO_INSTANTIATION: {
1199 // If we already have a macro, that means that we've hit the end
1200 // of the definition of the macro we were looking for. We're
1201 // done.
1202 if (Macro)
1203 return;
1204
1205 if (!PP->getPreprocessingRecord()) {
1206 Error("missing preprocessing record in PCH file");
1207 return;
1208 }
1209
1210 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1211 if (PPRec.getPreprocessedEntity(Record[0]))
1212 return;
1213
1214 MacroInstantiation *MI
1215 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1216 SourceRange(
1217 SourceLocation::getFromRawEncoding(Record[1]),
1218 SourceLocation::getFromRawEncoding(Record[2])),
1219 getMacroDefinition(Record[4]));
1220 PPRec.SetPreallocatedEntity(Record[0], MI);
1221 return;
1222 }
1223
1224 case pch::PP_MACRO_DEFINITION: {
1225 // If we already have a macro, that means that we've hit the end
1226 // of the definition of the macro we were looking for. We're
1227 // done.
1228 if (Macro)
1229 return;
1230
1231 if (!PP->getPreprocessingRecord()) {
1232 Error("missing preprocessing record in PCH file");
1233 return;
1234 }
1235
1236 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1237 if (PPRec.getPreprocessedEntity(Record[0]))
1238 return;
1239
1240 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1241 Error("out-of-bounds macro definition record");
1242 return;
1243 }
1244
1245 MacroDefinition *MD
1246 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1247 SourceLocation::getFromRawEncoding(Record[5]),
1248 SourceRange(
1249 SourceLocation::getFromRawEncoding(Record[2]),
1250 SourceLocation::getFromRawEncoding(Record[3])));
1251 PPRec.SetPreallocatedEntity(Record[0], MD);
1252 MacroDefinitionsLoaded[Record[1]] = MD;
1253 return;
1254 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001255 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001256 }
1257}
1258
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001259void PCHReader::ReadDefinedMacros() {
1260 // If there was no preprocessor block, do nothing.
1261 if (!MacroCursor.getBitStreamReader())
1262 return;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001263
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001264 llvm::BitstreamCursor Cursor = MacroCursor;
1265 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1266 Error("malformed preprocessor block record in PCH file");
1267 return;
1268 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001269
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001270 RecordData Record;
1271 while (true) {
1272 unsigned Code = Cursor.ReadCode();
1273 if (Code == llvm::bitc::END_BLOCK) {
1274 if (Cursor.ReadBlockEnd())
1275 Error("error at end of preprocessor block in PCH file");
1276 return;
1277 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001278
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001279 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1280 // No known subblocks, always skip them.
1281 Cursor.ReadSubBlockID();
1282 if (Cursor.SkipBlock()) {
1283 Error("malformed block record in PCH file");
1284 return;
1285 }
1286 continue;
1287 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001288
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001289 if (Code == llvm::bitc::DEFINE_ABBREV) {
1290 Cursor.ReadAbbrevRecord();
1291 continue;
1292 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001293
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001294 // Read a record.
1295 const char *BlobStart;
1296 unsigned BlobLen;
1297 Record.clear();
1298 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1299 default: // Default behavior: ignore.
1300 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001301
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001302 case pch::PP_MACRO_OBJECT_LIKE:
1303 case pch::PP_MACRO_FUNCTION_LIKE:
Douglas Gregoraae92242010-03-19 21:51:54 +00001304 DecodeIdentifierInfo(Record[0]);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001305 break;
1306
1307 case pch::PP_TOKEN:
1308 // Ignore tokens.
1309 break;
Douglas Gregoraae92242010-03-19 21:51:54 +00001310
1311 case pch::PP_MACRO_INSTANTIATION:
1312 case pch::PP_MACRO_DEFINITION:
1313 // Read the macro record.
1314 ReadMacroRecord(Cursor.GetCurrentBitNo());
1315 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001316 }
1317 }
1318}
1319
Douglas Gregoraae92242010-03-19 21:51:54 +00001320MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1321 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1322 return 0;
1323
1324 if (!MacroDefinitionsLoaded[ID])
1325 ReadMacroRecord(MacroDefinitionOffsets[ID]);
1326
1327 return MacroDefinitionsLoaded[ID];
1328}
1329
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001330/// \brief If we are loading a relocatable PCH file, and the filename is
1331/// not an absolute path, add the system root to the beginning of the file
1332/// name.
1333void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1334 // If this is not a relocatable PCH file, there's nothing to do.
1335 if (!RelocatablePCH)
1336 return;
Mike Stump11289f42009-09-09 15:08:12 +00001337
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001338 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001339 return;
1340
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001341 if (isysroot == 0) {
1342 // If no system root was given, default to '/'
1343 Filename.insert(Filename.begin(), '/');
1344 return;
1345 }
Mike Stump11289f42009-09-09 15:08:12 +00001346
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001347 unsigned Length = strlen(isysroot);
1348 if (isysroot[Length - 1] != '/')
1349 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001350
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001351 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1352}
1353
Mike Stump11289f42009-09-09 15:08:12 +00001354PCHReader::PCHReadResult
Douglas Gregoreda6a892009-04-26 00:07:37 +00001355PCHReader::ReadPCHBlock() {
Douglas Gregor55abb232009-04-10 20:39:37 +00001356 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001357 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001358 return Failure;
1359 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001360
1361 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001362 RecordData Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001363 while (!Stream.AtEndOfStream()) {
1364 unsigned Code = Stream.ReadCode();
1365 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001366 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001367 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001368 return Failure;
1369 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001370
Douglas Gregor55abb232009-04-10 20:39:37 +00001371 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001372 }
1373
1374 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1375 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001376 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001377 // We lazily load the decls block, but we want to set up the
1378 // DeclsCursor cursor to point into it. Clone our current bitcode
1379 // cursor to it, enter the block and read the abbrevs in that block.
1380 // With the main cursor, we just skip over it.
1381 DeclsCursor = Stream;
1382 if (Stream.SkipBlock() || // Skip with the main cursor.
1383 // Read the abbrevs.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001384 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001385 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001386 return Failure;
1387 }
1388 break;
Mike Stump11289f42009-09-09 15:08:12 +00001389
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001390 case pch::PREPROCESSOR_BLOCK_ID:
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001391 MacroCursor = Stream;
1392 if (PP)
1393 PP->setExternalSource(this);
1394
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001395 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001396 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001397 return Failure;
1398 }
1399 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001400
Douglas Gregora7f71a92009-04-10 03:52:48 +00001401 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001402 switch (ReadSourceManagerBlock()) {
1403 case Success:
1404 break;
1405
1406 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001407 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001408 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001409
1410 case IgnorePCH:
1411 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001412 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001413 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001414 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001415 continue;
1416 }
1417
1418 if (Code == llvm::bitc::DEFINE_ABBREV) {
1419 Stream.ReadAbbrevRecord();
1420 continue;
1421 }
1422
1423 // Read and process a record.
1424 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001425 const char *BlobStart = 0;
1426 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001427 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001428 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001429 default: // Default behavior: ignore.
1430 break;
1431
1432 case pch::TYPE_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001433 if (!TypesLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001434 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001435 return Failure;
1436 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001437 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001438 TypesLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001439 break;
1440
1441 case pch::DECL_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001442 if (!DeclsLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001443 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001444 return Failure;
1445 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001446 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001447 DeclsLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001448 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001449
1450 case pch::LANGUAGE_OPTIONS:
1451 if (ParseLanguageOptions(Record))
1452 return IgnorePCH;
1453 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001454
Douglas Gregor7b71e632009-04-27 22:23:34 +00001455 case pch::METADATA: {
1456 if (Record[0] != pch::VERSION_MAJOR) {
1457 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1458 : diag::warn_pch_version_too_new);
1459 return IgnorePCH;
1460 }
1461
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001462 RelocatablePCH = Record[4];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001463 if (Listener) {
1464 std::string TargetTriple(BlobStart, BlobLen);
1465 if (Listener->ReadTargetTriple(TargetTriple))
1466 return IgnorePCH;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001467 }
1468 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001469 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001470
1471 case pch::IDENTIFIER_TABLE:
Douglas Gregora868bbd2009-04-21 22:25:48 +00001472 IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001473 if (Record[0]) {
Mike Stump11289f42009-09-09 15:08:12 +00001474 IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001475 = PCHIdentifierLookupTable::Create(
Douglas Gregora868bbd2009-04-21 22:25:48 +00001476 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001477 (const unsigned char *)IdentifierTableData,
Douglas Gregora868bbd2009-04-21 22:25:48 +00001478 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001479 if (PP)
1480 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001481 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001482 break;
1483
1484 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001485 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001486 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001487 return Failure;
1488 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001489 IdentifierOffsets = (const uint32_t *)BlobStart;
1490 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001491 if (PP)
1492 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001493 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001494
1495 case pch::EXTERNAL_DEFINITIONS:
1496 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001497 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001498 return Failure;
1499 }
1500 ExternalDefinitions.swap(Record);
1501 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001502
Douglas Gregor652d82a2009-04-18 05:55:16 +00001503 case pch::SPECIAL_TYPES:
1504 SpecialTypes.swap(Record);
1505 break;
1506
Douglas Gregor08f01292009-04-17 22:13:46 +00001507 case pch::STATISTICS:
1508 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001509 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001510 TotalLexicalDeclContexts = Record[2];
1511 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001512 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001513
Douglas Gregord4df8652009-04-22 22:02:47 +00001514 case pch::TENTATIVE_DEFINITIONS:
1515 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001516 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001517 return Failure;
1518 }
1519 TentativeDefinitions.swap(Record);
1520 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001521
Tanya Lattner90073802010-02-12 00:07:30 +00001522 case pch::UNUSED_STATIC_FUNCS:
1523 if (!UnusedStaticFuncs.empty()) {
1524 Error("duplicate UNUSED_STATIC_FUNCS record in PCH file");
1525 return Failure;
1526 }
1527 UnusedStaticFuncs.swap(Record);
1528 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001529
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001530 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1531 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001532 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001533 return Failure;
1534 }
1535 LocallyScopedExternalDecls.swap(Record);
1536 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001537
Douglas Gregor95c13f52009-04-25 17:48:32 +00001538 case pch::SELECTOR_OFFSETS:
1539 SelectorOffsets = (const uint32_t *)BlobStart;
1540 TotalNumSelectors = Record[0];
1541 SelectorsLoaded.resize(TotalNumSelectors);
1542 break;
1543
Douglas Gregorc78d3462009-04-24 21:10:55 +00001544 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001545 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1546 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001547 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001548 = PCHMethodPoolLookupTable::Create(
1549 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001550 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001551 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001552 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001553 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001554
1555 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001556 if (!Record.empty() && Listener)
1557 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001558 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001559
1560 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001561 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001562 TotalNumSLocEntries = Record[0];
Douglas Gregord54f3a12009-10-05 21:07:28 +00001563 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001564 break;
1565
1566 case pch::SOURCE_LOCATION_PRELOADS:
1567 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1568 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1569 if (Result != Success)
1570 return Result;
1571 }
1572 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001573
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001574 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001575 PCHStatCache *MyStatCache =
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001576 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1577 (const unsigned char *)BlobStart,
1578 NumStatHits, NumStatMisses);
1579 FileMgr.addStatCache(MyStatCache);
1580 StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001581 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001582 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001583
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001584 case pch::EXT_VECTOR_DECLS:
1585 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001586 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001587 return Failure;
1588 }
1589 ExtVectorDecls.swap(Record);
1590 break;
1591
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00001592 case pch::VTABLE_USES:
1593 if (!VTableUses.empty()) {
1594 Error("duplicate VTABLE_USES record in PCH file");
1595 return Failure;
1596 }
1597 VTableUses.swap(Record);
1598 break;
1599
1600 case pch::DYNAMIC_CLASSES:
1601 if (!DynamicClasses.empty()) {
1602 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1603 return Failure;
1604 }
1605 DynamicClasses.swap(Record);
1606 break;
1607
Douglas Gregor45fe0362009-05-12 01:31:05 +00001608 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001609 ActualOriginalFileName.assign(BlobStart, BlobLen);
1610 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001611 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001612 break;
Mike Stump11289f42009-09-09 15:08:12 +00001613
Ted Kremenek17437132010-01-22 20:59:36 +00001614 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek8bd09292010-02-12 23:31:14 +00001615 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek2377a0e2010-01-22 20:55:35 +00001616 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Ted Kremenek8bd09292010-02-12 23:31:14 +00001617 if (llvm::StringRef(CurBranch) != PCHBranch) {
Douglas Gregord54f3a12009-10-05 21:07:28 +00001618 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1619 return IgnorePCH;
1620 }
1621 break;
1622 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001623
1624 case pch::MACRO_DEFINITION_OFFSETS:
1625 MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1626 if (PP) {
1627 if (!PP->getPreprocessingRecord())
1628 PP->createPreprocessingRecord();
1629 PP->getPreprocessingRecord()->SetExternalSource(*this, Record[0]);
1630 } else {
1631 NumPreallocatedPreprocessingEntities = Record[0];
1632 }
1633
1634 MacroDefinitionsLoaded.resize(Record[1]);
1635 break;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001636 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001637 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001638 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001639 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001640}
1641
Douglas Gregor92863e42009-04-10 23:10:45 +00001642PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001643 // Set the PCH file name.
1644 this->FileName = FileName;
1645
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001646 // Open the PCH file.
Daniel Dunbar2d925eb2009-09-22 05:38:01 +00001647 //
1648 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001649 std::string ErrStr;
Daniel Dunbar69914f42009-11-10 00:46:19 +00001650 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregor92863e42009-04-10 23:10:45 +00001651 if (!Buffer) {
1652 Error(ErrStr.c_str());
1653 return IgnorePCH;
1654 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001655
1656 // Initialize the stream
Mike Stump11289f42009-09-09 15:08:12 +00001657 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattner9356ace2009-04-26 20:59:20 +00001658 (const unsigned char *)Buffer->getBufferEnd());
1659 Stream.init(StreamFile);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001660
1661 // Sniff for the signature.
1662 if (Stream.Read(8) != 'C' ||
1663 Stream.Read(8) != 'P' ||
1664 Stream.Read(8) != 'C' ||
Douglas Gregor92863e42009-04-10 23:10:45 +00001665 Stream.Read(8) != 'H') {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001666 Diag(diag::err_not_a_pch_file) << FileName;
1667 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001668 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001669
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001670 while (!Stream.AtEndOfStream()) {
1671 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001672
Douglas Gregor92863e42009-04-10 23:10:45 +00001673 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001674 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001675 return Failure;
1676 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001677
1678 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001679
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001680 // We only know the PCH subblock ID.
1681 switch (BlockID) {
1682 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001683 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001684 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001685 return Failure;
1686 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001687 break;
1688 case pch::PCH_BLOCK_ID:
Douglas Gregoreda6a892009-04-26 00:07:37 +00001689 switch (ReadPCHBlock()) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001690 case Success:
1691 break;
1692
1693 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001694 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001695
1696 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001697 // FIXME: We could consider reading through to the end of this
1698 // PCH block, skipping subblocks, to see if there are other
1699 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001700
1701 // Clear out any preallocated source location entries, so that
1702 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001703 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001704
1705 // Remove the stat cache.
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001706 if (StatCache)
1707 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001708
Douglas Gregor92863e42009-04-10 23:10:45 +00001709 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001710 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001711 break;
1712 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001713 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001714 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001715 return Failure;
1716 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001717 break;
1718 }
Mike Stump11289f42009-09-09 15:08:12 +00001719 }
1720
Douglas Gregore6648fb2009-04-28 20:33:11 +00001721 // Check the predefines buffer.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +00001722 if (CheckPredefinesBuffers())
Douglas Gregore6648fb2009-04-28 20:33:11 +00001723 return IgnorePCH;
Mike Stump11289f42009-09-09 15:08:12 +00001724
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001725 if (PP) {
Zhongxing Xu3f51f412009-07-18 09:26:51 +00001726 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001727 // PCH file is read, so there may be some identifiers that were
1728 // loaded into the IdentifierTable before we intercepted the
1729 // creation of identifiers. Iterate through the list of known
1730 // identifiers and determine whether we have to establish
1731 // preprocessor definitions or top-level identifier declaration
1732 // chains for those identifiers.
1733 //
1734 // We copy the IdentifierInfo pointers to a small vector first,
1735 // since de-serializing declarations or macro definitions can add
1736 // new entries into the identifier table, invalidating the
1737 // iterators.
1738 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1739 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1740 IdEnd = PP->getIdentifierTable().end();
1741 Id != IdEnd; ++Id)
1742 Identifiers.push_back(Id->second);
Mike Stump11289f42009-09-09 15:08:12 +00001743 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001744 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1745 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1746 IdentifierInfo *II = Identifiers[I];
1747 // Look in the on-disk hash table for an entry for
1748 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001749 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001750 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1751 if (Pos == IdTable->end())
1752 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001753
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001754 // Dereferencing the iterator has the effect of populating the
1755 // IdentifierInfo node with the various declarations it needs.
1756 (void)*Pos;
1757 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001758 }
1759
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001760 if (Context)
1761 InitializeContext(*Context);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001762
Douglas Gregora868bbd2009-04-21 22:25:48 +00001763 return Success;
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001764}
1765
Douglas Gregoraae92242010-03-19 21:51:54 +00001766void PCHReader::setPreprocessor(Preprocessor &pp) {
1767 PP = &pp;
1768
1769 if (NumPreallocatedPreprocessingEntities) {
1770 if (!PP->getPreprocessingRecord())
1771 PP->createPreprocessingRecord();
1772 PP->getPreprocessingRecord()->SetExternalSource(*this,
1773 NumPreallocatedPreprocessingEntities);
1774 NumPreallocatedPreprocessingEntities = 0;
1775 }
1776}
1777
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001778void PCHReader::InitializeContext(ASTContext &Ctx) {
1779 Context = &Ctx;
1780 assert(Context && "Passed null context!");
1781
1782 assert(PP && "Forgot to set Preprocessor ?");
1783 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1784 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001785 PP->setExternalSource(this);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001786
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001787 // Load the translation unit declaration
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00001788 GetTranslationUnitDecl();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001789
1790 // Load the special types.
1791 Context->setBuiltinVaListType(
1792 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1793 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1794 Context->setObjCIdType(GetType(Id));
1795 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1796 Context->setObjCSelType(GetType(Sel));
1797 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1798 Context->setObjCProtoType(GetType(Proto));
1799 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1800 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001801
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001802 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1803 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001804 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001805 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1806 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001807 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1808 QualType FileType = GetType(File);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001809 if (FileType.isNull()) {
1810 Error("FILE type is NULL");
1811 return;
1812 }
John McCall9dd450b2009-09-21 23:43:11 +00001813 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001814 Context->setFILEDecl(Typedef->getDecl());
1815 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001816 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001817 if (!Tag) {
1818 Error("Invalid FILE type in PCH file");
1819 return;
1820 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00001821 Context->setFILEDecl(Tag->getDecl());
1822 }
1823 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001824 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1825 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001826 if (Jmp_bufType.isNull()) {
1827 Error("jmp_bug type is NULL");
1828 return;
1829 }
John McCall9dd450b2009-09-21 23:43:11 +00001830 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001831 Context->setjmp_bufDecl(Typedef->getDecl());
1832 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001833 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001834 if (!Tag) {
1835 Error("Invalid jmp_bug type in PCH file");
1836 return;
1837 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001838 Context->setjmp_bufDecl(Tag->getDecl());
1839 }
1840 }
1841 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1842 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001843 if (Sigjmp_bufType.isNull()) {
1844 Error("sigjmp_buf type is NULL");
1845 return;
1846 }
John McCall9dd450b2009-09-21 23:43:11 +00001847 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001848 Context->setsigjmp_bufDecl(Typedef->getDecl());
1849 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001850 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001851 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1852 Context->setsigjmp_bufDecl(Tag->getDecl());
1853 }
1854 }
Mike Stump11289f42009-09-09 15:08:12 +00001855 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001856 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1857 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001858 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001859 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1860 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpd0153282009-10-20 02:12:22 +00001861 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1862 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00001863 if (unsigned String
1864 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1865 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001866 if (unsigned ObjCSelRedef
1867 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
1868 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
1869 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
1870 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +00001871
1872 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
1873 Context->setInt128Installed();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001874}
1875
Douglas Gregor45fe0362009-05-12 01:31:05 +00001876/// \brief Retrieve the name of the original source file name
1877/// directly from the PCH file, without actually loading the PCH
1878/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00001879std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1880 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00001881 // Open the PCH file.
1882 std::string ErrStr;
1883 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1884 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1885 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001886 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001887 return std::string();
1888 }
1889
1890 // Initialize the stream
1891 llvm::BitstreamReader StreamFile;
1892 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001893 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001894 (const unsigned char *)Buffer->getBufferEnd());
1895 Stream.init(StreamFile);
1896
1897 // Sniff for the signature.
1898 if (Stream.Read(8) != 'C' ||
1899 Stream.Read(8) != 'P' ||
1900 Stream.Read(8) != 'C' ||
1901 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001902 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001903 return std::string();
1904 }
1905
1906 RecordData Record;
1907 while (!Stream.AtEndOfStream()) {
1908 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001909
Douglas Gregor45fe0362009-05-12 01:31:05 +00001910 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1911 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001912
Douglas Gregor45fe0362009-05-12 01:31:05 +00001913 // We only know the PCH subblock ID.
1914 switch (BlockID) {
1915 case pch::PCH_BLOCK_ID:
1916 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001917 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001918 return std::string();
1919 }
1920 break;
Mike Stump11289f42009-09-09 15:08:12 +00001921
Douglas Gregor45fe0362009-05-12 01:31:05 +00001922 default:
1923 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001924 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001925 return std::string();
1926 }
1927 break;
1928 }
1929 continue;
1930 }
1931
1932 if (Code == llvm::bitc::END_BLOCK) {
1933 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001934 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001935 return std::string();
1936 }
1937 continue;
1938 }
1939
1940 if (Code == llvm::bitc::DEFINE_ABBREV) {
1941 Stream.ReadAbbrevRecord();
1942 continue;
1943 }
1944
1945 Record.clear();
1946 const char *BlobStart = 0;
1947 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001948 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00001949 == pch::ORIGINAL_FILE_NAME)
1950 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00001951 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00001952
1953 return std::string();
1954}
1955
Douglas Gregor55abb232009-04-10 20:39:37 +00001956/// \brief Parse the record that corresponds to a LangOptions data
1957/// structure.
1958///
1959/// This routine compares the language options used to generate the
1960/// PCH file against the language options set for the current
1961/// compilation. For each option, we classify differences between the
1962/// two compiler states as either "benign" or "important". Benign
1963/// differences don't matter, and we accept them without complaint
1964/// (and without modifying the language options). Differences between
1965/// the states for important options cause the PCH file to be
1966/// unusable, so we emit a warning and return true to indicate that
1967/// there was an error.
1968///
1969/// \returns true if the PCH file is unacceptable, false otherwise.
1970bool PCHReader::ParseLanguageOptions(
1971 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001972 if (Listener) {
1973 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00001974
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001975 #define PARSE_LANGOPT(Option) \
1976 LangOpts.Option = Record[Idx]; \
1977 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00001978
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001979 unsigned Idx = 0;
1980 PARSE_LANGOPT(Trigraphs);
1981 PARSE_LANGOPT(BCPLComment);
1982 PARSE_LANGOPT(DollarIdents);
1983 PARSE_LANGOPT(AsmPreprocessor);
1984 PARSE_LANGOPT(GNUMode);
Chandler Carruthe03aa552010-04-17 20:17:31 +00001985 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001986 PARSE_LANGOPT(ImplicitInt);
1987 PARSE_LANGOPT(Digraphs);
1988 PARSE_LANGOPT(HexFloats);
1989 PARSE_LANGOPT(C99);
1990 PARSE_LANGOPT(Microsoft);
1991 PARSE_LANGOPT(CPlusPlus);
1992 PARSE_LANGOPT(CPlusPlus0x);
1993 PARSE_LANGOPT(CXXOperatorNames);
1994 PARSE_LANGOPT(ObjC1);
1995 PARSE_LANGOPT(ObjC2);
1996 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00001997 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian62c56022010-04-22 21:01:59 +00001998 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001999 PARSE_LANGOPT(PascalStrings);
2000 PARSE_LANGOPT(WritableStrings);
2001 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00002002 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002003 PARSE_LANGOPT(Exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +00002004 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002005 PARSE_LANGOPT(NeXTRuntime);
2006 PARSE_LANGOPT(Freestanding);
2007 PARSE_LANGOPT(NoBuiltin);
2008 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00002009 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002010 PARSE_LANGOPT(Blocks);
2011 PARSE_LANGOPT(EmitAllDecls);
2012 PARSE_LANGOPT(MathErrno);
Chris Lattner51924e512010-06-26 21:25:03 +00002013 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2014 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002015 PARSE_LANGOPT(HeinousExtensions);
2016 PARSE_LANGOPT(Optimize);
2017 PARSE_LANGOPT(OptimizeSize);
2018 PARSE_LANGOPT(Static);
2019 PARSE_LANGOPT(PICLevel);
2020 PARSE_LANGOPT(GNUInline);
2021 PARSE_LANGOPT(NoInline);
2022 PARSE_LANGOPT(AccessControl);
2023 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00002024 PARSE_LANGOPT(ShortWChar);
Chris Lattner51924e512010-06-26 21:25:03 +00002025 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2026 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbar143021e2009-09-21 04:16:19 +00002027 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattner51924e512010-06-26 21:25:03 +00002028 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002029 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00002030 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00002031 PARSE_LANGOPT(CatchUndefined);
2032 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002033 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00002034
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002035 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00002036 }
Douglas Gregor55abb232009-04-10 20:39:37 +00002037
2038 return false;
2039}
2040
Douglas Gregoraae92242010-03-19 21:51:54 +00002041void PCHReader::ReadPreprocessedEntities() {
2042 ReadDefinedMacros();
2043}
2044
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002045/// \brief Read and return the type at the given offset.
2046///
2047/// This routine actually reads the record corresponding to the type
2048/// at the given offset in the bitstream. It is a helper routine for
2049/// GetType, which deals with reading type IDs.
2050QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002051 // Keep track of where we are in the stream, then jump back there
2052 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00002053 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002054
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002055 ReadingKindTracker ReadingKind(Read_Type, *this);
2056
Douglas Gregor1342e842009-07-06 18:54:52 +00002057 // Note that we are loading a type record.
2058 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002059
Douglas Gregor12bfa382009-10-17 00:13:19 +00002060 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002061 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00002062 unsigned Code = DeclsCursor.ReadCode();
2063 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00002064 case pch::TYPE_EXT_QUAL: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002065 if (Record.size() != 2) {
2066 Error("Incorrect encoding of extended qualifier type");
2067 return QualType();
2068 }
Douglas Gregor455b8f42009-04-15 22:00:08 +00002069 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00002070 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2071 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00002072 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002073
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002074 case pch::TYPE_COMPLEX: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002075 if (Record.size() != 1) {
2076 Error("Incorrect encoding of complex type");
2077 return QualType();
2078 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002079 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002080 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002081 }
2082
2083 case pch::TYPE_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002084 if (Record.size() != 1) {
2085 Error("Incorrect encoding of pointer type");
2086 return QualType();
2087 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002088 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002089 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002090 }
2091
2092 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002093 if (Record.size() != 1) {
2094 Error("Incorrect encoding of block pointer type");
2095 return QualType();
2096 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002097 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002098 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002099 }
2100
2101 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002102 if (Record.size() != 1) {
2103 Error("Incorrect encoding of lvalue reference type");
2104 return QualType();
2105 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002106 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002107 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002108 }
2109
2110 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002111 if (Record.size() != 1) {
2112 Error("Incorrect encoding of rvalue reference type");
2113 return QualType();
2114 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002115 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002116 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002117 }
2118
2119 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidisee776bc2010-07-02 11:55:15 +00002120 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002121 Error("Incorrect encoding of member pointer type");
2122 return QualType();
2123 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002124 QualType PointeeType = GetType(Record[0]);
2125 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002126 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002127 }
2128
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002129 case pch::TYPE_CONSTANT_ARRAY: {
2130 QualType ElementType = GetType(Record[0]);
2131 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2132 unsigned IndexTypeQuals = Record[2];
2133 unsigned Idx = 3;
2134 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00002135 return Context->getConstantArrayType(ElementType, Size,
2136 ASM, IndexTypeQuals);
2137 }
2138
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002139 case pch::TYPE_INCOMPLETE_ARRAY: {
2140 QualType ElementType = GetType(Record[0]);
2141 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2142 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00002143 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002144 }
2145
2146 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002147 QualType ElementType = GetType(Record[0]);
2148 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2149 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00002150 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2151 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002152 return Context->getVariableArrayType(ElementType, ReadExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00002153 ASM, IndexTypeQuals,
2154 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002155 }
2156
2157 case pch::TYPE_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002158 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002159 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002160 return QualType();
2161 }
2162
2163 QualType ElementType = GetType(Record[0]);
2164 unsigned NumElements = Record[1];
Chris Lattner37141f42010-06-23 06:00:24 +00002165 unsigned AltiVecSpec = Record[2];
2166 return Context->getVectorType(ElementType, NumElements,
2167 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002168 }
2169
2170 case pch::TYPE_EXT_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002171 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002172 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002173 return QualType();
2174 }
2175
2176 QualType ElementType = GetType(Record[0]);
2177 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00002178 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002179 }
2180
2181 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002182 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002183 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002184 return QualType();
2185 }
2186 QualType ResultType = GetType(Record[0]);
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002187 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002188 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002189 }
2190
2191 case pch::TYPE_FUNCTION_PROTO: {
2192 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00002193 bool NoReturn = Record[1];
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002194 unsigned RegParm = Record[2];
2195 CallingConv CallConv = (CallingConv)Record[3];
2196 unsigned Idx = 4;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002197 unsigned NumParams = Record[Idx++];
2198 llvm::SmallVector<QualType, 16> ParamTypes;
2199 for (unsigned I = 0; I != NumParams; ++I)
2200 ParamTypes.push_back(GetType(Record[Idx++]));
2201 bool isVariadic = Record[Idx++];
2202 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002203 bool hasExceptionSpec = Record[Idx++];
2204 bool hasAnyExceptionSpec = Record[Idx++];
2205 unsigned NumExceptions = Record[Idx++];
2206 llvm::SmallVector<QualType, 2> Exceptions;
2207 for (unsigned I = 0; I != NumExceptions; ++I)
2208 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00002209 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002210 isVariadic, Quals, hasExceptionSpec,
2211 hasAnyExceptionSpec, NumExceptions,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002212 Exceptions.data(),
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002213 FunctionType::ExtInfo(NoReturn, RegParm,
2214 CallConv));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002215 }
2216
John McCallb96ec562009-12-04 22:46:56 +00002217 case pch::TYPE_UNRESOLVED_USING:
2218 return Context->getTypeDeclType(
2219 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2220
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002221 case pch::TYPE_TYPEDEF: {
2222 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002223 Error("incorrect encoding of typedef type");
2224 return QualType();
2225 }
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002226 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2227 QualType Canonical = GetType(Record[1]);
2228 return Context->getTypedefType(Decl, Canonical);
2229 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002230
2231 case pch::TYPE_TYPEOF_EXPR:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002232 return Context->getTypeOfExprType(ReadExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002233
2234 case pch::TYPE_TYPEOF: {
2235 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002236 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002237 return QualType();
2238 }
2239 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002240 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002241 }
Mike Stump11289f42009-09-09 15:08:12 +00002242
Anders Carlsson81df7b82009-06-24 19:06:50 +00002243 case pch::TYPE_DECLTYPE:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002244 return Context->getDecltypeType(ReadExpr());
Anders Carlsson81df7b82009-06-24 19:06:50 +00002245
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002246 case pch::TYPE_RECORD: {
2247 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002248 Error("incorrect encoding of record type");
2249 return QualType();
2250 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002251 bool IsDependent = Record[0];
2252 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2253 T->Dependent = IsDependent;
2254 return T;
2255 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002256
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002257 case pch::TYPE_ENUM: {
2258 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002259 Error("incorrect encoding of enum type");
2260 return QualType();
2261 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002262 bool IsDependent = Record[0];
2263 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2264 T->Dependent = IsDependent;
2265 return T;
2266 }
Douglas Gregor1daeb692009-04-13 18:14:40 +00002267
John McCallfcc33b02009-09-05 00:15:47 +00002268 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002269 unsigned Idx = 0;
2270 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2271 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2272 QualType NamedType = GetType(Record[Idx++]);
2273 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCallfcc33b02009-09-05 00:15:47 +00002274 }
2275
Steve Naroffc277ad12009-07-18 15:33:26 +00002276 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00002277 unsigned Idx = 0;
2278 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002279 return Context->getObjCInterfaceType(ItfD);
2280 }
2281
2282 case pch::TYPE_OBJC_OBJECT: {
2283 unsigned Idx = 0;
2284 QualType Base = GetType(Record[Idx++]);
Chris Lattner587cbe12009-04-22 06:45:28 +00002285 unsigned NumProtos = Record[Idx++];
2286 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2287 for (unsigned I = 0; I != NumProtos; ++I)
2288 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCall8b07ec22010-05-15 11:32:37 +00002289 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00002290 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002291
Steve Narofffb4330f2009-06-17 22:40:22 +00002292 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00002293 unsigned Idx = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002294 QualType Pointee = GetType(Record[Idx++]);
2295 return Context->getObjCObjectPointerType(Pointee);
Chris Lattner6e054af2009-04-22 06:40:03 +00002296 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00002297
John McCallcebee162009-10-18 09:09:24 +00002298 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2299 unsigned Idx = 0;
2300 QualType Parm = GetType(Record[Idx++]);
2301 QualType Replacement = GetType(Record[Idx++]);
2302 return
2303 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2304 Replacement);
2305 }
John McCalle78aac42010-03-10 03:28:59 +00002306
2307 case pch::TYPE_INJECTED_CLASS_NAME: {
2308 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2309 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidisdab33c52010-07-02 11:55:20 +00002310 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2311 // for PCH reading, too much interdependencies.
2312 return
2313 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCalle78aac42010-03-10 03:28:59 +00002314 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002315
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002316 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2317 unsigned Idx = 0;
2318 unsigned Depth = Record[Idx++];
2319 unsigned Index = Record[Idx++];
2320 bool Pack = Record[Idx++];
2321 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2322 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2323 }
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002324
2325 case pch::TYPE_DEPENDENT_NAME: {
2326 unsigned Idx = 0;
2327 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2328 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2329 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidise9290952010-07-02 11:55:24 +00002330 QualType Canon = GetType(Record[Idx++]);
2331 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002332 }
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002333
2334 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2335 unsigned Idx = 0;
2336 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2337 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2338 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2339 unsigned NumArgs = Record[Idx++];
2340 llvm::SmallVector<TemplateArgument, 8> Args;
2341 Args.reserve(NumArgs);
2342 while (NumArgs--)
2343 Args.push_back(ReadTemplateArgument(Record, Idx));
2344 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2345 Args.size(), Args.data());
2346 }
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00002347
2348 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2349 unsigned Idx = 0;
2350
2351 // ArrayType
2352 QualType ElementType = GetType(Record[Idx++]);
2353 ArrayType::ArraySizeModifier ASM
2354 = (ArrayType::ArraySizeModifier)Record[Idx++];
2355 unsigned IndexTypeQuals = Record[Idx++];
2356
2357 // DependentSizedArrayType
2358 Expr *NumElts = ReadExpr();
2359 SourceRange Brackets = ReadSourceRange(Record, Idx);
2360
2361 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2362 IndexTypeQuals, Brackets);
2363 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002364
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002365 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2366 unsigned Idx = 0;
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002367 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002368 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002369 llvm::SmallVector<TemplateArgument, 8> Args;
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00002370 ReadTemplateArgumentList(Args, Record, Idx);
2371 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002372 QualType T;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002373 if (Canon.isNull())
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002374 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2375 Args.size());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002376 else
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002377 T = Context->getTemplateSpecializationType(Name, Args.data(),
2378 Args.size(), Canon);
2379 T->Dependent = IsDependent;
2380 return T;
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002381 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002382 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002383 // Suppress a GCC warning
2384 return QualType();
2385}
2386
John McCall8f115c62009-10-16 21:56:05 +00002387namespace {
2388
2389class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2390 PCHReader &Reader;
2391 const PCHReader::RecordData &Record;
2392 unsigned &Idx;
2393
2394public:
2395 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2396 unsigned &Idx)
2397 : Reader(Reader), Record(Record), Idx(Idx) { }
2398
John McCall17001972009-10-18 01:05:36 +00002399 // We want compile-time assurance that we've enumerated all of
2400 // these, so unfortunately we have to declare them first, then
2401 // define them out-of-line.
2402#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002403#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002404 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002405#include "clang/AST/TypeLocNodes.def"
2406
John McCall17001972009-10-18 01:05:36 +00002407 void VisitFunctionTypeLoc(FunctionTypeLoc);
2408 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002409};
2410
2411}
2412
John McCall17001972009-10-18 01:05:36 +00002413void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002414 // nothing to do
2415}
John McCall17001972009-10-18 01:05:36 +00002416void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +00002417 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2418 if (TL.needsExtraLocalData()) {
2419 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2420 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2421 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2422 TL.setModeAttr(Record[Idx++]);
2423 }
John McCall8f115c62009-10-16 21:56:05 +00002424}
John McCall17001972009-10-18 01:05:36 +00002425void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2426 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002427}
John McCall17001972009-10-18 01:05:36 +00002428void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2429 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002430}
John McCall17001972009-10-18 01:05:36 +00002431void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2432 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002433}
John McCall17001972009-10-18 01:05:36 +00002434void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2435 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002436}
John McCall17001972009-10-18 01:05:36 +00002437void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2438 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002439}
John McCall17001972009-10-18 01:05:36 +00002440void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2441 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002442}
John McCall17001972009-10-18 01:05:36 +00002443void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2444 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2445 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002446 if (Record[Idx++])
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002447 TL.setSizeExpr(Reader.ReadExpr());
Douglas Gregor12bfa382009-10-17 00:13:19 +00002448 else
John McCall17001972009-10-18 01:05:36 +00002449 TL.setSizeExpr(0);
2450}
2451void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2452 VisitArrayTypeLoc(TL);
2453}
2454void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2455 VisitArrayTypeLoc(TL);
2456}
2457void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2458 VisitArrayTypeLoc(TL);
2459}
2460void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2461 DependentSizedArrayTypeLoc TL) {
2462 VisitArrayTypeLoc(TL);
2463}
2464void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2465 DependentSizedExtVectorTypeLoc TL) {
2466 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2467}
2468void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2469 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2470}
2471void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2472 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2473}
2474void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2475 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2476 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2477 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002478 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002479 }
2480}
2481void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2482 VisitFunctionTypeLoc(TL);
2483}
2484void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2485 VisitFunctionTypeLoc(TL);
2486}
John McCallb96ec562009-12-04 22:46:56 +00002487void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2488 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2489}
John McCall17001972009-10-18 01:05:36 +00002490void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2491 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2492}
2493void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002494 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2495 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2496 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002497}
2498void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002499 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2500 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2501 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2502 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002503}
2504void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2505 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2506}
2507void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2508 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2509}
2510void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2511 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2512}
John McCall17001972009-10-18 01:05:36 +00002513void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2514 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2515}
John McCallcebee162009-10-18 09:09:24 +00002516void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2517 SubstTemplateTypeParmTypeLoc TL) {
2518 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2519}
John McCall17001972009-10-18 01:05:36 +00002520void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2521 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002522 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2523 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2524 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2525 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2526 TL.setArgLocInfo(i,
2527 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2528 Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002529}
Abramo Bagnara6150c882010-05-11 21:36:43 +00002530void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002531 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2532 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002533}
John McCalle78aac42010-03-10 03:28:59 +00002534void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2535 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2536}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002537void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002538 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2539 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002540 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2541}
John McCallc392f372010-06-11 00:33:02 +00002542void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2543 DependentTemplateSpecializationTypeLoc TL) {
2544 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2545 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2546 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2547 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2548 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2549 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2550 TL.setArgLocInfo(I,
2551 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
2552 Record, Idx));
2553}
John McCall17001972009-10-18 01:05:36 +00002554void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2555 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002556}
2557void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2558 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall17001972009-10-18 01:05:36 +00002559 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2560 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2561 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2562 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002563}
John McCallfc93cf92009-10-22 22:37:11 +00002564void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2565 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallfc93cf92009-10-22 22:37:11 +00002566}
John McCall8f115c62009-10-16 21:56:05 +00002567
John McCallbcd03502009-12-07 02:54:59 +00002568TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002569 unsigned &Idx) {
2570 QualType InfoTy = GetType(Record[Idx++]);
2571 if (InfoTy.isNull())
2572 return 0;
2573
John McCallbcd03502009-12-07 02:54:59 +00002574 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCall8f115c62009-10-16 21:56:05 +00002575 TypeLocReader TLR(*this, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002576 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002577 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002578 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002579}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002580
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002581QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002582 unsigned FastQuals = ID & Qualifiers::FastMask;
2583 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002584
2585 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2586 QualType T;
2587 switch ((pch::PredefinedTypeIDs)Index) {
2588 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002589 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2590 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002591
2592 case pch::PREDEF_TYPE_CHAR_U_ID:
2593 case pch::PREDEF_TYPE_CHAR_S_ID:
2594 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002595 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002596 break;
2597
Chris Lattner8575daa2009-04-27 21:45:14 +00002598 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2599 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2600 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2601 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2602 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002603 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002604 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2605 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2606 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2607 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2608 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2609 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002610 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002611 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2612 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2613 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2614 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2615 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002616 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002617 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2618 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002619 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2620 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002621 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002622 }
2623
2624 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002625 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002626 }
2627
2628 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002629 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl409183f2010-07-14 20:26:45 +00002630 if (TypesLoaded[Index].isNull()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002631 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Sebastian Redl409183f2010-07-14 20:26:45 +00002632 TypesLoaded[Index]->setFromPCH();
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002633 if (DeserializationListener)
2634 DeserializationListener->TypeRead(ID, TypesLoaded[Index]);
Sebastian Redl409183f2010-07-14 20:26:45 +00002635 }
Mike Stump11289f42009-09-09 15:08:12 +00002636
John McCall8ccfcb52009-09-24 19:53:00 +00002637 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002638}
2639
John McCall0ad16662009-10-29 08:12:44 +00002640TemplateArgumentLocInfo
2641PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2642 const RecordData &Record,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002643 unsigned &Index) {
John McCall0ad16662009-10-29 08:12:44 +00002644 switch (Kind) {
2645 case TemplateArgument::Expression:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002646 return ReadExpr();
John McCall0ad16662009-10-29 08:12:44 +00002647 case TemplateArgument::Type:
John McCallbcd03502009-12-07 02:54:59 +00002648 return GetTypeSourceInfo(Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002649 case TemplateArgument::Template: {
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002650 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2651 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2652 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002653 }
John McCall0ad16662009-10-29 08:12:44 +00002654 case TemplateArgument::Null:
2655 case TemplateArgument::Integral:
2656 case TemplateArgument::Declaration:
2657 case TemplateArgument::Pack:
2658 return TemplateArgumentLocInfo();
2659 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002660 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002661 return TemplateArgumentLocInfo();
2662}
2663
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002664TemplateArgumentLoc
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002665PCHReader::ReadTemplateArgumentLoc(const RecordData &Record, unsigned &Index) {
2666 TemplateArgument Arg = ReadTemplateArgument(Record, Index);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002667
2668 if (Arg.getKind() == TemplateArgument::Expression) {
2669 if (Record[Index++]) // bool InfoHasSameExpr.
2670 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2671 }
2672 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002673 Record, Index));
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00002674}
2675
John McCall75b960e2010-06-01 09:23:16 +00002676Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2677 return GetDecl(ID);
2678}
2679
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002680TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002681 if (!DeclsLoaded[0]) {
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002682 ReadDeclRecord(DeclOffsets[0], 0);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002683 if (DeserializationListener)
2684 DeserializationListener->DeclRead(0, DeclsLoaded[0]);
2685 }
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002686
2687 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2688}
2689
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002690Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002691 if (ID == 0)
2692 return 0;
2693
Douglas Gregor745ed142009-04-25 18:35:21 +00002694 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002695 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002696 return 0;
2697 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002698
Douglas Gregor745ed142009-04-25 18:35:21 +00002699 unsigned Index = ID - 1;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002700 if (!DeclsLoaded[Index]) {
Douglas Gregor745ed142009-04-25 18:35:21 +00002701 ReadDeclRecord(DeclOffsets[Index], Index);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002702 if (DeserializationListener)
2703 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2704 }
Douglas Gregor745ed142009-04-25 18:35:21 +00002705
2706 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002707}
2708
Chris Lattner9c28af02009-04-27 05:46:25 +00002709/// \brief Resolve the offset of a statement into a statement.
2710///
2711/// This operation will read a new statement from the external
2712/// source each time it is called, and is meant to be used via a
2713/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall75b960e2010-06-01 09:23:16 +00002714Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002715 // Since we know tha this statement is part of a decl, make sure to use the
2716 // decl cursor to read it.
2717 DeclsCursor.JumpToBit(Offset);
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002718 return ReadStmtFromStream(DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002719}
2720
John McCall75b960e2010-06-01 09:23:16 +00002721bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2722 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002723 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002724 "DeclContext has no lexical decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002725
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002726 uint64_t Offset = DeclContextOffsets[DC].first;
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002727 if (Offset == 0) {
2728 Error("DeclContext has no lexical decls in storage");
2729 return true;
2730 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002731
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002732 // Keep track of where we are in the stream, then jump back there
2733 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002734 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002735
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002736 // Load the record containing all of the declarations lexically in
2737 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002738 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002739 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002740 unsigned Code = DeclsCursor.ReadCode();
2741 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002742 if (RecCode != pch::DECL_CONTEXT_LEXICAL) {
2743 Error("Expected lexical block");
2744 return true;
2745 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002746
2747 // Load all of the declaration IDs
John McCall75b960e2010-06-01 09:23:16 +00002748 for (RecordData::iterator I = Record.begin(), E = Record.end(); I != E; ++I)
2749 Decls.push_back(GetDecl(*I));
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002750 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002751 return false;
2752}
2753
John McCall75b960e2010-06-01 09:23:16 +00002754DeclContext::lookup_result
2755PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2756 DeclarationName Name) {
Mike Stump11289f42009-09-09 15:08:12 +00002757 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002758 "DeclContext has no visible decls in storage");
2759 uint64_t Offset = DeclContextOffsets[DC].second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002760 if (Offset == 0) {
2761 Error("DeclContext has no visible decls in storage");
John McCall75b960e2010-06-01 09:23:16 +00002762 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2763 DeclContext::lookup_iterator());
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002764 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002765
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002766 // Keep track of where we are in the stream, then jump back there
2767 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002768 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002769
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002770 // Load the record containing all of the declarations visible in
2771 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002772 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002773 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002774 unsigned Code = DeclsCursor.ReadCode();
2775 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002776 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2777 Error("Expected visible block");
John McCall75b960e2010-06-01 09:23:16 +00002778 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2779 DeclContext::lookup_iterator());
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002780 }
2781
John McCall75b960e2010-06-01 09:23:16 +00002782 llvm::SmallVector<VisibleDeclaration, 64> Decls;
2783 if (Record.empty()) {
2784 SetExternalVisibleDecls(DC, Decls);
2785 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2786 DeclContext::lookup_iterator());
2787 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002788
2789 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002790 while (Idx < Record.size()) {
2791 Decls.push_back(VisibleDeclaration());
2792 Decls.back().Name = ReadDeclarationName(Record, Idx);
2793
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002794 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002795 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002796 LoadedDecls.reserve(Size);
2797 for (unsigned I = 0; I < Size; ++I)
2798 LoadedDecls.push_back(Record[Idx++]);
2799 }
2800
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002801 ++NumVisibleDeclContextsRead;
John McCall75b960e2010-06-01 09:23:16 +00002802
2803 SetExternalVisibleDecls(DC, Decls);
2804 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002805}
2806
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00002807void PCHReader::PassInterestingDeclsToConsumer() {
2808 assert(Consumer);
2809 while (!InterestingDecls.empty()) {
2810 DeclGroupRef DG(InterestingDecls.front());
2811 InterestingDecls.pop_front();
2812 Consumer->HandleTopLevelDecl(DG);
2813 }
2814}
2815
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002816void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002817 this->Consumer = Consumer;
2818
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002819 if (!Consumer)
2820 return;
2821
2822 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00002823 // Force deserialization of this decl, which will cause it to be queued for
2824 // passing to the consumer.
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002825 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002826 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002827
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00002828 PassInterestingDeclsToConsumer();
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002829}
2830
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002831void PCHReader::PrintStats() {
2832 std::fprintf(stderr, "*** PCH Statistics:\n");
2833
Mike Stump11289f42009-09-09 15:08:12 +00002834 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002835 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00002836 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00002837 unsigned NumDeclsLoaded
2838 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2839 (Decl *)0);
2840 unsigned NumIdentifiersLoaded
2841 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2842 IdentifiersLoaded.end(),
2843 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002844 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002845 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2846 SelectorsLoaded.end(),
2847 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002848
Douglas Gregorc5046832009-04-27 18:38:38 +00002849 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2850 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002851 if (TotalNumSLocEntries)
2852 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2853 NumSLocEntriesRead, TotalNumSLocEntries,
2854 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002855 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002856 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002857 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2858 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2859 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002860 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002861 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2862 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002863 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002864 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002865 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2866 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002867 if (TotalNumSelectors)
2868 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2869 NumSelectorsLoaded, TotalNumSelectors,
2870 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2871 if (TotalNumStatements)
2872 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2873 NumStatementsRead, TotalNumStatements,
2874 ((float)NumStatementsRead/TotalNumStatements * 100));
2875 if (TotalNumMacros)
2876 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2877 NumMacrosRead, TotalNumMacros,
2878 ((float)NumMacrosRead/TotalNumMacros * 100));
2879 if (TotalLexicalDeclContexts)
2880 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2881 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2882 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2883 * 100));
2884 if (TotalVisibleDeclContexts)
2885 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2886 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2887 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2888 * 100));
2889 if (TotalSelectorsInMethodPool) {
2890 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2891 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2892 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2893 * 100));
2894 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2895 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002896 std::fprintf(stderr, "\n");
2897}
2898
Douglas Gregora868bbd2009-04-21 22:25:48 +00002899void PCHReader::InitializeSema(Sema &S) {
2900 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002901 S.ExternalSource = this;
2902
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002903 // Makes sure any declarations that were deserialized "too early"
2904 // still get added to the identifier's declaration chains.
2905 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2906 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2907 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002908 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002909 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002910
2911 // If there were any tentative definitions, deserialize them and add
Sebastian Redl35351a92010-01-31 22:27:38 +00002912 // them to Sema's list of tentative definitions.
Douglas Gregord4df8652009-04-22 22:02:47 +00002913 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2914 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redl35351a92010-01-31 22:27:38 +00002915 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregord4df8652009-04-22 22:02:47 +00002916 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00002917
Tanya Lattner90073802010-02-12 00:07:30 +00002918 // If there were any unused static functions, deserialize them and add to
2919 // Sema's list of unused static functions.
2920 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
2921 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
2922 SemaObj->UnusedStaticFuncs.push_back(FD);
2923 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002924
2925 // If there were any locally-scoped external declarations,
2926 // deserialize them and add them to Sema's table of locally-scoped
2927 // external declarations.
2928 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2929 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2930 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2931 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002932
2933 // If there were any ext_vector type declarations, deserialize them
2934 // and add them to Sema's vector of such declarations.
2935 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2936 SemaObj->ExtVectorDecls.push_back(
2937 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00002938
2939 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
2940 // Can we cut them down before writing them ?
2941
2942 // If there were any VTable uses, deserialize the information and add it
2943 // to Sema's vector and map of VTable uses.
2944 unsigned Idx = 0;
2945 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
2946 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
2947 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
2948 bool DefinitionRequired = VTableUses[Idx++];
2949 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
2950 SemaObj->VTablesUsed[Class] = DefinitionRequired;
2951 }
2952
2953 // If there were any dynamic classes declarations, deserialize them
2954 // and add them to Sema's vector of such declarations.
2955 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
2956 SemaObj->DynamicClasses.push_back(
2957 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00002958}
2959
2960IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2961 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00002962 PCHIdentifierLookupTable *IdTable
Douglas Gregora868bbd2009-04-21 22:25:48 +00002963 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2964 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2965 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2966 if (Pos == IdTable->end())
2967 return 0;
2968
2969 // Dereferencing the iterator has the effect of building the
2970 // IdentifierInfo node and populating it with the various
2971 // declarations it needs.
2972 return *Pos;
2973}
2974
Mike Stump11289f42009-09-09 15:08:12 +00002975std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00002976PCHReader::ReadMethodPool(Selector Sel) {
2977 if (!MethodPoolLookupTable)
2978 return std::pair<ObjCMethodList, ObjCMethodList>();
2979
2980 // Try to find this selector within our on-disk hash table.
2981 PCHMethodPoolLookupTable *PoolTable
2982 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2983 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00002984 if (Pos == PoolTable->end()) {
2985 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002986 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00002987 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00002988
Douglas Gregor95c13f52009-04-25 17:48:32 +00002989 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002990 return *Pos;
2991}
2992
Douglas Gregor0e149972009-04-25 19:10:14 +00002993void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00002994 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002995 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00002996 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00002997}
2998
Douglas Gregor1342e842009-07-06 18:54:52 +00002999/// \brief Set the globally-visible declarations associated with the given
3000/// identifier.
3001///
3002/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00003003/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00003004/// them.
3005///
3006/// \param II an IdentifierInfo that refers to one or more globally-visible
3007/// declarations.
3008///
3009/// \param DeclIDs the set of declaration IDs with the name @p II that are
3010/// visible at global scope.
3011///
3012/// \param Nonrecursive should be true to indicate that the caller knows that
3013/// this call is non-recursive, and therefore the globally-visible declarations
3014/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00003015void
3016PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00003017 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3018 bool Nonrecursive) {
3019 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
3020 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3021 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3022 PII.II = II;
3023 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3024 PII.DeclIDs.push_back(DeclIDs[I]);
3025 return;
3026 }
Mike Stump11289f42009-09-09 15:08:12 +00003027
Douglas Gregor1342e842009-07-06 18:54:52 +00003028 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3029 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3030 if (SemaObj) {
3031 // Introduce this declaration into the translation-unit scope
3032 // and add it to the declaration chain for this identifier, so
3033 // that (unqualified) name lookup will find it.
3034 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3035 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3036 } else {
3037 // Queue this declaration so that it will be added to the
3038 // translation unit scope and identifier's declaration chain
3039 // once a Sema object is known.
3040 PreloadedDecls.push_back(D);
3041 }
3042 }
3043}
3044
Chris Lattnerc523d8e2009-04-11 21:15:38 +00003045IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003046 if (ID == 0)
3047 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003048
Douglas Gregor0e149972009-04-25 19:10:14 +00003049 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003050 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003051 return 0;
3052 }
Mike Stump11289f42009-09-09 15:08:12 +00003053
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003054 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00003055 if (!IdentifiersLoaded[ID - 1]) {
3056 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor95272492009-04-25 21:21:38 +00003057 const char *Str = IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00003058
Douglas Gregorab4df582009-04-28 20:01:51 +00003059 // All of the strings in the PCH file are preceded by a 16-bit
3060 // length. Extract that 16-bit length to avoid having to execute
3061 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00003062 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3063 // unsigned integers. This is important to avoid integer overflow when
3064 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00003065 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00003066 unsigned StrLen = (((unsigned) StrLenPtr[0])
3067 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00003068 IdentifiersLoaded[ID - 1]
Kovarththanan Rajaratnama3b09592010-03-12 10:32:27 +00003069 = &PP->getIdentifierTable().get(Str, StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003070 }
Mike Stump11289f42009-09-09 15:08:12 +00003071
Douglas Gregor0e149972009-04-25 19:10:14 +00003072 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003073}
3074
Douglas Gregor258ae542009-04-27 06:38:32 +00003075void PCHReader::ReadSLocEntry(unsigned ID) {
3076 ReadSLocEntryRecord(ID);
3077}
3078
Steve Naroff2ddea052009-04-23 10:39:46 +00003079Selector PCHReader::DecodeSelector(unsigned ID) {
3080 if (ID == 0)
3081 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00003082
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003083 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00003084 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00003085
3086 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003087 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00003088 return Selector();
3089 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003090
3091 unsigned Index = ID - 1;
3092 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
3093 // Load this selector from the selector table.
3094 // FIXME: endianness portability issues with SelectorOffsets table
3095 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003096 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00003097 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
3098 }
3099
3100 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00003101}
3102
John McCall75b960e2010-06-01 09:23:16 +00003103Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003104 return DecodeSelector(ID);
3105}
3106
John McCall75b960e2010-06-01 09:23:16 +00003107uint32_t PCHReader::GetNumExternalSelectors() {
Douglas Gregord720daf2010-04-06 17:30:22 +00003108 return TotalNumSelectors + 1;
3109}
3110
Mike Stump11289f42009-09-09 15:08:12 +00003111DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003112PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3113 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3114 switch (Kind) {
3115 case DeclarationName::Identifier:
3116 return DeclarationName(GetIdentifierInfo(Record, Idx));
3117
3118 case DeclarationName::ObjCZeroArgSelector:
3119 case DeclarationName::ObjCOneArgSelector:
3120 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00003121 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003122
3123 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003124 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003125 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003126
3127 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003128 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003129 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003130
3131 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003132 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003133 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003134
3135 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003136 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003137 (OverloadedOperatorKind)Record[Idx++]);
3138
Alexis Hunt3d221f22009-11-29 07:34:05 +00003139 case DeclarationName::CXXLiteralOperatorName:
3140 return Context->DeclarationNames.getCXXLiteralOperatorName(
3141 GetIdentifierInfo(Record, Idx));
3142
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003143 case DeclarationName::CXXUsingDirective:
3144 return DeclarationName::getUsingDirectiveName();
3145 }
3146
3147 // Required to silence GCC warning
3148 return DeclarationName();
3149}
Douglas Gregor55abb232009-04-10 20:39:37 +00003150
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003151TemplateName
3152PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3153 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3154 switch (Kind) {
3155 case TemplateName::Template:
3156 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3157
3158 case TemplateName::OverloadedTemplate: {
3159 unsigned size = Record[Idx++];
3160 UnresolvedSet<8> Decls;
3161 while (size--)
3162 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3163
3164 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3165 }
3166
3167 case TemplateName::QualifiedTemplate: {
3168 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3169 bool hasTemplKeyword = Record[Idx++];
3170 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3171 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3172 }
3173
3174 case TemplateName::DependentTemplate: {
3175 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3176 if (Record[Idx++]) // isIdentifier
3177 return Context->getDependentTemplateName(NNS,
3178 GetIdentifierInfo(Record, Idx));
3179 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00003180 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003181 }
3182 }
3183
3184 assert(0 && "Unhandled template name kind!");
3185 return TemplateName();
3186}
3187
3188TemplateArgument
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00003189PCHReader::ReadTemplateArgument(const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003190 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3191 case TemplateArgument::Null:
3192 return TemplateArgument();
3193 case TemplateArgument::Type:
3194 return TemplateArgument(GetType(Record[Idx++]));
3195 case TemplateArgument::Declaration:
3196 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidis0b0369a2010-06-28 09:31:34 +00003197 case TemplateArgument::Integral: {
3198 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3199 QualType T = GetType(Record[Idx++]);
3200 return TemplateArgument(Value, T);
3201 }
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003202 case TemplateArgument::Template:
3203 return TemplateArgument(ReadTemplateName(Record, Idx));
3204 case TemplateArgument::Expression:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00003205 return TemplateArgument(ReadExpr());
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003206 case TemplateArgument::Pack: {
3207 unsigned NumArgs = Record[Idx++];
3208 llvm::SmallVector<TemplateArgument, 8> Args;
3209 Args.reserve(NumArgs);
3210 while (NumArgs--)
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00003211 Args.push_back(ReadTemplateArgument(Record, Idx));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003212 TemplateArgument TemplArg;
3213 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3214 return TemplArg;
3215 }
3216 }
3217
3218 assert(0 && "Unhandled template argument kind!");
3219 return TemplateArgument();
3220}
3221
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003222TemplateParameterList *
3223PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3224 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3225 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3226 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3227
3228 unsigned NumParams = Record[Idx++];
3229 llvm::SmallVector<NamedDecl *, 16> Params;
3230 Params.reserve(NumParams);
3231 while (NumParams--)
3232 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3233
3234 TemplateParameterList* TemplateParams =
3235 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3236 Params.data(), Params.size(), RAngleLoc);
3237 return TemplateParams;
3238}
3239
3240void
3241PCHReader::
3242ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
3243 const RecordData &Record, unsigned &Idx) {
3244 unsigned NumTemplateArgs = Record[Idx++];
3245 TemplArgs.reserve(NumTemplateArgs);
3246 while (NumTemplateArgs--)
3247 TemplArgs.push_back(ReadTemplateArgument(Record, Idx));
3248}
3249
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00003250/// \brief Read a UnresolvedSet structure.
3251void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3252 const RecordData &Record, unsigned &Idx) {
3253 unsigned NumDecls = Record[Idx++];
3254 while (NumDecls--) {
3255 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3256 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3257 Set.addDecl(D, AS);
3258 }
3259}
3260
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003261CXXBaseSpecifier
3262PCHReader::ReadCXXBaseSpecifier(const RecordData &Record, unsigned &Idx) {
3263 bool isVirtual = static_cast<bool>(Record[Idx++]);
3264 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3265 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
3266 QualType T = GetType(Record[Idx++]);
3267 SourceRange Range = ReadSourceRange(Record, Idx);
3268 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, T);
3269}
3270
Chris Lattnerca025db2010-05-07 21:43:38 +00003271NestedNameSpecifier *
3272PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3273 unsigned N = Record[Idx++];
3274 NestedNameSpecifier *NNS = 0, *Prev = 0;
3275 for (unsigned I = 0; I != N; ++I) {
3276 NestedNameSpecifier::SpecifierKind Kind
3277 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3278 switch (Kind) {
3279 case NestedNameSpecifier::Identifier: {
3280 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3281 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3282 break;
3283 }
3284
3285 case NestedNameSpecifier::Namespace: {
3286 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3287 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3288 break;
3289 }
3290
3291 case NestedNameSpecifier::TypeSpec:
3292 case NestedNameSpecifier::TypeSpecWithTemplate: {
3293 Type *T = GetType(Record[Idx++]).getTypePtr();
3294 bool Template = Record[Idx++];
3295 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3296 break;
3297 }
3298
3299 case NestedNameSpecifier::Global: {
3300 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3301 // No associated value, and there can't be a prefix.
3302 break;
3303 }
Chris Lattnerca025db2010-05-07 21:43:38 +00003304 }
Argyrios Kyrtzidisad65c692010-07-07 15:46:30 +00003305 Prev = NNS;
Chris Lattnerca025db2010-05-07 21:43:38 +00003306 }
3307 return NNS;
3308}
3309
3310SourceRange
3311PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar6d3bc082010-06-02 15:47:10 +00003312 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3313 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3314 return SourceRange(beg, end);
Chris Lattnerca025db2010-05-07 21:43:38 +00003315}
3316
Douglas Gregor1daeb692009-04-13 18:14:40 +00003317/// \brief Read an integral value
3318llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3319 unsigned BitWidth = Record[Idx++];
3320 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3321 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3322 Idx += NumWords;
3323 return Result;
3324}
3325
3326/// \brief Read a signed integral value
3327llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3328 bool isUnsigned = Record[Idx++];
3329 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3330}
3331
Douglas Gregore0a3a512009-04-14 21:55:33 +00003332/// \brief Read a floating-point value
3333llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00003334 return llvm::APFloat(ReadAPInt(Record, Idx));
3335}
3336
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003337// \brief Read a string
3338std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3339 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00003340 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003341 Idx += Len;
3342 return Result;
3343}
3344
Chris Lattnercba86142010-05-10 00:25:06 +00003345CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3346 unsigned &Idx) {
3347 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3348 return CXXTemporary::Create(*Context, Decl);
3349}
3350
Douglas Gregor55abb232009-04-10 20:39:37 +00003351DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00003352 return Diag(SourceLocation(), DiagID);
3353}
3354
3355DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003356 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00003357}
Douglas Gregora9af1d12009-04-17 00:04:06 +00003358
Douglas Gregora868bbd2009-04-21 22:25:48 +00003359/// \brief Retrieve the identifier table associated with the
3360/// preprocessor.
3361IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003362 assert(PP && "Forgot to set Preprocessor ?");
3363 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00003364}
3365
Douglas Gregora9af1d12009-04-17 00:04:06 +00003366/// \brief Record that the given ID maps to the given switch-case
3367/// statement.
3368void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3369 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3370 SwitchCaseStmts[ID] = SC;
3371}
3372
3373/// \brief Retrieve the switch-case statement with the given ID.
3374SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3375 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3376 return SwitchCaseStmts[ID];
3377}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003378
3379/// \brief Record that the given label statement has been
3380/// deserialized and has the given ID.
3381void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00003382 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003383 "Deserialized label twice");
3384 LabelStmts[ID] = S;
3385
3386 // If we've already seen any goto statements that point to this
3387 // label, resolve them now.
3388 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3389 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3390 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3391 Goto->second->setLabel(S);
3392 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00003393
3394 // If we've already seen any address-label statements that point to
3395 // this label, resolve them now.
3396 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00003397 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00003398 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00003399 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00003400 AddrLabel != AddrLabels.second; ++AddrLabel)
3401 AddrLabel->second->setLabel(S);
3402 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003403}
3404
3405/// \brief Set the label of the given statement to the label
3406/// identified by ID.
3407///
3408/// Depending on the order in which the label and other statements
3409/// referencing that label occur, this operation may complete
3410/// immediately (updating the statement) or it may queue the
3411/// statement to be back-patched later.
3412void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3413 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3414 if (Label != LabelStmts.end()) {
3415 // We've already seen this label, so set the label of the goto and
3416 // we're done.
3417 S->setLabel(Label->second);
3418 } else {
3419 // We haven't seen this label yet, so add this goto to the set of
3420 // unresolved goto statements.
3421 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3422 }
3423}
Douglas Gregor779d8652009-04-17 18:58:21 +00003424
3425/// \brief Set the label of the given expression to the label
3426/// identified by ID.
3427///
3428/// Depending on the order in which the label and other statements
3429/// referencing that label occur, this operation may complete
3430/// immediately (updating the statement) or it may queue the
3431/// statement to be back-patched later.
3432void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3433 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3434 if (Label != LabelStmts.end()) {
3435 // We've already seen this label, so set the label of the
3436 // label-address expression and we're done.
3437 S->setLabel(Label->second);
3438 } else {
3439 // We haven't seen this label yet, so add this label-address
3440 // expression to the set of unresolved label-address expressions.
3441 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3442 }
3443}
Douglas Gregor1342e842009-07-06 18:54:52 +00003444
3445
Mike Stump11289f42009-09-09 15:08:12 +00003446PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00003447 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
3448 Reader.CurrentlyLoadingTypeOrDecl = this;
3449}
3450
3451PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
3452 if (!Parent) {
3453 // If any identifiers with corresponding top-level declarations have
3454 // been loaded, load those declarations now.
3455 while (!Reader.PendingIdentifierInfos.empty()) {
3456 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
3457 Reader.PendingIdentifierInfos.front().DeclIDs,
3458 true);
3459 Reader.PendingIdentifierInfos.pop_front();
3460 }
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003461
3462 // We are not in recursive loading, so it's safe to pass the "interesting"
3463 // decls to the consumer.
3464 if (Reader.Consumer)
3465 Reader.PassInterestingDeclsToConsumer();
Douglas Gregor1342e842009-07-06 18:54:52 +00003466 }
3467
Mike Stump11289f42009-09-09 15:08:12 +00003468 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00003469}