blob: 7b95b8909af2552de42735a8fdba4b0f7ebfdbb8 [file] [log] [blame]
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner92ba5ff2009-04-27 05:14:47 +000013
Douglas Gregoref84c4b2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor55abb232009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Sebastian Redl85b2a6a2010-07-14 23:45:08 +000016#include "clang/Frontend/PCHDeserializationListener.h"
Daniel Dunbar732ef8a2009-11-11 23:58:53 +000017#include "clang/Frontend/Utils.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000018#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor1a0d0b92009-04-14 00:24:19 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000021#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000023#include "clang/AST/TypeLocVisitor.h"
Chris Lattner34321bc2009-04-10 21:41:48 +000024#include "clang/Lex/MacroInfo.h"
Douglas Gregoraae92242010-03-19 21:51:54 +000025#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000026#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000027#include "clang/Lex/HeaderSearch.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000028#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000029#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000030#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000031#include "clang/Basic/FileManager.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000032#include "clang/Basic/TargetInfo.h"
Douglas Gregord54f3a12009-10-05 21:07:28 +000033#include "clang/Basic/Version.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000035#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000036#include "llvm/Support/MemoryBuffer.h"
John McCall0ad16662009-10-29 08:12:44 +000037#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +000038#include "llvm/System/Path.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000039#include <algorithm>
Douglas Gregorc379c072009-04-28 18:58:38 +000040#include <iterator>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000041#include <cstdio>
Douglas Gregorc5046832009-04-27 18:38:38 +000042#include <sys/stat.h>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000043using namespace clang;
44
45//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000046// PCH reader validator implementation
47//===----------------------------------------------------------------------===//
48
49PCHReaderListener::~PCHReaderListener() {}
50
51bool
52PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
53 const LangOptions &PPLangOpts = PP.getLangOptions();
54#define PARSE_LANGOPT_BENIGN(Option)
55#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
56 if (PPLangOpts.Option != LangOpts.Option) { \
57 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
58 return true; \
59 }
60
61 PARSE_LANGOPT_BENIGN(Trigraphs);
62 PARSE_LANGOPT_BENIGN(BCPLComment);
63 PARSE_LANGOPT_BENIGN(DollarIdents);
64 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
65 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
Chandler Carruthe03aa552010-04-17 20:17:31 +000066 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000067 PARSE_LANGOPT_BENIGN(ImplicitInt);
68 PARSE_LANGOPT_BENIGN(Digraphs);
69 PARSE_LANGOPT_BENIGN(HexFloats);
70 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
71 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
72 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
73 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
74 PARSE_LANGOPT_BENIGN(CXXOperatorName);
75 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
76 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
77 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
Fariborz Jahanian45878032010-02-09 19:31:38 +000078 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Fariborz Jahanian62c56022010-04-22 21:01:59 +000079 PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
80 diag::warn_pch_no_constant_cfstrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000081 PARSE_LANGOPT_BENIGN(PascalStrings);
82 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump11289f42009-09-09 15:08:12 +000083 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000084 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +000085 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000086 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +000087 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000088 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
89 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
90 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +000091 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000092 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000093 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000094 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
95 PARSE_LANGOPT_BENIGN(EmitAllDecls);
96 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
Chris Lattner51924e512010-06-26 21:25:03 +000097 PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
Mike Stump11289f42009-09-09 15:08:12 +000098 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000099 diag::warn_pch_heinous_extensions);
100 // FIXME: Most of the options below are benign if the macro wasn't
101 // used. Unfortunately, this means that a PCH compiled without
102 // optimization can't be used with optimization turned on, even
103 // though the only thing that changes is whether __OPTIMIZE__ was
104 // defined... but if __OPTIMIZE__ never showed up in the header, it
105 // doesn't matter. We could consider making this some special kind
106 // of check.
107 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
108 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
109 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
110 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
111 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
112 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
113 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
114 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsoned4e2952009-11-05 20:14:16 +0000115 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000116 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000117 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000118 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
119 return true;
120 }
121 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000122 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
123 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000124 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000125 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stumpd9546382009-12-12 01:27:46 +0000126 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000127 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +0000128 PARSE_LANGOPT_BENIGN(SpellChecking);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +0000129#undef PARSE_LANGOPT_IMPORTANT
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000130#undef PARSE_LANGOPT_BENIGN
131
132 return false;
133}
134
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000135bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
136 if (Triple == PP.getTargetInfo().getTriple().str())
137 return false;
138
139 Reader.Diag(diag::warn_pch_target_triple)
140 << Triple << PP.getTargetInfo().getTriple().str();
141 return true;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000142}
143
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000144struct EmptyStringRef {
Benjamin Kramer8d5609b2010-07-14 23:19:41 +0000145 bool operator ()(llvm::StringRef r) const { return r.empty(); }
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000146};
147struct EmptyBlock {
148 bool operator ()(const PCHPredefinesBlock &r) const { return r.Data.empty(); }
149};
150
151static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L,
152 PCHPredefinesBlocks R) {
153 // First, sum up the lengths.
154 unsigned LL = 0, RL = 0;
155 for (unsigned I = 0, N = L.size(); I != N; ++I) {
156 LL += L[I].size();
157 }
158 for (unsigned I = 0, N = R.size(); I != N; ++I) {
159 RL += R[I].Data.size();
160 }
161 if (LL != RL)
162 return false;
163 if (LL == 0 && RL == 0)
164 return true;
165
166 // Kick out empty parts, they confuse the algorithm below.
167 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
168 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
169
170 // Do it the hard way. At this point, both vectors must be non-empty.
171 llvm::StringRef LR = L[0], RR = R[0].Data;
172 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
Daniel Dunbar01ad0a72010-07-16 00:00:11 +0000173 (void) RN;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000174 for (;;) {
175 // Compare the current pieces.
176 if (LR.size() == RR.size()) {
177 // If they're the same length, it's pretty easy.
178 if (LR != RR)
179 return false;
180 // Both pieces are done, advance.
181 ++LI;
182 ++RI;
183 // If either string is done, they're both done, since they're the same
184 // length.
185 if (LI == LN) {
186 assert(RI == RN && "Strings not the same length after all?");
187 return true;
188 }
189 LR = L[LI];
190 RR = R[RI].Data;
191 } else if (LR.size() < RR.size()) {
192 // Right piece is longer.
193 if (!RR.startswith(LR))
194 return false;
195 ++LI;
196 assert(LI != LN && "Strings not the same length after all?");
197 RR = RR.substr(LR.size());
198 LR = L[LI];
199 } else {
200 // Left piece is longer.
201 if (!LR.startswith(RR))
202 return false;
203 ++RI;
204 assert(RI != RN && "Strings not the same length after all?");
205 LR = LR.substr(RR.size());
206 RR = R[RI].Data;
207 }
208 }
209}
210
211static std::pair<FileID, llvm::StringRef::size_type>
212FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
213 std::pair<FileID, llvm::StringRef::size_type> Res;
214 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
215 Res.second = Buffers[I].Data.find(MacroDef);
216 if (Res.second != llvm::StringRef::npos) {
217 Res.first = Buffers[I].BufferID;
218 break;
219 }
220 }
221 return Res;
222}
223
224bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000225 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000226 std::string &SuggestedPredefines) {
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000227 // We are in the context of an implicit include, so the predefines buffer will
228 // have a #include entry for the PCH file itself (as normalized by the
229 // preprocessor initialization). Find it and skip over it in the checking
230 // below.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000231 llvm::SmallString<256> PCHInclude;
232 PCHInclude += "#include \"";
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000233 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000234 PCHInclude += "\"\n";
235 std::pair<llvm::StringRef,llvm::StringRef> Split =
236 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
237 llvm::StringRef Left = Split.first, Right = Split.second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000238 if (Left == PP.getPredefines()) {
239 Error("Missing PCH include entry!");
240 return true;
241 }
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000242
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000243 // If the concatenation of all the PCH buffers is equal to the adjusted
244 // command line, we're done.
245 // We build a SmallVector of the command line here, because we'll eventually
246 // need to support an arbitrary amount of pieces anyway (when we have chained
247 // PCH reading).
248 llvm::SmallVector<llvm::StringRef, 2> CommandLine;
249 CommandLine.push_back(Left);
250 CommandLine.push_back(Right);
251 if (EqualConcatenations(CommandLine, Buffers))
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000252 return false;
253
254 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000255
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000256 // The predefines buffers are different. Determine what the differences are,
257 // and whether they require us to reject the PCH file.
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000258 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000259 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
260 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000261
262 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
263 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
264 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000265
Daniel Dunbar499baed2009-11-11 05:26:28 +0000266 // Sort both sets of predefined buffer lines, since we allow some extra
267 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000268 std::sort(CmdLineLines.begin(), CmdLineLines.end());
269 std::sort(PCHLines.begin(), PCHLines.end());
270
Daniel Dunbar499baed2009-11-11 05:26:28 +0000271 // Determine which predefines that were used to build the PCH file are missing
272 // from the command line.
273 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000274 std::set_difference(PCHLines.begin(), PCHLines.end(),
275 CmdLineLines.begin(), CmdLineLines.end(),
276 std::back_inserter(MissingPredefines));
277
278 bool MissingDefines = false;
279 bool ConflictingDefines = false;
280 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000281 llvm::StringRef Missing = MissingPredefines[I];
282 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000283 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
284 return true;
285 }
Mike Stump11289f42009-09-09 15:08:12 +0000286
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000287 // This is a macro definition. Determine the name of the macro we're
288 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000289 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000290 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000291 = Missing.find_first_of("( \n\r", StartOfMacroName);
292 assert(EndOfMacroName != std::string::npos &&
293 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000294 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000295
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000296 // Determine whether this macro was given a different definition on the
297 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000298 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000299 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000300 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000301 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
302 MacroDefStart);
303 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000304 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000305 // Different macro; we're done.
306 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000307 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000308 }
Mike Stump11289f42009-09-09 15:08:12 +0000309
310 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000311 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000312 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000313 (*ConflictPos)[MacroDefLen] != '(')
314 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000315
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000316 // We found a conflicting macro definition.
317 break;
318 }
Mike Stump11289f42009-09-09 15:08:12 +0000319
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000320 if (ConflictPos != CmdLineLines.end()) {
321 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
322 << MacroName;
323
324 // Show the definition of this macro within the PCH file.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000325 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
326 FindMacro(Buffers, Missing);
327 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
328 SourceLocation PCHMissingLoc =
329 SourceMgr.getLocForStartOfFile(MacroLoc.first)
330 .getFileLocWithOffset(MacroLoc.second);
Daniel Dunbar499baed2009-11-11 05:26:28 +0000331 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000332
333 ConflictingDefines = true;
334 continue;
335 }
Mike Stump11289f42009-09-09 15:08:12 +0000336
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000337 // If the macro doesn't conflict, then we'll just pick up the macro
338 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000339 if (ConflictingDefines)
340 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000341
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000342 if (!MissingDefines) {
343 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
344 MissingDefines = true;
345 }
346
347 // Show the definition of this macro within the PCH file.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000348 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
349 FindMacro(Buffers, Missing);
350 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
351 SourceLocation PCHMissingLoc =
352 SourceMgr.getLocForStartOfFile(MacroLoc.first)
353 .getFileLocWithOffset(MacroLoc.second);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000354 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
355 }
Mike Stump11289f42009-09-09 15:08:12 +0000356
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000357 if (ConflictingDefines)
358 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000360 // Determine what predefines were introduced based on command-line
361 // parameters that were not present when building the PCH
362 // file. Extra #defines are okay, so long as the identifiers being
363 // defined were not used within the precompiled header.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000364 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000365 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
366 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000367 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000368 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000369 llvm::StringRef &Extra = ExtraPredefines[I];
370 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000371 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
372 return true;
373 }
374
375 // This is an extra macro definition. Determine the name of the
376 // macro we're defining.
377 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000378 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000379 = Extra.find_first_of("( \n\r", StartOfMacroName);
380 assert(EndOfMacroName != std::string::npos &&
381 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000382 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000383
384 // Check whether this name was used somewhere in the PCH file. If
385 // so, defining it as a macro could change behavior, so we reject
386 // the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000387 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000388 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000389 return true;
390 }
391
392 // Add this definition to the suggested predefines buffer.
393 SuggestedPredefines += Extra;
394 SuggestedPredefines += '\n';
395 }
396
397 // If we get here, it's because the predefines buffer had compatible
398 // contents. Accept the PCH file.
399 return false;
400}
401
Douglas Gregor5712ebc2010-03-16 16:35:32 +0000402void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
403 unsigned ID) {
404 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
405 ++NumHeaderInfos;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000406}
407
408void PCHValidator::ReadCounter(unsigned Value) {
409 PP.setCounterValue(Value);
410}
411
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000412//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000413// PCH reader implementation
414//===----------------------------------------------------------------------===//
415
Mike Stump11289f42009-09-09 15:08:12 +0000416PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
417 const char *isysroot)
Sebastian Redl85b2a6a2010-07-14 23:45:08 +0000418 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
419 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
420 Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
Sebastian Redl34522812010-07-16 17:50:48 +0000421 Consumer(0), IdentifierTableData(0), IdentifierLookupTable(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000422 IdentifierOffsets(0),
423 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
424 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000425 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregor9507d462010-03-19 22:13:20 +0000426 NumPreallocatedPreprocessingEntities(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000427 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump11289f42009-09-09 15:08:12 +0000428 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000429 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000430 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000431 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000432 RelocatablePCH = false;
433}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000434
435PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000436 Diagnostic &Diags, const char *isysroot)
Sebastian Redl85b2a6a2010-07-14 23:45:08 +0000437 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
Sebastian Redl34522812010-07-16 17:50:48 +0000438 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000439 IdentifierTableData(0), IdentifierLookupTable(0),
440 IdentifierOffsets(0),
441 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
442 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000443 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregor9507d462010-03-19 22:13:20 +0000444 NumPreallocatedPreprocessingEntities(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000445 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump11289f42009-09-09 15:08:12 +0000446 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000447 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000448 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000449 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000450 RelocatablePCH = false;
451}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000452
Sebastian Redl34522812010-07-16 17:50:48 +0000453PCHReader::~PCHReader() {
454 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
455 delete Chain[e - i - 1];
456}
457
458PCHReader::PerFileData::PerFileData()
459 : StatCache(0)
460{}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000461
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000462
Douglas Gregora868bbd2009-04-21 22:25:48 +0000463namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000464class PCHMethodPoolLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000465 PCHReader &Reader;
466
467public:
468 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
469
470 typedef Selector external_key_type;
471 typedef external_key_type internal_key_type;
472
473 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000474
Douglas Gregorc78d3462009-04-24 21:10:55 +0000475 static bool EqualKey(const internal_key_type& a,
476 const internal_key_type& b) {
477 return a == b;
478 }
Mike Stump11289f42009-09-09 15:08:12 +0000479
Douglas Gregorc78d3462009-04-24 21:10:55 +0000480 static unsigned ComputeHash(Selector Sel) {
481 unsigned N = Sel.getNumArgs();
482 if (N == 0)
483 ++N;
484 unsigned R = 5381;
485 for (unsigned I = 0; I != N; ++I)
486 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000487 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000488 return R;
489 }
Mike Stump11289f42009-09-09 15:08:12 +0000490
Douglas Gregorc78d3462009-04-24 21:10:55 +0000491 // This hopefully will just get inlined and removed by the optimizer.
492 static const internal_key_type&
493 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000494
Douglas Gregorc78d3462009-04-24 21:10:55 +0000495 static std::pair<unsigned, unsigned>
496 ReadKeyDataLength(const unsigned char*& d) {
497 using namespace clang::io;
498 unsigned KeyLen = ReadUnalignedLE16(d);
499 unsigned DataLen = ReadUnalignedLE16(d);
500 return std::make_pair(KeyLen, DataLen);
501 }
Mike Stump11289f42009-09-09 15:08:12 +0000502
Douglas Gregor95c13f52009-04-25 17:48:32 +0000503 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000504 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000505 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000506 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000507 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000508 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
509 if (N == 0)
510 return SelTable.getNullarySelector(FirstII);
511 else if (N == 1)
512 return SelTable.getUnarySelector(FirstII);
513
514 llvm::SmallVector<IdentifierInfo *, 16> Args;
515 Args.push_back(FirstII);
516 for (unsigned I = 1; I != N; ++I)
517 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
518
Douglas Gregor038c3382009-05-22 22:45:36 +0000519 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000520 }
Mike Stump11289f42009-09-09 15:08:12 +0000521
Douglas Gregorc78d3462009-04-24 21:10:55 +0000522 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
523 using namespace clang::io;
524 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
525 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
526
527 data_type Result;
528
529 // Load instance methods
530 ObjCMethodList *Prev = 0;
531 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000532 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000533 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
534 if (!Result.first.Method) {
535 // This is the first method, which is the easy case.
536 Result.first.Method = Method;
537 Prev = &Result.first;
538 continue;
539 }
540
Ted Kremenekda4abf12010-02-11 00:53:01 +0000541 ObjCMethodList *Mem =
542 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
543 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000544 Prev = Prev->Next;
545 }
546
547 // Load factory methods
548 Prev = 0;
549 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000550 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000551 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
552 if (!Result.second.Method) {
553 // This is the first method, which is the easy case.
554 Result.second.Method = Method;
555 Prev = &Result.second;
556 continue;
557 }
558
Ted Kremenekda4abf12010-02-11 00:53:01 +0000559 ObjCMethodList *Mem =
560 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
561 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000562 Prev = Prev->Next;
563 }
564
565 return Result;
566 }
567};
Mike Stump11289f42009-09-09 15:08:12 +0000568
569} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000570
571/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000572typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000573 PCHMethodPoolLookupTable;
574
575namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000576class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000577 PCHReader &Reader;
578
579 // If we know the IdentifierInfo in advance, it is here and we will
580 // not build a new one. Used when deserializing information about an
581 // identifier that was constructed before the PCH file was read.
582 IdentifierInfo *KnownII;
583
584public:
585 typedef IdentifierInfo * data_type;
586
587 typedef const std::pair<const char*, unsigned> external_key_type;
588
589 typedef external_key_type internal_key_type;
590
Mike Stump11289f42009-09-09 15:08:12 +0000591 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregora868bbd2009-04-21 22:25:48 +0000592 : Reader(Reader), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000593
Douglas Gregora868bbd2009-04-21 22:25:48 +0000594 static bool EqualKey(const internal_key_type& a,
595 const internal_key_type& b) {
596 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
597 : false;
598 }
Mike Stump11289f42009-09-09 15:08:12 +0000599
Douglas Gregora868bbd2009-04-21 22:25:48 +0000600 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000601 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000602 }
Mike Stump11289f42009-09-09 15:08:12 +0000603
Douglas Gregora868bbd2009-04-21 22:25:48 +0000604 // This hopefully will just get inlined and removed by the optimizer.
605 static const internal_key_type&
606 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000607
Douglas Gregora868bbd2009-04-21 22:25:48 +0000608 static std::pair<unsigned, unsigned>
609 ReadKeyDataLength(const unsigned char*& d) {
610 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000611 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000612 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000613 return std::make_pair(KeyLen, DataLen);
614 }
Mike Stump11289f42009-09-09 15:08:12 +0000615
Douglas Gregora868bbd2009-04-21 22:25:48 +0000616 static std::pair<const char*, unsigned>
617 ReadKey(const unsigned char* d, unsigned n) {
618 assert(n >= 2 && d[n-1] == '\0');
619 return std::make_pair((const char*) d, n-1);
620 }
Mike Stump11289f42009-09-09 15:08:12 +0000621
622 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000623 const unsigned char* d,
624 unsigned DataLen) {
625 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000626 pch::IdentID ID = ReadUnalignedLE32(d);
627 bool IsInteresting = ID & 0x01;
628
629 // Wipe out the "is interesting" bit.
630 ID = ID >> 1;
631
632 if (!IsInteresting) {
633 // For unintersting identifiers, just build the IdentifierInfo
634 // and associate it with the persistent ID.
635 IdentifierInfo *II = KnownII;
636 if (!II)
637 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
638 k.first, k.first + k.second);
639 Reader.SetIdentifierInfo(ID, II);
640 return II;
641 }
642
Douglas Gregorb9256522009-04-28 21:32:13 +0000643 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000644 bool CPlusPlusOperatorKeyword = Bits & 0x01;
645 Bits >>= 1;
646 bool Poisoned = Bits & 0x01;
647 Bits >>= 1;
648 bool ExtensionToken = Bits & 0x01;
649 Bits >>= 1;
650 bool hasMacroDefinition = Bits & 0x01;
651 Bits >>= 1;
652 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
653 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000654
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000655 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000656 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000657
658 // Build the IdentifierInfo itself and link the identifier ID with
659 // the new IdentifierInfo.
660 IdentifierInfo *II = KnownII;
661 if (!II)
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000662 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
663 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000664 Reader.SetIdentifierInfo(ID, II);
665
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000666 // Set or check the various bits in the IdentifierInfo structure.
667 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000668 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000669 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000670 "Incorrect extension token flag");
671 (void)ExtensionToken;
672 II->setIsPoisoned(Poisoned);
673 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
674 "Incorrect C++ operator keyword flag");
675 (void)CPlusPlusOperatorKeyword;
676
Douglas Gregorc3366a52009-04-21 23:56:24 +0000677 // If this identifier is a macro, deserialize the macro
678 // definition.
679 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000680 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregorc3366a52009-04-21 23:56:24 +0000681 Reader.ReadMacroRecord(Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000682 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000683 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000684
685 // Read all of the declarations visible at global scope with this
686 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000687 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000688 if (DataLen > 0) {
689 llvm::SmallVector<uint32_t, 4> DeclIDs;
690 for (; DataLen > 0; DataLen -= 4)
691 DeclIDs.push_back(ReadUnalignedLE32(d));
692 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000693 }
Mike Stump11289f42009-09-09 15:08:12 +0000694
Douglas Gregora868bbd2009-04-21 22:25:48 +0000695 return II;
696 }
697};
Mike Stump11289f42009-09-09 15:08:12 +0000698
699} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000700
701/// \brief The on-disk hash table used to contain information about
702/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000703typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000704 PCHIdentifierLookupTable;
705
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000706void PCHReader::Error(const char *Msg) {
707 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000708}
709
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000710/// \brief Check the contents of the concatenation of all predefines buffers in
711/// the PCH chain against the contents of the predefines buffer of the current
712/// compiler invocation.
Douglas Gregor92863e42009-04-10 23:10:45 +0000713///
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000714/// The contents should be the same. If not, then some command-line option
715/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregor92863e42009-04-10 23:10:45 +0000716///
717/// \returns true if there was a mismatch (in which case the PCH file
718/// should be ignored), or false otherwise.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000719bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000720 if (Listener)
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000721 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000722 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000723 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000724 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000725}
726
Douglas Gregorc5046832009-04-27 18:38:38 +0000727//===----------------------------------------------------------------------===//
728// Source Manager Deserialization
729//===----------------------------------------------------------------------===//
730
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000731/// \brief Read the line table in the source manager block.
732/// \returns true if ther was an error.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000733bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000734 unsigned Idx = 0;
735 LineTableInfo &LineTable = SourceMgr.getLineTable();
736
737 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000738 std::map<int, int> FileIDs;
739 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000740 // Extract the file name
741 unsigned FilenameLen = Record[Idx++];
742 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
743 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000744 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000745 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000746 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000747 }
748
749 // Parse the line entries
750 std::vector<LineEntry> Entries;
751 while (Idx < Record.size()) {
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000752 int FID = Record[Idx++];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000753
754 // Extract the line entries
755 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000756 assert(NumEntries && "Numentries is 00000");
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000757 Entries.clear();
758 Entries.reserve(NumEntries);
759 for (unsigned I = 0; I != NumEntries; ++I) {
760 unsigned FileOffset = Record[Idx++];
761 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000762 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump11289f42009-09-09 15:08:12 +0000763 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000764 = (SrcMgr::CharacteristicKind)Record[Idx++];
765 unsigned IncludeOffset = Record[Idx++];
766 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
767 FileKind, IncludeOffset));
768 }
769 LineTable.AddEntry(FID, Entries);
770 }
771
772 return false;
773}
774
Douglas Gregorc5046832009-04-27 18:38:38 +0000775namespace {
776
Benjamin Kramer16634c22009-11-28 10:07:24 +0000777class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000778public:
779 const bool hasStat;
780 const ino_t ino;
781 const dev_t dev;
782 const mode_t mode;
783 const time_t mtime;
784 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000785
Douglas Gregorc5046832009-04-27 18:38:38 +0000786 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000787 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
788
Douglas Gregorc5046832009-04-27 18:38:38 +0000789 PCHStatData()
790 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
791};
792
Benjamin Kramer16634c22009-11-28 10:07:24 +0000793class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000794 public:
795 typedef const char *external_key_type;
796 typedef const char *internal_key_type;
797
798 typedef PCHStatData data_type;
799
800 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000801 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000802 }
803
804 static internal_key_type GetInternalKey(const char *path) { return path; }
805
806 static bool EqualKey(internal_key_type a, internal_key_type b) {
807 return strcmp(a, b) == 0;
808 }
809
810 static std::pair<unsigned, unsigned>
811 ReadKeyDataLength(const unsigned char*& d) {
812 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
813 unsigned DataLen = (unsigned) *d++;
814 return std::make_pair(KeyLen + 1, DataLen);
815 }
816
817 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
818 return (const char *)d;
819 }
820
821 static data_type ReadData(const internal_key_type, const unsigned char *d,
822 unsigned /*DataLen*/) {
823 using namespace clang::io;
824
825 if (*d++ == 1)
826 return data_type();
827
828 ino_t ino = (ino_t) ReadUnalignedLE32(d);
829 dev_t dev = (dev_t) ReadUnalignedLE32(d);
830 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000831 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000832 off_t size = (off_t) ReadUnalignedLE64(d);
833 return data_type(ino, dev, mode, mtime, size);
834 }
835};
836
837/// \brief stat() cache for precompiled headers.
838///
839/// This cache is very similar to the stat cache used by pretokenized
840/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000841class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000842 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
843 CacheTy *Cache;
844
845 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000846public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000847 PCHStatCache(const unsigned char *Buckets,
848 const unsigned char *Base,
849 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000850 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000851 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
852 Cache = CacheTy::Create(Buckets, Base);
853 }
854
855 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000856
Douglas Gregorc5046832009-04-27 18:38:38 +0000857 int stat(const char *path, struct stat *buf) {
858 // Do the lookup for the file's data in the PCH file.
859 CacheTy::iterator I = Cache->find(path);
860
861 // If we don't get a hit in the PCH file just forward to 'stat'.
862 if (I == Cache->end()) {
863 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000864 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000865 }
Mike Stump11289f42009-09-09 15:08:12 +0000866
Douglas Gregorc5046832009-04-27 18:38:38 +0000867 ++NumStatHits;
868 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000869
Douglas Gregorc5046832009-04-27 18:38:38 +0000870 if (!Data.hasStat)
871 return 1;
872
873 buf->st_ino = Data.ino;
874 buf->st_dev = Data.dev;
875 buf->st_mtime = Data.mtime;
876 buf->st_mode = Data.mode;
877 buf->st_size = Data.size;
878 return 0;
879 }
880};
881} // end anonymous namespace
882
883
Douglas Gregora7f71a92009-04-10 03:52:48 +0000884/// \brief Read the source manager block
Douglas Gregor92863e42009-04-10 23:10:45 +0000885PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000886 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000887
Sebastian Redl34522812010-07-16 17:50:48 +0000888 llvm::BitstreamCursor &SLocEntryCursor = Chain[0]->SLocEntryCursor;
889
Douglas Gregor258ae542009-04-27 06:38:32 +0000890 // Set the source-location entry cursor to the current position in
891 // the stream. This cursor will be used to read the contents of the
892 // source manager block initially, and then lazily read
893 // source-location entries as needed.
Sebastian Redl34522812010-07-16 17:50:48 +0000894 SLocEntryCursor = Chain[0]->Stream;
Douglas Gregor258ae542009-04-27 06:38:32 +0000895
896 // The stream itself is going to skip over the source manager block.
Sebastian Redl34522812010-07-16 17:50:48 +0000897 if (Chain[0]->Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000898 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000899 return Failure;
900 }
901
902 // Enter the source manager block.
903 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000904 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000905 return Failure;
906 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000907
Douglas Gregora7f71a92009-04-10 03:52:48 +0000908 RecordData Record;
909 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000910 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000911 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000912 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000913 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000914 return Failure;
915 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000916 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000917 }
Mike Stump11289f42009-09-09 15:08:12 +0000918
Douglas Gregora7f71a92009-04-10 03:52:48 +0000919 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
920 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000921 SLocEntryCursor.ReadSubBlockID();
922 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000923 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000924 return Failure;
925 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000926 continue;
927 }
Mike Stump11289f42009-09-09 15:08:12 +0000928
Douglas Gregora7f71a92009-04-10 03:52:48 +0000929 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000930 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000931 continue;
932 }
Mike Stump11289f42009-09-09 15:08:12 +0000933
Douglas Gregora7f71a92009-04-10 03:52:48 +0000934 // Read a record.
935 const char *BlobStart;
936 unsigned BlobLen;
937 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000938 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000939 default: // Default behavior: ignore.
940 break;
941
Chris Lattner184e65d2009-04-14 23:22:57 +0000942 case pch::SM_LINE_TABLE:
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000943 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000944 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000945 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000946
Douglas Gregor258ae542009-04-27 06:38:32 +0000947 case pch::SM_SLOC_FILE_ENTRY:
948 case pch::SM_SLOC_BUFFER_ENTRY:
949 case pch::SM_SLOC_INSTANTIATION_ENTRY:
950 // Once we hit one of the source location entries, we're done.
951 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000952 }
953 }
954}
955
Douglas Gregor258ae542009-04-27 06:38:32 +0000956/// \brief Read in the source location entry with the given ID.
957PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
958 if (ID == 0)
959 return Success;
960
961 if (ID > TotalNumSLocEntries) {
962 Error("source location entry ID out-of-range for PCH file");
963 return Failure;
964 }
965
Sebastian Redl34522812010-07-16 17:50:48 +0000966 llvm::BitstreamCursor &SLocEntryCursor = Chain[0]->SLocEntryCursor;
967
Douglas Gregor258ae542009-04-27 06:38:32 +0000968 ++NumSLocEntriesRead;
969 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
970 unsigned Code = SLocEntryCursor.ReadCode();
971 if (Code == llvm::bitc::END_BLOCK ||
972 Code == llvm::bitc::ENTER_SUBBLOCK ||
973 Code == llvm::bitc::DEFINE_ABBREV) {
974 Error("incorrectly-formatted source location entry in PCH file");
975 return Failure;
976 }
977
Douglas Gregor258ae542009-04-27 06:38:32 +0000978 RecordData Record;
979 const char *BlobStart;
980 unsigned BlobLen;
981 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
982 default:
983 Error("incorrectly-formatted source location entry in PCH file");
984 return Failure;
985
986 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000987 std::string Filename(BlobStart, BlobStart + BlobLen);
988 MaybeAddSystemRootToFilename(Filename);
989 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000990 if (File == 0) {
991 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000992 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000993 ErrorStr += "' referenced by PCH file";
994 Error(ErrorStr.c_str());
995 return Failure;
996 }
Mike Stump11289f42009-09-09 15:08:12 +0000997
Douglas Gregorb41ca8f2010-03-21 22:49:54 +0000998 if (Record.size() < 10) {
Ted Kremenekabb1ddd2010-03-18 21:23:05 +0000999 Error("source location entry is incorrect");
1000 return Failure;
1001 }
1002
Douglas Gregor08288f22010-04-09 15:54:22 +00001003 if ((off_t)Record[4] != File->getSize()
1004#if !defined(LLVM_ON_WIN32)
1005 // In our regression testing, the Windows file system seems to
1006 // have inconsistent modification times that sometimes
1007 // erroneously trigger this error-handling path.
1008 || (time_t)Record[5] != File->getModificationTime()
1009#endif
1010 ) {
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001011 Diag(diag::err_fe_pch_file_modified)
1012 << Filename;
1013 return Failure;
1014 }
1015
Douglas Gregor258ae542009-04-27 06:38:32 +00001016 FileID FID = SourceMgr.createFileID(File,
1017 SourceLocation::getFromRawEncoding(Record[1]),
1018 (SrcMgr::CharacteristicKind)Record[2],
1019 ID, Record[0]);
1020 if (Record[3])
1021 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1022 .setHasLineDirectives();
1023
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001024 // Reconstruct header-search information for this file.
1025 HeaderFileInfo HFI;
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001026 HFI.isImport = Record[6];
1027 HFI.DirInfo = Record[7];
1028 HFI.NumIncludes = Record[8];
1029 HFI.ControllingMacroID = Record[9];
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001030 if (Listener)
1031 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor258ae542009-04-27 06:38:32 +00001032 break;
1033 }
1034
1035 case pch::SM_SLOC_BUFFER_ENTRY: {
1036 const char *Name = BlobStart;
1037 unsigned Offset = Record[0];
1038 unsigned Code = SLocEntryCursor.ReadCode();
1039 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001040 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +00001041 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001042
1043 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1044 Error("PCH record has invalid code");
1045 return Failure;
1046 }
1047
Douglas Gregor258ae542009-04-27 06:38:32 +00001048 llvm::MemoryBuffer *Buffer
Chris Lattner58c79342010-04-05 22:42:27 +00001049 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1050 Name);
Douglas Gregor258ae542009-04-27 06:38:32 +00001051 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +00001052
Douglas Gregore6648fb2009-04-28 20:33:11 +00001053 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl75fbb3b2010-07-14 17:49:11 +00001054 PCHPredefinesBlock Block = {
1055 BufferID,
1056 llvm::StringRef(BlobStart, BlobLen - 1)
1057 };
1058 PCHPredefinesBuffers.push_back(Block);
Douglas Gregore6648fb2009-04-28 20:33:11 +00001059 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001060
1061 break;
1062 }
1063
1064 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +00001065 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +00001066 = SourceLocation::getFromRawEncoding(Record[1]);
1067 SourceMgr.createInstantiationLoc(SpellingLoc,
1068 SourceLocation::getFromRawEncoding(Record[2]),
1069 SourceLocation::getFromRawEncoding(Record[3]),
1070 Record[4],
1071 ID,
1072 Record[0]);
1073 break;
Mike Stump11289f42009-09-09 15:08:12 +00001074 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001075 }
1076
1077 return Success;
1078}
1079
Chris Lattnere78a6be2009-04-27 01:05:14 +00001080/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1081/// specified cursor. Read the abbreviations that are at the top of the block
1082/// and then leave the cursor pointing into the block.
1083bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1084 unsigned BlockID) {
1085 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001086 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001087 return Failure;
1088 }
Mike Stump11289f42009-09-09 15:08:12 +00001089
Chris Lattnere78a6be2009-04-27 01:05:14 +00001090 while (true) {
1091 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001092
Chris Lattnere78a6be2009-04-27 01:05:14 +00001093 // We expect all abbrevs to be at the start of the block.
1094 if (Code != llvm::bitc::DEFINE_ABBREV)
1095 return false;
1096 Cursor.ReadAbbrevRecord();
1097 }
1098}
1099
Douglas Gregorc3366a52009-04-21 23:56:24 +00001100void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001101 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +00001102
Sebastian Redl34522812010-07-16 17:50:48 +00001103 llvm::BitstreamCursor &Stream = Chain[0]->Stream;
1104
Douglas Gregorc3366a52009-04-21 23:56:24 +00001105 // Keep track of where we are in the stream, then jump back there
1106 // after reading this macro.
1107 SavedStreamPosition SavedPosition(Stream);
1108
1109 Stream.JumpToBit(Offset);
1110 RecordData Record;
1111 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1112 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001113
Douglas Gregorc3366a52009-04-21 23:56:24 +00001114 while (true) {
1115 unsigned Code = Stream.ReadCode();
1116 switch (Code) {
1117 case llvm::bitc::END_BLOCK:
1118 return;
1119
1120 case llvm::bitc::ENTER_SUBBLOCK:
1121 // No known subblocks, always skip them.
1122 Stream.ReadSubBlockID();
1123 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001124 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001125 return;
1126 }
1127 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001128
Douglas Gregorc3366a52009-04-21 23:56:24 +00001129 case llvm::bitc::DEFINE_ABBREV:
1130 Stream.ReadAbbrevRecord();
1131 continue;
1132 default: break;
1133 }
1134
1135 // Read a record.
1136 Record.clear();
1137 pch::PreprocessorRecordTypes RecType =
1138 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1139 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001140 case pch::PP_MACRO_OBJECT_LIKE:
1141 case pch::PP_MACRO_FUNCTION_LIKE: {
1142 // If we already have a macro, that means that we've hit the end
1143 // of the definition of the macro we were looking for. We're
1144 // done.
1145 if (Macro)
1146 return;
1147
1148 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1149 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001150 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001151 return;
1152 }
1153 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1154 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001155
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001156 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001157 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001158
Douglas Gregoraae92242010-03-19 21:51:54 +00001159 unsigned NextIndex = 3;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001160 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1161 // Decode function-like macro info.
1162 bool isC99VarArgs = Record[3];
1163 bool isGNUVarArgs = Record[4];
1164 MacroArgs.clear();
1165 unsigned NumArgs = Record[5];
Douglas Gregoraae92242010-03-19 21:51:54 +00001166 NextIndex = 6 + NumArgs;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001167 for (unsigned i = 0; i != NumArgs; ++i)
1168 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1169
1170 // Install function-like macro info.
1171 MI->setIsFunctionLike();
1172 if (isC99VarArgs) MI->setIsC99Varargs();
1173 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001174 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001175 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001176 }
1177
1178 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001179 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001180
1181 // Remember that we saw this macro last so that we add the tokens that
1182 // form its body to it.
1183 Macro = MI;
Douglas Gregoraae92242010-03-19 21:51:54 +00001184
1185 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1186 // We have a macro definition. Load it now.
1187 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1188 getMacroDefinition(Record[NextIndex]));
1189 }
1190
Douglas Gregorc3366a52009-04-21 23:56:24 +00001191 ++NumMacrosRead;
1192 break;
1193 }
Mike Stump11289f42009-09-09 15:08:12 +00001194
Douglas Gregorc3366a52009-04-21 23:56:24 +00001195 case pch::PP_TOKEN: {
1196 // If we see a TOKEN before a PP_MACRO_*, then the file is
1197 // erroneous, just pretend we didn't see this.
1198 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001199
Douglas Gregorc3366a52009-04-21 23:56:24 +00001200 Token Tok;
1201 Tok.startToken();
1202 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1203 Tok.setLength(Record[1]);
1204 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1205 Tok.setIdentifierInfo(II);
1206 Tok.setKind((tok::TokenKind)Record[3]);
1207 Tok.setFlag((Token::TokenFlags)Record[4]);
1208 Macro->AddTokenToBody(Tok);
1209 break;
1210 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001211
1212 case pch::PP_MACRO_INSTANTIATION: {
1213 // If we already have a macro, that means that we've hit the end
1214 // of the definition of the macro we were looking for. We're
1215 // done.
1216 if (Macro)
1217 return;
1218
1219 if (!PP->getPreprocessingRecord()) {
1220 Error("missing preprocessing record in PCH file");
1221 return;
1222 }
1223
1224 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1225 if (PPRec.getPreprocessedEntity(Record[0]))
1226 return;
1227
1228 MacroInstantiation *MI
1229 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1230 SourceRange(
1231 SourceLocation::getFromRawEncoding(Record[1]),
1232 SourceLocation::getFromRawEncoding(Record[2])),
1233 getMacroDefinition(Record[4]));
1234 PPRec.SetPreallocatedEntity(Record[0], MI);
1235 return;
1236 }
1237
1238 case pch::PP_MACRO_DEFINITION: {
1239 // If we already have a macro, that means that we've hit the end
1240 // of the definition of the macro we were looking for. We're
1241 // done.
1242 if (Macro)
1243 return;
1244
1245 if (!PP->getPreprocessingRecord()) {
1246 Error("missing preprocessing record in PCH file");
1247 return;
1248 }
1249
1250 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1251 if (PPRec.getPreprocessedEntity(Record[0]))
1252 return;
1253
1254 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1255 Error("out-of-bounds macro definition record");
1256 return;
1257 }
1258
1259 MacroDefinition *MD
1260 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1261 SourceLocation::getFromRawEncoding(Record[5]),
1262 SourceRange(
1263 SourceLocation::getFromRawEncoding(Record[2]),
1264 SourceLocation::getFromRawEncoding(Record[3])));
1265 PPRec.SetPreallocatedEntity(Record[0], MD);
1266 MacroDefinitionsLoaded[Record[1]] = MD;
1267 return;
1268 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001269 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001270 }
1271}
1272
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001273void PCHReader::ReadDefinedMacros() {
Sebastian Redl34522812010-07-16 17:50:48 +00001274 llvm::BitstreamCursor &MacroCursor = Chain[0]->MacroCursor;
1275
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001276 // If there was no preprocessor block, do nothing.
1277 if (!MacroCursor.getBitStreamReader())
1278 return;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001279
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001280 llvm::BitstreamCursor Cursor = MacroCursor;
1281 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1282 Error("malformed preprocessor block record in PCH file");
1283 return;
1284 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001285
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001286 RecordData Record;
1287 while (true) {
1288 unsigned Code = Cursor.ReadCode();
1289 if (Code == llvm::bitc::END_BLOCK) {
1290 if (Cursor.ReadBlockEnd())
1291 Error("error at end of preprocessor block in PCH file");
1292 return;
1293 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001294
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001295 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1296 // No known subblocks, always skip them.
1297 Cursor.ReadSubBlockID();
1298 if (Cursor.SkipBlock()) {
1299 Error("malformed block record in PCH file");
1300 return;
1301 }
1302 continue;
1303 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001304
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001305 if (Code == llvm::bitc::DEFINE_ABBREV) {
1306 Cursor.ReadAbbrevRecord();
1307 continue;
1308 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001309
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001310 // Read a record.
1311 const char *BlobStart;
1312 unsigned BlobLen;
1313 Record.clear();
1314 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1315 default: // Default behavior: ignore.
1316 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001317
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001318 case pch::PP_MACRO_OBJECT_LIKE:
1319 case pch::PP_MACRO_FUNCTION_LIKE:
Douglas Gregoraae92242010-03-19 21:51:54 +00001320 DecodeIdentifierInfo(Record[0]);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001321 break;
1322
1323 case pch::PP_TOKEN:
1324 // Ignore tokens.
1325 break;
Douglas Gregoraae92242010-03-19 21:51:54 +00001326
1327 case pch::PP_MACRO_INSTANTIATION:
1328 case pch::PP_MACRO_DEFINITION:
1329 // Read the macro record.
1330 ReadMacroRecord(Cursor.GetCurrentBitNo());
1331 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001332 }
1333 }
1334}
1335
Douglas Gregoraae92242010-03-19 21:51:54 +00001336MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1337 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1338 return 0;
1339
1340 if (!MacroDefinitionsLoaded[ID])
1341 ReadMacroRecord(MacroDefinitionOffsets[ID]);
1342
1343 return MacroDefinitionsLoaded[ID];
1344}
1345
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001346/// \brief If we are loading a relocatable PCH file, and the filename is
1347/// not an absolute path, add the system root to the beginning of the file
1348/// name.
1349void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1350 // If this is not a relocatable PCH file, there's nothing to do.
1351 if (!RelocatablePCH)
1352 return;
Mike Stump11289f42009-09-09 15:08:12 +00001353
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001354 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001355 return;
1356
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001357 if (isysroot == 0) {
1358 // If no system root was given, default to '/'
1359 Filename.insert(Filename.begin(), '/');
1360 return;
1361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001363 unsigned Length = strlen(isysroot);
1364 if (isysroot[Length - 1] != '/')
1365 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001366
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001367 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1368}
1369
Mike Stump11289f42009-09-09 15:08:12 +00001370PCHReader::PCHReadResult
Sebastian Redl2abc0382010-07-16 20:41:52 +00001371PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl34522812010-07-16 17:50:48 +00001372 llvm::BitstreamCursor &Stream = F.Stream;
1373
Douglas Gregor55abb232009-04-10 20:39:37 +00001374 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001375 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001376 return Failure;
1377 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001378
1379 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001380 RecordData Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001381 while (!Stream.AtEndOfStream()) {
1382 unsigned Code = Stream.ReadCode();
1383 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001384 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001385 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001386 return Failure;
1387 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001388
Douglas Gregor55abb232009-04-10 20:39:37 +00001389 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001390 }
1391
1392 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1393 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001394 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001395 // We lazily load the decls block, but we want to set up the
1396 // DeclsCursor cursor to point into it. Clone our current bitcode
1397 // cursor to it, enter the block and read the abbrevs in that block.
1398 // With the main cursor, we just skip over it.
Sebastian Redl34522812010-07-16 17:50:48 +00001399 F.DeclsCursor = Stream;
Chris Lattnere78a6be2009-04-27 01:05:14 +00001400 if (Stream.SkipBlock() || // Skip with the main cursor.
1401 // Read the abbrevs.
Sebastian Redl34522812010-07-16 17:50:48 +00001402 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001403 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001404 return Failure;
1405 }
1406 break;
Mike Stump11289f42009-09-09 15:08:12 +00001407
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001408 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl34522812010-07-16 17:50:48 +00001409 F.MacroCursor = Stream;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001410 if (PP)
1411 PP->setExternalSource(this);
1412
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001413 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001414 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001415 return Failure;
1416 }
1417 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001418
Douglas Gregora7f71a92009-04-10 03:52:48 +00001419 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001420 switch (ReadSourceManagerBlock()) {
1421 case Success:
1422 break;
1423
1424 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001425 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001426 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001427
1428 case IgnorePCH:
1429 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001430 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001431 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001432 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001433 continue;
1434 }
1435
1436 if (Code == llvm::bitc::DEFINE_ABBREV) {
1437 Stream.ReadAbbrevRecord();
1438 continue;
1439 }
1440
1441 // Read and process a record.
1442 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001443 const char *BlobStart = 0;
1444 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001445 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001446 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001447 default: // Default behavior: ignore.
1448 break;
1449
1450 case pch::TYPE_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001451 if (!TypesLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001452 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001453 return Failure;
1454 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001455 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001456 TypesLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001457 break;
1458
1459 case pch::DECL_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001460 if (!DeclsLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001461 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001462 return Failure;
1463 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001464 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001465 DeclsLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001466 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001467
1468 case pch::LANGUAGE_OPTIONS:
1469 if (ParseLanguageOptions(Record))
1470 return IgnorePCH;
1471 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001472
Douglas Gregor7b71e632009-04-27 22:23:34 +00001473 case pch::METADATA: {
1474 if (Record[0] != pch::VERSION_MAJOR) {
1475 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1476 : diag::warn_pch_version_too_new);
1477 return IgnorePCH;
1478 }
1479
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001480 RelocatablePCH = Record[4];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001481 if (Listener) {
1482 std::string TargetTriple(BlobStart, BlobLen);
1483 if (Listener->ReadTargetTriple(TargetTriple))
1484 return IgnorePCH;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001485 }
1486 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001487 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001488
1489 case pch::IDENTIFIER_TABLE:
Douglas Gregora868bbd2009-04-21 22:25:48 +00001490 IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001491 if (Record[0]) {
Mike Stump11289f42009-09-09 15:08:12 +00001492 IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001493 = PCHIdentifierLookupTable::Create(
Douglas Gregora868bbd2009-04-21 22:25:48 +00001494 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001495 (const unsigned char *)IdentifierTableData,
Douglas Gregora868bbd2009-04-21 22:25:48 +00001496 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001497 if (PP)
1498 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001499 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001500 break;
1501
1502 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001503 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001504 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001505 return Failure;
1506 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001507 IdentifierOffsets = (const uint32_t *)BlobStart;
1508 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001509 if (PP)
1510 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001511 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001512
1513 case pch::EXTERNAL_DEFINITIONS:
1514 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001515 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001516 return Failure;
1517 }
1518 ExternalDefinitions.swap(Record);
1519 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001520
Douglas Gregor652d82a2009-04-18 05:55:16 +00001521 case pch::SPECIAL_TYPES:
1522 SpecialTypes.swap(Record);
1523 break;
1524
Douglas Gregor08f01292009-04-17 22:13:46 +00001525 case pch::STATISTICS:
1526 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001527 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001528 TotalLexicalDeclContexts = Record[2];
1529 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001530 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001531
Douglas Gregord4df8652009-04-22 22:02:47 +00001532 case pch::TENTATIVE_DEFINITIONS:
1533 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001534 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001535 return Failure;
1536 }
1537 TentativeDefinitions.swap(Record);
1538 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001539
Tanya Lattner90073802010-02-12 00:07:30 +00001540 case pch::UNUSED_STATIC_FUNCS:
1541 if (!UnusedStaticFuncs.empty()) {
1542 Error("duplicate UNUSED_STATIC_FUNCS record in PCH file");
1543 return Failure;
1544 }
1545 UnusedStaticFuncs.swap(Record);
1546 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001547
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001548 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1549 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001550 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001551 return Failure;
1552 }
1553 LocallyScopedExternalDecls.swap(Record);
1554 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001555
Douglas Gregor95c13f52009-04-25 17:48:32 +00001556 case pch::SELECTOR_OFFSETS:
1557 SelectorOffsets = (const uint32_t *)BlobStart;
1558 TotalNumSelectors = Record[0];
1559 SelectorsLoaded.resize(TotalNumSelectors);
1560 break;
1561
Douglas Gregorc78d3462009-04-24 21:10:55 +00001562 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001563 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1564 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001565 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001566 = PCHMethodPoolLookupTable::Create(
1567 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001568 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001569 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001570 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001571 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001572
1573 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001574 if (!Record.empty() && Listener)
1575 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001576 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001577
1578 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001579 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001580 TotalNumSLocEntries = Record[0];
Douglas Gregord54f3a12009-10-05 21:07:28 +00001581 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001582 break;
1583
1584 case pch::SOURCE_LOCATION_PRELOADS:
1585 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1586 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1587 if (Result != Success)
1588 return Result;
1589 }
1590 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001591
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001592 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001593 PCHStatCache *MyStatCache =
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001594 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1595 (const unsigned char *)BlobStart,
1596 NumStatHits, NumStatMisses);
1597 FileMgr.addStatCache(MyStatCache);
Sebastian Redl34522812010-07-16 17:50:48 +00001598 F.StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001599 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001600 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001601
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001602 case pch::EXT_VECTOR_DECLS:
1603 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001604 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001605 return Failure;
1606 }
1607 ExtVectorDecls.swap(Record);
1608 break;
1609
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00001610 case pch::VTABLE_USES:
1611 if (!VTableUses.empty()) {
1612 Error("duplicate VTABLE_USES record in PCH file");
1613 return Failure;
1614 }
1615 VTableUses.swap(Record);
1616 break;
1617
1618 case pch::DYNAMIC_CLASSES:
1619 if (!DynamicClasses.empty()) {
1620 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1621 return Failure;
1622 }
1623 DynamicClasses.swap(Record);
1624 break;
1625
Douglas Gregor45fe0362009-05-12 01:31:05 +00001626 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001627 ActualOriginalFileName.assign(BlobStart, BlobLen);
1628 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001629 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001630 break;
Mike Stump11289f42009-09-09 15:08:12 +00001631
Ted Kremenek17437132010-01-22 20:59:36 +00001632 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek8bd09292010-02-12 23:31:14 +00001633 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek2377a0e2010-01-22 20:55:35 +00001634 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Ted Kremenek8bd09292010-02-12 23:31:14 +00001635 if (llvm::StringRef(CurBranch) != PCHBranch) {
Douglas Gregord54f3a12009-10-05 21:07:28 +00001636 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1637 return IgnorePCH;
1638 }
1639 break;
1640 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001641
1642 case pch::MACRO_DEFINITION_OFFSETS:
1643 MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1644 if (PP) {
1645 if (!PP->getPreprocessingRecord())
1646 PP->createPreprocessingRecord();
1647 PP->getPreprocessingRecord()->SetExternalSource(*this, Record[0]);
1648 } else {
1649 NumPreallocatedPreprocessingEntities = Record[0];
1650 }
1651
1652 MacroDefinitionsLoaded.resize(Record[1]);
1653 break;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001654 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001655 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001656 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001657 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001658}
1659
Douglas Gregor92863e42009-04-10 23:10:45 +00001660PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redl2abc0382010-07-16 20:41:52 +00001661 switch(OpenPCH(FileName)) {
1662 case Failure: return Failure;
1663 case IgnorePCH: return IgnorePCH;
1664 case Success: break;
1665 }
Sebastian Redl34522812010-07-16 17:50:48 +00001666 PerFileData &F = *Chain.back();
Sebastian Redl34522812010-07-16 17:50:48 +00001667 llvm::BitstreamCursor &Stream = F.Stream;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001668
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001669 while (!Stream.AtEndOfStream()) {
1670 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001671
Douglas Gregor92863e42009-04-10 23:10:45 +00001672 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001673 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001674 return Failure;
1675 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001676
1677 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001678
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001679 // We only know the PCH subblock ID.
1680 switch (BlockID) {
1681 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001682 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001683 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001684 return Failure;
1685 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001686 break;
1687 case pch::PCH_BLOCK_ID:
Sebastian Redl2abc0382010-07-16 20:41:52 +00001688 switch (ReadPCHBlock(F)) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001689 case Success:
1690 break;
1691
1692 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001693 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001694
1695 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001696 // FIXME: We could consider reading through to the end of this
1697 // PCH block, skipping subblocks, to see if there are other
1698 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001699
1700 // Clear out any preallocated source location entries, so that
1701 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001702 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001703
1704 // Remove the stat cache.
Sebastian Redl34522812010-07-16 17:50:48 +00001705 if (F.StatCache)
1706 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001707
Douglas Gregor92863e42009-04-10 23:10:45 +00001708 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001709 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001710 break;
1711 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001712 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001713 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001714 return Failure;
1715 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001716 break;
1717 }
Mike Stump11289f42009-09-09 15:08:12 +00001718 }
1719
Sebastian Redl2abc0382010-07-16 20:41:52 +00001720 // Check the predefines buffers.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +00001721 if (CheckPredefinesBuffers())
Douglas Gregore6648fb2009-04-28 20:33:11 +00001722 return IgnorePCH;
Mike Stump11289f42009-09-09 15:08:12 +00001723
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001724 if (PP) {
Zhongxing Xu3f51f412009-07-18 09:26:51 +00001725 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001726 // PCH file is read, so there may be some identifiers that were
1727 // loaded into the IdentifierTable before we intercepted the
1728 // creation of identifiers. Iterate through the list of known
1729 // identifiers and determine whether we have to establish
1730 // preprocessor definitions or top-level identifier declaration
1731 // chains for those identifiers.
1732 //
1733 // We copy the IdentifierInfo pointers to a small vector first,
1734 // since de-serializing declarations or macro definitions can add
1735 // new entries into the identifier table, invalidating the
1736 // iterators.
1737 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1738 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1739 IdEnd = PP->getIdentifierTable().end();
1740 Id != IdEnd; ++Id)
1741 Identifiers.push_back(Id->second);
Mike Stump11289f42009-09-09 15:08:12 +00001742 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001743 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1744 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1745 IdentifierInfo *II = Identifiers[I];
1746 // Look in the on-disk hash table for an entry for
1747 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001748 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001749 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1750 if (Pos == IdTable->end())
1751 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001752
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001753 // Dereferencing the iterator has the effect of populating the
1754 // IdentifierInfo node with the various declarations it needs.
1755 (void)*Pos;
1756 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001757 }
1758
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001759 if (Context)
1760 InitializeContext(*Context);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001761
Douglas Gregora868bbd2009-04-21 22:25:48 +00001762 return Success;
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001763}
1764
Sebastian Redl2abc0382010-07-16 20:41:52 +00001765PCHReader::PCHReadResult PCHReader::OpenPCH(llvm::StringRef FileName) {
1766 Chain.push_back(new PerFileData());
1767 PerFileData &F = *Chain.back();
1768
1769 // Set the PCH file name.
1770 F.FileName = FileName;
1771
1772 // Open the PCH file.
1773 //
1774 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1775 std::string ErrStr;
1776 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1777 if (!F.Buffer) {
1778 Error(ErrStr.c_str());
1779 return IgnorePCH;
1780 }
1781
1782 // Initialize the stream
1783 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1784 (const unsigned char *)F.Buffer->getBufferEnd());
1785 llvm::BitstreamCursor &Stream = F.Stream;
1786 Stream.init(F.StreamFile);
1787
1788 // Sniff for the signature.
1789 if (Stream.Read(8) != 'C' ||
1790 Stream.Read(8) != 'P' ||
1791 Stream.Read(8) != 'C' ||
1792 Stream.Read(8) != 'H') {
1793 Diag(diag::err_not_a_pch_file) << FileName;
1794 return Failure;
1795 }
1796 return Success;
1797}
1798
1799PCHReader::PCHReadResult PCHReader::ReadChainedPCH(llvm::StringRef FileName) {
1800 switch(OpenPCH(FileName)) {
1801 case Failure: return Failure;
1802 case IgnorePCH: return IgnorePCH;
1803 case Success: break;
1804 }
1805 return Success;
1806}
1807
Douglas Gregoraae92242010-03-19 21:51:54 +00001808void PCHReader::setPreprocessor(Preprocessor &pp) {
1809 PP = &pp;
1810
1811 if (NumPreallocatedPreprocessingEntities) {
1812 if (!PP->getPreprocessingRecord())
1813 PP->createPreprocessingRecord();
1814 PP->getPreprocessingRecord()->SetExternalSource(*this,
1815 NumPreallocatedPreprocessingEntities);
1816 NumPreallocatedPreprocessingEntities = 0;
1817 }
1818}
1819
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001820void PCHReader::InitializeContext(ASTContext &Ctx) {
1821 Context = &Ctx;
1822 assert(Context && "Passed null context!");
1823
1824 assert(PP && "Forgot to set Preprocessor ?");
1825 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1826 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001827 PP->setExternalSource(this);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001828
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001829 // Load the translation unit declaration
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00001830 GetTranslationUnitDecl();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001831
1832 // Load the special types.
1833 Context->setBuiltinVaListType(
1834 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1835 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1836 Context->setObjCIdType(GetType(Id));
1837 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1838 Context->setObjCSelType(GetType(Sel));
1839 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1840 Context->setObjCProtoType(GetType(Proto));
1841 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1842 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001843
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001844 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1845 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001846 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001847 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1848 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001849 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1850 QualType FileType = GetType(File);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001851 if (FileType.isNull()) {
1852 Error("FILE type is NULL");
1853 return;
1854 }
John McCall9dd450b2009-09-21 23:43:11 +00001855 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001856 Context->setFILEDecl(Typedef->getDecl());
1857 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001858 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001859 if (!Tag) {
1860 Error("Invalid FILE type in PCH file");
1861 return;
1862 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00001863 Context->setFILEDecl(Tag->getDecl());
1864 }
1865 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001866 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1867 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001868 if (Jmp_bufType.isNull()) {
1869 Error("jmp_bug type is NULL");
1870 return;
1871 }
John McCall9dd450b2009-09-21 23:43:11 +00001872 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001873 Context->setjmp_bufDecl(Typedef->getDecl());
1874 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001875 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001876 if (!Tag) {
1877 Error("Invalid jmp_bug type in PCH file");
1878 return;
1879 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001880 Context->setjmp_bufDecl(Tag->getDecl());
1881 }
1882 }
1883 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1884 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001885 if (Sigjmp_bufType.isNull()) {
1886 Error("sigjmp_buf type is NULL");
1887 return;
1888 }
John McCall9dd450b2009-09-21 23:43:11 +00001889 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001890 Context->setsigjmp_bufDecl(Typedef->getDecl());
1891 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001892 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001893 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1894 Context->setsigjmp_bufDecl(Tag->getDecl());
1895 }
1896 }
Mike Stump11289f42009-09-09 15:08:12 +00001897 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001898 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1899 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001900 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001901 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1902 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpd0153282009-10-20 02:12:22 +00001903 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1904 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00001905 if (unsigned String
1906 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1907 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001908 if (unsigned ObjCSelRedef
1909 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
1910 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
1911 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
1912 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +00001913
1914 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
1915 Context->setInt128Installed();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001916}
1917
Douglas Gregor45fe0362009-05-12 01:31:05 +00001918/// \brief Retrieve the name of the original source file name
1919/// directly from the PCH file, without actually loading the PCH
1920/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00001921std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1922 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00001923 // Open the PCH file.
1924 std::string ErrStr;
1925 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1926 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1927 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001928 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001929 return std::string();
1930 }
1931
1932 // Initialize the stream
1933 llvm::BitstreamReader StreamFile;
1934 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001935 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001936 (const unsigned char *)Buffer->getBufferEnd());
1937 Stream.init(StreamFile);
1938
1939 // Sniff for the signature.
1940 if (Stream.Read(8) != 'C' ||
1941 Stream.Read(8) != 'P' ||
1942 Stream.Read(8) != 'C' ||
1943 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001944 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001945 return std::string();
1946 }
1947
1948 RecordData Record;
1949 while (!Stream.AtEndOfStream()) {
1950 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001951
Douglas Gregor45fe0362009-05-12 01:31:05 +00001952 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1953 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001954
Douglas Gregor45fe0362009-05-12 01:31:05 +00001955 // We only know the PCH subblock ID.
1956 switch (BlockID) {
1957 case pch::PCH_BLOCK_ID:
1958 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001959 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001960 return std::string();
1961 }
1962 break;
Mike Stump11289f42009-09-09 15:08:12 +00001963
Douglas Gregor45fe0362009-05-12 01:31:05 +00001964 default:
1965 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001966 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001967 return std::string();
1968 }
1969 break;
1970 }
1971 continue;
1972 }
1973
1974 if (Code == llvm::bitc::END_BLOCK) {
1975 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001976 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001977 return std::string();
1978 }
1979 continue;
1980 }
1981
1982 if (Code == llvm::bitc::DEFINE_ABBREV) {
1983 Stream.ReadAbbrevRecord();
1984 continue;
1985 }
1986
1987 Record.clear();
1988 const char *BlobStart = 0;
1989 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001990 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00001991 == pch::ORIGINAL_FILE_NAME)
1992 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00001993 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00001994
1995 return std::string();
1996}
1997
Douglas Gregor55abb232009-04-10 20:39:37 +00001998/// \brief Parse the record that corresponds to a LangOptions data
1999/// structure.
2000///
2001/// This routine compares the language options used to generate the
2002/// PCH file against the language options set for the current
2003/// compilation. For each option, we classify differences between the
2004/// two compiler states as either "benign" or "important". Benign
2005/// differences don't matter, and we accept them without complaint
2006/// (and without modifying the language options). Differences between
2007/// the states for important options cause the PCH file to be
2008/// unusable, so we emit a warning and return true to indicate that
2009/// there was an error.
2010///
2011/// \returns true if the PCH file is unacceptable, false otherwise.
2012bool PCHReader::ParseLanguageOptions(
2013 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002014 if (Listener) {
2015 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00002016
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002017 #define PARSE_LANGOPT(Option) \
2018 LangOpts.Option = Record[Idx]; \
2019 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00002020
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002021 unsigned Idx = 0;
2022 PARSE_LANGOPT(Trigraphs);
2023 PARSE_LANGOPT(BCPLComment);
2024 PARSE_LANGOPT(DollarIdents);
2025 PARSE_LANGOPT(AsmPreprocessor);
2026 PARSE_LANGOPT(GNUMode);
Chandler Carruthe03aa552010-04-17 20:17:31 +00002027 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002028 PARSE_LANGOPT(ImplicitInt);
2029 PARSE_LANGOPT(Digraphs);
2030 PARSE_LANGOPT(HexFloats);
2031 PARSE_LANGOPT(C99);
2032 PARSE_LANGOPT(Microsoft);
2033 PARSE_LANGOPT(CPlusPlus);
2034 PARSE_LANGOPT(CPlusPlus0x);
2035 PARSE_LANGOPT(CXXOperatorNames);
2036 PARSE_LANGOPT(ObjC1);
2037 PARSE_LANGOPT(ObjC2);
2038 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00002039 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian62c56022010-04-22 21:01:59 +00002040 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002041 PARSE_LANGOPT(PascalStrings);
2042 PARSE_LANGOPT(WritableStrings);
2043 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00002044 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002045 PARSE_LANGOPT(Exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +00002046 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002047 PARSE_LANGOPT(NeXTRuntime);
2048 PARSE_LANGOPT(Freestanding);
2049 PARSE_LANGOPT(NoBuiltin);
2050 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00002051 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002052 PARSE_LANGOPT(Blocks);
2053 PARSE_LANGOPT(EmitAllDecls);
2054 PARSE_LANGOPT(MathErrno);
Chris Lattner51924e512010-06-26 21:25:03 +00002055 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2056 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002057 PARSE_LANGOPT(HeinousExtensions);
2058 PARSE_LANGOPT(Optimize);
2059 PARSE_LANGOPT(OptimizeSize);
2060 PARSE_LANGOPT(Static);
2061 PARSE_LANGOPT(PICLevel);
2062 PARSE_LANGOPT(GNUInline);
2063 PARSE_LANGOPT(NoInline);
2064 PARSE_LANGOPT(AccessControl);
2065 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00002066 PARSE_LANGOPT(ShortWChar);
Chris Lattner51924e512010-06-26 21:25:03 +00002067 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2068 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbar143021e2009-09-21 04:16:19 +00002069 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattner51924e512010-06-26 21:25:03 +00002070 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002071 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00002072 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00002073 PARSE_LANGOPT(CatchUndefined);
2074 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002075 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00002076
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002077 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00002078 }
Douglas Gregor55abb232009-04-10 20:39:37 +00002079
2080 return false;
2081}
2082
Douglas Gregoraae92242010-03-19 21:51:54 +00002083void PCHReader::ReadPreprocessedEntities() {
2084 ReadDefinedMacros();
2085}
2086
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002087/// \brief Read and return the type at the given offset.
2088///
2089/// This routine actually reads the record corresponding to the type
2090/// at the given offset in the bitstream. It is a helper routine for
2091/// GetType, which deals with reading type IDs.
2092QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Sebastian Redl34522812010-07-16 17:50:48 +00002093 llvm::BitstreamCursor &DeclsCursor = Chain[0]->DeclsCursor;
2094
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002095 // Keep track of where we are in the stream, then jump back there
2096 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00002097 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002098
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002099 ReadingKindTracker ReadingKind(Read_Type, *this);
2100
Douglas Gregor1342e842009-07-06 18:54:52 +00002101 // Note that we are loading a type record.
2102 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002103
Douglas Gregor12bfa382009-10-17 00:13:19 +00002104 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002105 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00002106 unsigned Code = DeclsCursor.ReadCode();
2107 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00002108 case pch::TYPE_EXT_QUAL: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002109 if (Record.size() != 2) {
2110 Error("Incorrect encoding of extended qualifier type");
2111 return QualType();
2112 }
Douglas Gregor455b8f42009-04-15 22:00:08 +00002113 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00002114 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2115 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00002116 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002117
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002118 case pch::TYPE_COMPLEX: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002119 if (Record.size() != 1) {
2120 Error("Incorrect encoding of complex type");
2121 return QualType();
2122 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002123 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002124 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002125 }
2126
2127 case pch::TYPE_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002128 if (Record.size() != 1) {
2129 Error("Incorrect encoding of pointer type");
2130 return QualType();
2131 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002132 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002133 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002134 }
2135
2136 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002137 if (Record.size() != 1) {
2138 Error("Incorrect encoding of block pointer type");
2139 return QualType();
2140 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002141 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002142 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002143 }
2144
2145 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002146 if (Record.size() != 1) {
2147 Error("Incorrect encoding of lvalue reference type");
2148 return QualType();
2149 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002150 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002151 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002152 }
2153
2154 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002155 if (Record.size() != 1) {
2156 Error("Incorrect encoding of rvalue reference type");
2157 return QualType();
2158 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002159 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002160 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002161 }
2162
2163 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidisee776bc2010-07-02 11:55:15 +00002164 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002165 Error("Incorrect encoding of member pointer type");
2166 return QualType();
2167 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002168 QualType PointeeType = GetType(Record[0]);
2169 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002170 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002171 }
2172
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002173 case pch::TYPE_CONSTANT_ARRAY: {
2174 QualType ElementType = GetType(Record[0]);
2175 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2176 unsigned IndexTypeQuals = Record[2];
2177 unsigned Idx = 3;
2178 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00002179 return Context->getConstantArrayType(ElementType, Size,
2180 ASM, IndexTypeQuals);
2181 }
2182
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002183 case pch::TYPE_INCOMPLETE_ARRAY: {
2184 QualType ElementType = GetType(Record[0]);
2185 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2186 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00002187 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002188 }
2189
2190 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002191 QualType ElementType = GetType(Record[0]);
2192 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2193 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00002194 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2195 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002196 return Context->getVariableArrayType(ElementType, ReadExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00002197 ASM, IndexTypeQuals,
2198 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002199 }
2200
2201 case pch::TYPE_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002202 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002203 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002204 return QualType();
2205 }
2206
2207 QualType ElementType = GetType(Record[0]);
2208 unsigned NumElements = Record[1];
Chris Lattner37141f42010-06-23 06:00:24 +00002209 unsigned AltiVecSpec = Record[2];
2210 return Context->getVectorType(ElementType, NumElements,
2211 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002212 }
2213
2214 case pch::TYPE_EXT_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002215 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002216 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002217 return QualType();
2218 }
2219
2220 QualType ElementType = GetType(Record[0]);
2221 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00002222 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002223 }
2224
2225 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002226 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002227 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002228 return QualType();
2229 }
2230 QualType ResultType = GetType(Record[0]);
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002231 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002232 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002233 }
2234
2235 case pch::TYPE_FUNCTION_PROTO: {
2236 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00002237 bool NoReturn = Record[1];
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002238 unsigned RegParm = Record[2];
2239 CallingConv CallConv = (CallingConv)Record[3];
2240 unsigned Idx = 4;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002241 unsigned NumParams = Record[Idx++];
2242 llvm::SmallVector<QualType, 16> ParamTypes;
2243 for (unsigned I = 0; I != NumParams; ++I)
2244 ParamTypes.push_back(GetType(Record[Idx++]));
2245 bool isVariadic = Record[Idx++];
2246 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002247 bool hasExceptionSpec = Record[Idx++];
2248 bool hasAnyExceptionSpec = Record[Idx++];
2249 unsigned NumExceptions = Record[Idx++];
2250 llvm::SmallVector<QualType, 2> Exceptions;
2251 for (unsigned I = 0; I != NumExceptions; ++I)
2252 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00002253 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002254 isVariadic, Quals, hasExceptionSpec,
2255 hasAnyExceptionSpec, NumExceptions,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002256 Exceptions.data(),
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002257 FunctionType::ExtInfo(NoReturn, RegParm,
2258 CallConv));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002259 }
2260
John McCallb96ec562009-12-04 22:46:56 +00002261 case pch::TYPE_UNRESOLVED_USING:
2262 return Context->getTypeDeclType(
2263 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2264
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002265 case pch::TYPE_TYPEDEF: {
2266 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002267 Error("incorrect encoding of typedef type");
2268 return QualType();
2269 }
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002270 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2271 QualType Canonical = GetType(Record[1]);
2272 return Context->getTypedefType(Decl, Canonical);
2273 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002274
2275 case pch::TYPE_TYPEOF_EXPR:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002276 return Context->getTypeOfExprType(ReadExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002277
2278 case pch::TYPE_TYPEOF: {
2279 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002280 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002281 return QualType();
2282 }
2283 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002284 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002285 }
Mike Stump11289f42009-09-09 15:08:12 +00002286
Anders Carlsson81df7b82009-06-24 19:06:50 +00002287 case pch::TYPE_DECLTYPE:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002288 return Context->getDecltypeType(ReadExpr());
Anders Carlsson81df7b82009-06-24 19:06:50 +00002289
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002290 case pch::TYPE_RECORD: {
2291 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002292 Error("incorrect encoding of record type");
2293 return QualType();
2294 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002295 bool IsDependent = Record[0];
2296 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2297 T->Dependent = IsDependent;
2298 return T;
2299 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002300
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002301 case pch::TYPE_ENUM: {
2302 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002303 Error("incorrect encoding of enum type");
2304 return QualType();
2305 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002306 bool IsDependent = Record[0];
2307 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2308 T->Dependent = IsDependent;
2309 return T;
2310 }
Douglas Gregor1daeb692009-04-13 18:14:40 +00002311
John McCallfcc33b02009-09-05 00:15:47 +00002312 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002313 unsigned Idx = 0;
2314 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2315 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2316 QualType NamedType = GetType(Record[Idx++]);
2317 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCallfcc33b02009-09-05 00:15:47 +00002318 }
2319
Steve Naroffc277ad12009-07-18 15:33:26 +00002320 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00002321 unsigned Idx = 0;
2322 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002323 return Context->getObjCInterfaceType(ItfD);
2324 }
2325
2326 case pch::TYPE_OBJC_OBJECT: {
2327 unsigned Idx = 0;
2328 QualType Base = GetType(Record[Idx++]);
Chris Lattner587cbe12009-04-22 06:45:28 +00002329 unsigned NumProtos = Record[Idx++];
2330 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2331 for (unsigned I = 0; I != NumProtos; ++I)
2332 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCall8b07ec22010-05-15 11:32:37 +00002333 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00002334 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002335
Steve Narofffb4330f2009-06-17 22:40:22 +00002336 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00002337 unsigned Idx = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002338 QualType Pointee = GetType(Record[Idx++]);
2339 return Context->getObjCObjectPointerType(Pointee);
Chris Lattner6e054af2009-04-22 06:40:03 +00002340 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00002341
John McCallcebee162009-10-18 09:09:24 +00002342 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2343 unsigned Idx = 0;
2344 QualType Parm = GetType(Record[Idx++]);
2345 QualType Replacement = GetType(Record[Idx++]);
2346 return
2347 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2348 Replacement);
2349 }
John McCalle78aac42010-03-10 03:28:59 +00002350
2351 case pch::TYPE_INJECTED_CLASS_NAME: {
2352 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2353 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidisdab33c52010-07-02 11:55:20 +00002354 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2355 // for PCH reading, too much interdependencies.
2356 return
2357 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCalle78aac42010-03-10 03:28:59 +00002358 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002359
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002360 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2361 unsigned Idx = 0;
2362 unsigned Depth = Record[Idx++];
2363 unsigned Index = Record[Idx++];
2364 bool Pack = Record[Idx++];
2365 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2366 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2367 }
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002368
2369 case pch::TYPE_DEPENDENT_NAME: {
2370 unsigned Idx = 0;
2371 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2372 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2373 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidise9290952010-07-02 11:55:24 +00002374 QualType Canon = GetType(Record[Idx++]);
2375 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002376 }
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002377
2378 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2379 unsigned Idx = 0;
2380 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2381 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2382 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2383 unsigned NumArgs = Record[Idx++];
2384 llvm::SmallVector<TemplateArgument, 8> Args;
2385 Args.reserve(NumArgs);
2386 while (NumArgs--)
2387 Args.push_back(ReadTemplateArgument(Record, Idx));
2388 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2389 Args.size(), Args.data());
2390 }
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00002391
2392 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2393 unsigned Idx = 0;
2394
2395 // ArrayType
2396 QualType ElementType = GetType(Record[Idx++]);
2397 ArrayType::ArraySizeModifier ASM
2398 = (ArrayType::ArraySizeModifier)Record[Idx++];
2399 unsigned IndexTypeQuals = Record[Idx++];
2400
2401 // DependentSizedArrayType
2402 Expr *NumElts = ReadExpr();
2403 SourceRange Brackets = ReadSourceRange(Record, Idx);
2404
2405 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2406 IndexTypeQuals, Brackets);
2407 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002408
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002409 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2410 unsigned Idx = 0;
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002411 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002412 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002413 llvm::SmallVector<TemplateArgument, 8> Args;
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00002414 ReadTemplateArgumentList(Args, Record, Idx);
2415 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002416 QualType T;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002417 if (Canon.isNull())
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002418 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2419 Args.size());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002420 else
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002421 T = Context->getTemplateSpecializationType(Name, Args.data(),
2422 Args.size(), Canon);
2423 T->Dependent = IsDependent;
2424 return T;
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002425 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002426 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002427 // Suppress a GCC warning
2428 return QualType();
2429}
2430
John McCall8f115c62009-10-16 21:56:05 +00002431namespace {
2432
2433class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2434 PCHReader &Reader;
2435 const PCHReader::RecordData &Record;
2436 unsigned &Idx;
2437
2438public:
2439 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2440 unsigned &Idx)
2441 : Reader(Reader), Record(Record), Idx(Idx) { }
2442
John McCall17001972009-10-18 01:05:36 +00002443 // We want compile-time assurance that we've enumerated all of
2444 // these, so unfortunately we have to declare them first, then
2445 // define them out-of-line.
2446#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002447#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002448 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002449#include "clang/AST/TypeLocNodes.def"
2450
John McCall17001972009-10-18 01:05:36 +00002451 void VisitFunctionTypeLoc(FunctionTypeLoc);
2452 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002453};
2454
2455}
2456
John McCall17001972009-10-18 01:05:36 +00002457void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002458 // nothing to do
2459}
John McCall17001972009-10-18 01:05:36 +00002460void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +00002461 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2462 if (TL.needsExtraLocalData()) {
2463 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2464 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2465 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2466 TL.setModeAttr(Record[Idx++]);
2467 }
John McCall8f115c62009-10-16 21:56:05 +00002468}
John McCall17001972009-10-18 01:05:36 +00002469void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2470 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002471}
John McCall17001972009-10-18 01:05:36 +00002472void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2473 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002474}
John McCall17001972009-10-18 01:05:36 +00002475void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2476 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002477}
John McCall17001972009-10-18 01:05:36 +00002478void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2479 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002480}
John McCall17001972009-10-18 01:05:36 +00002481void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2482 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002483}
John McCall17001972009-10-18 01:05:36 +00002484void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2485 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002486}
John McCall17001972009-10-18 01:05:36 +00002487void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2488 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2489 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002490 if (Record[Idx++])
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002491 TL.setSizeExpr(Reader.ReadExpr());
Douglas Gregor12bfa382009-10-17 00:13:19 +00002492 else
John McCall17001972009-10-18 01:05:36 +00002493 TL.setSizeExpr(0);
2494}
2495void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2496 VisitArrayTypeLoc(TL);
2497}
2498void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2499 VisitArrayTypeLoc(TL);
2500}
2501void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2502 VisitArrayTypeLoc(TL);
2503}
2504void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2505 DependentSizedArrayTypeLoc TL) {
2506 VisitArrayTypeLoc(TL);
2507}
2508void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2509 DependentSizedExtVectorTypeLoc TL) {
2510 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2511}
2512void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2513 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2514}
2515void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2516 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2517}
2518void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2519 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2520 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2521 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002522 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002523 }
2524}
2525void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2526 VisitFunctionTypeLoc(TL);
2527}
2528void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2529 VisitFunctionTypeLoc(TL);
2530}
John McCallb96ec562009-12-04 22:46:56 +00002531void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2532 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2533}
John McCall17001972009-10-18 01:05:36 +00002534void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2535 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2536}
2537void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002538 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2539 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2540 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002541}
2542void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002543 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2544 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2545 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2546 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002547}
2548void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2549 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2550}
2551void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2552 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2553}
2554void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2555 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2556}
John McCall17001972009-10-18 01:05:36 +00002557void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2558 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2559}
John McCallcebee162009-10-18 09:09:24 +00002560void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2561 SubstTemplateTypeParmTypeLoc TL) {
2562 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2563}
John McCall17001972009-10-18 01:05:36 +00002564void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2565 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002566 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2567 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2568 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2569 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2570 TL.setArgLocInfo(i,
2571 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2572 Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002573}
Abramo Bagnara6150c882010-05-11 21:36:43 +00002574void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002575 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2576 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002577}
John McCalle78aac42010-03-10 03:28:59 +00002578void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2579 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2580}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002581void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002582 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2583 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002584 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2585}
John McCallc392f372010-06-11 00:33:02 +00002586void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2587 DependentTemplateSpecializationTypeLoc TL) {
2588 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2589 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2590 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2591 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2592 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2593 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2594 TL.setArgLocInfo(I,
2595 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
2596 Record, Idx));
2597}
John McCall17001972009-10-18 01:05:36 +00002598void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2599 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002600}
2601void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2602 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall17001972009-10-18 01:05:36 +00002603 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2604 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2605 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2606 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002607}
John McCallfc93cf92009-10-22 22:37:11 +00002608void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2609 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallfc93cf92009-10-22 22:37:11 +00002610}
John McCall8f115c62009-10-16 21:56:05 +00002611
John McCallbcd03502009-12-07 02:54:59 +00002612TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002613 unsigned &Idx) {
2614 QualType InfoTy = GetType(Record[Idx++]);
2615 if (InfoTy.isNull())
2616 return 0;
2617
John McCallbcd03502009-12-07 02:54:59 +00002618 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCall8f115c62009-10-16 21:56:05 +00002619 TypeLocReader TLR(*this, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002620 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002621 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002622 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002623}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002624
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002625QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002626 unsigned FastQuals = ID & Qualifiers::FastMask;
2627 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002628
2629 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2630 QualType T;
2631 switch ((pch::PredefinedTypeIDs)Index) {
2632 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002633 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2634 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002635
2636 case pch::PREDEF_TYPE_CHAR_U_ID:
2637 case pch::PREDEF_TYPE_CHAR_S_ID:
2638 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002639 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002640 break;
2641
Chris Lattner8575daa2009-04-27 21:45:14 +00002642 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2643 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2644 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2645 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2646 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002647 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002648 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2649 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2650 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2651 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2652 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2653 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002654 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002655 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2656 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2657 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2658 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2659 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002660 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002661 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2662 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002663 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2664 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002665 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002666 }
2667
2668 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002669 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002670 }
2671
2672 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002673 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl409183f2010-07-14 20:26:45 +00002674 if (TypesLoaded[Index].isNull()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002675 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Sebastian Redl409183f2010-07-14 20:26:45 +00002676 TypesLoaded[Index]->setFromPCH();
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002677 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002678 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2679 TypesLoaded[Index]);
Sebastian Redl409183f2010-07-14 20:26:45 +00002680 }
Mike Stump11289f42009-09-09 15:08:12 +00002681
John McCall8ccfcb52009-09-24 19:53:00 +00002682 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002683}
2684
John McCall0ad16662009-10-29 08:12:44 +00002685TemplateArgumentLocInfo
2686PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2687 const RecordData &Record,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002688 unsigned &Index) {
John McCall0ad16662009-10-29 08:12:44 +00002689 switch (Kind) {
2690 case TemplateArgument::Expression:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002691 return ReadExpr();
John McCall0ad16662009-10-29 08:12:44 +00002692 case TemplateArgument::Type:
John McCallbcd03502009-12-07 02:54:59 +00002693 return GetTypeSourceInfo(Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002694 case TemplateArgument::Template: {
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002695 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2696 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2697 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002698 }
John McCall0ad16662009-10-29 08:12:44 +00002699 case TemplateArgument::Null:
2700 case TemplateArgument::Integral:
2701 case TemplateArgument::Declaration:
2702 case TemplateArgument::Pack:
2703 return TemplateArgumentLocInfo();
2704 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002705 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002706 return TemplateArgumentLocInfo();
2707}
2708
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002709TemplateArgumentLoc
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002710PCHReader::ReadTemplateArgumentLoc(const RecordData &Record, unsigned &Index) {
2711 TemplateArgument Arg = ReadTemplateArgument(Record, Index);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002712
2713 if (Arg.getKind() == TemplateArgument::Expression) {
2714 if (Record[Index++]) // bool InfoHasSameExpr.
2715 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2716 }
2717 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002718 Record, Index));
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00002719}
2720
John McCall75b960e2010-06-01 09:23:16 +00002721Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2722 return GetDecl(ID);
2723}
2724
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002725TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002726 if (!DeclsLoaded[0]) {
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002727 ReadDeclRecord(DeclOffsets[0], 0);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002728 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002729 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002730 }
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002731
2732 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2733}
2734
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002735Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002736 if (ID == 0)
2737 return 0;
2738
Douglas Gregor745ed142009-04-25 18:35:21 +00002739 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002740 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002741 return 0;
2742 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002743
Douglas Gregor745ed142009-04-25 18:35:21 +00002744 unsigned Index = ID - 1;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002745 if (!DeclsLoaded[Index]) {
Douglas Gregor745ed142009-04-25 18:35:21 +00002746 ReadDeclRecord(DeclOffsets[Index], Index);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002747 if (DeserializationListener)
2748 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2749 }
Douglas Gregor745ed142009-04-25 18:35:21 +00002750
2751 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002752}
2753
Chris Lattner9c28af02009-04-27 05:46:25 +00002754/// \brief Resolve the offset of a statement into a statement.
2755///
2756/// This operation will read a new statement from the external
2757/// source each time it is called, and is meant to be used via a
2758/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall75b960e2010-06-01 09:23:16 +00002759Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002760 // Since we know tha this statement is part of a decl, make sure to use the
2761 // decl cursor to read it.
Sebastian Redl34522812010-07-16 17:50:48 +00002762 Chain[0]->DeclsCursor.JumpToBit(Offset);
2763 return ReadStmtFromStream(Chain[0]->DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002764}
2765
John McCall75b960e2010-06-01 09:23:16 +00002766bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2767 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002768 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002769 "DeclContext has no lexical decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002770
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002771 uint64_t Offset = DeclContextOffsets[DC].first;
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002772 if (Offset == 0) {
2773 Error("DeclContext has no lexical decls in storage");
2774 return true;
2775 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002776
Sebastian Redl34522812010-07-16 17:50:48 +00002777 llvm::BitstreamCursor &DeclsCursor = Chain[0]->DeclsCursor;
2778
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002779 // Keep track of where we are in the stream, then jump back there
2780 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002781 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002782
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002783 // Load the record containing all of the declarations lexically in
2784 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002785 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002786 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002787 unsigned Code = DeclsCursor.ReadCode();
2788 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002789 if (RecCode != pch::DECL_CONTEXT_LEXICAL) {
2790 Error("Expected lexical block");
2791 return true;
2792 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002793
2794 // Load all of the declaration IDs
John McCall75b960e2010-06-01 09:23:16 +00002795 for (RecordData::iterator I = Record.begin(), E = Record.end(); I != E; ++I)
2796 Decls.push_back(GetDecl(*I));
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002797 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002798 return false;
2799}
2800
John McCall75b960e2010-06-01 09:23:16 +00002801DeclContext::lookup_result
2802PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2803 DeclarationName Name) {
Mike Stump11289f42009-09-09 15:08:12 +00002804 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002805 "DeclContext has no visible decls in storage");
2806 uint64_t Offset = DeclContextOffsets[DC].second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002807 if (Offset == 0) {
2808 Error("DeclContext has no visible decls in storage");
John McCall75b960e2010-06-01 09:23:16 +00002809 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2810 DeclContext::lookup_iterator());
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002811 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002812
Sebastian Redl34522812010-07-16 17:50:48 +00002813 llvm::BitstreamCursor &DeclsCursor = Chain[0]->DeclsCursor;
2814
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002815 // Keep track of where we are in the stream, then jump back there
2816 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002817 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002818
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002819 // Load the record containing all of the declarations visible in
2820 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002821 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002822 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002823 unsigned Code = DeclsCursor.ReadCode();
2824 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002825 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2826 Error("Expected visible block");
John McCall75b960e2010-06-01 09:23:16 +00002827 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2828 DeclContext::lookup_iterator());
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002829 }
2830
John McCall75b960e2010-06-01 09:23:16 +00002831 llvm::SmallVector<VisibleDeclaration, 64> Decls;
2832 if (Record.empty()) {
2833 SetExternalVisibleDecls(DC, Decls);
2834 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2835 DeclContext::lookup_iterator());
2836 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002837
2838 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002839 while (Idx < Record.size()) {
2840 Decls.push_back(VisibleDeclaration());
2841 Decls.back().Name = ReadDeclarationName(Record, Idx);
2842
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002843 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002844 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002845 LoadedDecls.reserve(Size);
2846 for (unsigned I = 0; I < Size; ++I)
2847 LoadedDecls.push_back(Record[Idx++]);
2848 }
2849
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002850 ++NumVisibleDeclContextsRead;
John McCall75b960e2010-06-01 09:23:16 +00002851
2852 SetExternalVisibleDecls(DC, Decls);
2853 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002854}
2855
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00002856void PCHReader::PassInterestingDeclsToConsumer() {
2857 assert(Consumer);
2858 while (!InterestingDecls.empty()) {
2859 DeclGroupRef DG(InterestingDecls.front());
2860 InterestingDecls.pop_front();
2861 Consumer->HandleTopLevelDecl(DG);
2862 }
2863}
2864
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002865void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002866 this->Consumer = Consumer;
2867
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002868 if (!Consumer)
2869 return;
2870
2871 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00002872 // Force deserialization of this decl, which will cause it to be queued for
2873 // passing to the consumer.
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002874 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002875 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002876
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00002877 PassInterestingDeclsToConsumer();
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002878}
2879
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002880void PCHReader::PrintStats() {
2881 std::fprintf(stderr, "*** PCH Statistics:\n");
2882
Mike Stump11289f42009-09-09 15:08:12 +00002883 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002884 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00002885 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00002886 unsigned NumDeclsLoaded
2887 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2888 (Decl *)0);
2889 unsigned NumIdentifiersLoaded
2890 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2891 IdentifiersLoaded.end(),
2892 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002893 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002894 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2895 SelectorsLoaded.end(),
2896 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002897
Douglas Gregorc5046832009-04-27 18:38:38 +00002898 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2899 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002900 if (TotalNumSLocEntries)
2901 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2902 NumSLocEntriesRead, TotalNumSLocEntries,
2903 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002904 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002905 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002906 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2907 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2908 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002909 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002910 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2911 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002912 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002913 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002914 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2915 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002916 if (TotalNumSelectors)
2917 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2918 NumSelectorsLoaded, TotalNumSelectors,
2919 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2920 if (TotalNumStatements)
2921 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2922 NumStatementsRead, TotalNumStatements,
2923 ((float)NumStatementsRead/TotalNumStatements * 100));
2924 if (TotalNumMacros)
2925 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2926 NumMacrosRead, TotalNumMacros,
2927 ((float)NumMacrosRead/TotalNumMacros * 100));
2928 if (TotalLexicalDeclContexts)
2929 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2930 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2931 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2932 * 100));
2933 if (TotalVisibleDeclContexts)
2934 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2935 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2936 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2937 * 100));
2938 if (TotalSelectorsInMethodPool) {
2939 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2940 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2941 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2942 * 100));
2943 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2944 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002945 std::fprintf(stderr, "\n");
2946}
2947
Douglas Gregora868bbd2009-04-21 22:25:48 +00002948void PCHReader::InitializeSema(Sema &S) {
2949 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002950 S.ExternalSource = this;
2951
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002952 // Makes sure any declarations that were deserialized "too early"
2953 // still get added to the identifier's declaration chains.
2954 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2955 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2956 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002957 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002958 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002959
2960 // If there were any tentative definitions, deserialize them and add
Sebastian Redl35351a92010-01-31 22:27:38 +00002961 // them to Sema's list of tentative definitions.
Douglas Gregord4df8652009-04-22 22:02:47 +00002962 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2963 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redl35351a92010-01-31 22:27:38 +00002964 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregord4df8652009-04-22 22:02:47 +00002965 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00002966
Tanya Lattner90073802010-02-12 00:07:30 +00002967 // If there were any unused static functions, deserialize them and add to
2968 // Sema's list of unused static functions.
2969 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
2970 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
2971 SemaObj->UnusedStaticFuncs.push_back(FD);
2972 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002973
2974 // If there were any locally-scoped external declarations,
2975 // deserialize them and add them to Sema's table of locally-scoped
2976 // external declarations.
2977 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2978 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2979 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2980 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002981
2982 // If there were any ext_vector type declarations, deserialize them
2983 // and add them to Sema's vector of such declarations.
2984 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2985 SemaObj->ExtVectorDecls.push_back(
2986 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00002987
2988 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
2989 // Can we cut them down before writing them ?
2990
2991 // If there were any VTable uses, deserialize the information and add it
2992 // to Sema's vector and map of VTable uses.
2993 unsigned Idx = 0;
2994 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
2995 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
2996 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
2997 bool DefinitionRequired = VTableUses[Idx++];
2998 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
2999 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3000 }
3001
3002 // If there were any dynamic classes declarations, deserialize them
3003 // and add them to Sema's vector of such declarations.
3004 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3005 SemaObj->DynamicClasses.push_back(
3006 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003007}
3008
3009IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
3010 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00003011 PCHIdentifierLookupTable *IdTable
Douglas Gregora868bbd2009-04-21 22:25:48 +00003012 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
3013 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3014 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3015 if (Pos == IdTable->end())
3016 return 0;
3017
3018 // Dereferencing the iterator has the effect of building the
3019 // IdentifierInfo node and populating it with the various
3020 // declarations it needs.
3021 return *Pos;
3022}
3023
Mike Stump11289f42009-09-09 15:08:12 +00003024std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00003025PCHReader::ReadMethodPool(Selector Sel) {
3026 if (!MethodPoolLookupTable)
3027 return std::pair<ObjCMethodList, ObjCMethodList>();
3028
3029 // Try to find this selector within our on-disk hash table.
3030 PCHMethodPoolLookupTable *PoolTable
3031 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
3032 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00003033 if (Pos == PoolTable->end()) {
3034 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003035 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00003036 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003037
Douglas Gregor95c13f52009-04-25 17:48:32 +00003038 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003039 return *Pos;
3040}
3041
Douglas Gregor0e149972009-04-25 19:10:14 +00003042void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00003043 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003044 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00003045 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003046}
3047
Douglas Gregor1342e842009-07-06 18:54:52 +00003048/// \brief Set the globally-visible declarations associated with the given
3049/// identifier.
3050///
3051/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00003052/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00003053/// them.
3054///
3055/// \param II an IdentifierInfo that refers to one or more globally-visible
3056/// declarations.
3057///
3058/// \param DeclIDs the set of declaration IDs with the name @p II that are
3059/// visible at global scope.
3060///
3061/// \param Nonrecursive should be true to indicate that the caller knows that
3062/// this call is non-recursive, and therefore the globally-visible declarations
3063/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00003064void
3065PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00003066 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3067 bool Nonrecursive) {
3068 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
3069 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3070 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3071 PII.II = II;
3072 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3073 PII.DeclIDs.push_back(DeclIDs[I]);
3074 return;
3075 }
Mike Stump11289f42009-09-09 15:08:12 +00003076
Douglas Gregor1342e842009-07-06 18:54:52 +00003077 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3078 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3079 if (SemaObj) {
3080 // Introduce this declaration into the translation-unit scope
3081 // and add it to the declaration chain for this identifier, so
3082 // that (unqualified) name lookup will find it.
3083 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3084 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3085 } else {
3086 // Queue this declaration so that it will be added to the
3087 // translation unit scope and identifier's declaration chain
3088 // once a Sema object is known.
3089 PreloadedDecls.push_back(D);
3090 }
3091 }
3092}
3093
Chris Lattnerc523d8e2009-04-11 21:15:38 +00003094IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003095 if (ID == 0)
3096 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003097
Douglas Gregor0e149972009-04-25 19:10:14 +00003098 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003099 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003100 return 0;
3101 }
Mike Stump11289f42009-09-09 15:08:12 +00003102
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003103 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00003104 if (!IdentifiersLoaded[ID - 1]) {
3105 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor95272492009-04-25 21:21:38 +00003106 const char *Str = IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00003107
Douglas Gregorab4df582009-04-28 20:01:51 +00003108 // All of the strings in the PCH file are preceded by a 16-bit
3109 // length. Extract that 16-bit length to avoid having to execute
3110 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00003111 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3112 // unsigned integers. This is important to avoid integer overflow when
3113 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00003114 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00003115 unsigned StrLen = (((unsigned) StrLenPtr[0])
3116 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00003117 IdentifiersLoaded[ID - 1]
Kovarththanan Rajaratnama3b09592010-03-12 10:32:27 +00003118 = &PP->getIdentifierTable().get(Str, StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003119 }
Mike Stump11289f42009-09-09 15:08:12 +00003120
Douglas Gregor0e149972009-04-25 19:10:14 +00003121 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003122}
3123
Douglas Gregor258ae542009-04-27 06:38:32 +00003124void PCHReader::ReadSLocEntry(unsigned ID) {
3125 ReadSLocEntryRecord(ID);
3126}
3127
Steve Naroff2ddea052009-04-23 10:39:46 +00003128Selector PCHReader::DecodeSelector(unsigned ID) {
3129 if (ID == 0)
3130 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00003131
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003132 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00003133 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00003134
3135 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003136 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00003137 return Selector();
3138 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003139
3140 unsigned Index = ID - 1;
3141 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
3142 // Load this selector from the selector table.
3143 // FIXME: endianness portability issues with SelectorOffsets table
3144 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003145 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00003146 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
3147 }
3148
3149 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00003150}
3151
John McCall75b960e2010-06-01 09:23:16 +00003152Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003153 return DecodeSelector(ID);
3154}
3155
John McCall75b960e2010-06-01 09:23:16 +00003156uint32_t PCHReader::GetNumExternalSelectors() {
Douglas Gregord720daf2010-04-06 17:30:22 +00003157 return TotalNumSelectors + 1;
3158}
3159
Mike Stump11289f42009-09-09 15:08:12 +00003160DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003161PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3162 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3163 switch (Kind) {
3164 case DeclarationName::Identifier:
3165 return DeclarationName(GetIdentifierInfo(Record, Idx));
3166
3167 case DeclarationName::ObjCZeroArgSelector:
3168 case DeclarationName::ObjCOneArgSelector:
3169 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00003170 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003171
3172 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003173 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003174 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003175
3176 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003177 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003178 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003179
3180 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003181 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003182 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003183
3184 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003185 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003186 (OverloadedOperatorKind)Record[Idx++]);
3187
Alexis Hunt3d221f22009-11-29 07:34:05 +00003188 case DeclarationName::CXXLiteralOperatorName:
3189 return Context->DeclarationNames.getCXXLiteralOperatorName(
3190 GetIdentifierInfo(Record, Idx));
3191
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003192 case DeclarationName::CXXUsingDirective:
3193 return DeclarationName::getUsingDirectiveName();
3194 }
3195
3196 // Required to silence GCC warning
3197 return DeclarationName();
3198}
Douglas Gregor55abb232009-04-10 20:39:37 +00003199
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003200TemplateName
3201PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3202 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3203 switch (Kind) {
3204 case TemplateName::Template:
3205 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3206
3207 case TemplateName::OverloadedTemplate: {
3208 unsigned size = Record[Idx++];
3209 UnresolvedSet<8> Decls;
3210 while (size--)
3211 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3212
3213 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3214 }
3215
3216 case TemplateName::QualifiedTemplate: {
3217 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3218 bool hasTemplKeyword = Record[Idx++];
3219 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3220 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3221 }
3222
3223 case TemplateName::DependentTemplate: {
3224 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3225 if (Record[Idx++]) // isIdentifier
3226 return Context->getDependentTemplateName(NNS,
3227 GetIdentifierInfo(Record, Idx));
3228 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00003229 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003230 }
3231 }
3232
3233 assert(0 && "Unhandled template name kind!");
3234 return TemplateName();
3235}
3236
3237TemplateArgument
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00003238PCHReader::ReadTemplateArgument(const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003239 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3240 case TemplateArgument::Null:
3241 return TemplateArgument();
3242 case TemplateArgument::Type:
3243 return TemplateArgument(GetType(Record[Idx++]));
3244 case TemplateArgument::Declaration:
3245 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidis0b0369a2010-06-28 09:31:34 +00003246 case TemplateArgument::Integral: {
3247 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3248 QualType T = GetType(Record[Idx++]);
3249 return TemplateArgument(Value, T);
3250 }
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003251 case TemplateArgument::Template:
3252 return TemplateArgument(ReadTemplateName(Record, Idx));
3253 case TemplateArgument::Expression:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00003254 return TemplateArgument(ReadExpr());
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003255 case TemplateArgument::Pack: {
3256 unsigned NumArgs = Record[Idx++];
3257 llvm::SmallVector<TemplateArgument, 8> Args;
3258 Args.reserve(NumArgs);
3259 while (NumArgs--)
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00003260 Args.push_back(ReadTemplateArgument(Record, Idx));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003261 TemplateArgument TemplArg;
3262 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3263 return TemplArg;
3264 }
3265 }
3266
3267 assert(0 && "Unhandled template argument kind!");
3268 return TemplateArgument();
3269}
3270
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003271TemplateParameterList *
3272PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3273 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3274 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3275 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3276
3277 unsigned NumParams = Record[Idx++];
3278 llvm::SmallVector<NamedDecl *, 16> Params;
3279 Params.reserve(NumParams);
3280 while (NumParams--)
3281 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3282
3283 TemplateParameterList* TemplateParams =
3284 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3285 Params.data(), Params.size(), RAngleLoc);
3286 return TemplateParams;
3287}
3288
3289void
3290PCHReader::
3291ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
3292 const RecordData &Record, unsigned &Idx) {
3293 unsigned NumTemplateArgs = Record[Idx++];
3294 TemplArgs.reserve(NumTemplateArgs);
3295 while (NumTemplateArgs--)
3296 TemplArgs.push_back(ReadTemplateArgument(Record, Idx));
3297}
3298
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00003299/// \brief Read a UnresolvedSet structure.
3300void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3301 const RecordData &Record, unsigned &Idx) {
3302 unsigned NumDecls = Record[Idx++];
3303 while (NumDecls--) {
3304 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3305 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3306 Set.addDecl(D, AS);
3307 }
3308}
3309
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003310CXXBaseSpecifier
3311PCHReader::ReadCXXBaseSpecifier(const RecordData &Record, unsigned &Idx) {
3312 bool isVirtual = static_cast<bool>(Record[Idx++]);
3313 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3314 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
3315 QualType T = GetType(Record[Idx++]);
3316 SourceRange Range = ReadSourceRange(Record, Idx);
3317 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, T);
3318}
3319
Chris Lattnerca025db2010-05-07 21:43:38 +00003320NestedNameSpecifier *
3321PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3322 unsigned N = Record[Idx++];
3323 NestedNameSpecifier *NNS = 0, *Prev = 0;
3324 for (unsigned I = 0; I != N; ++I) {
3325 NestedNameSpecifier::SpecifierKind Kind
3326 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3327 switch (Kind) {
3328 case NestedNameSpecifier::Identifier: {
3329 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3330 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3331 break;
3332 }
3333
3334 case NestedNameSpecifier::Namespace: {
3335 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3336 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3337 break;
3338 }
3339
3340 case NestedNameSpecifier::TypeSpec:
3341 case NestedNameSpecifier::TypeSpecWithTemplate: {
3342 Type *T = GetType(Record[Idx++]).getTypePtr();
3343 bool Template = Record[Idx++];
3344 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3345 break;
3346 }
3347
3348 case NestedNameSpecifier::Global: {
3349 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3350 // No associated value, and there can't be a prefix.
3351 break;
3352 }
Chris Lattnerca025db2010-05-07 21:43:38 +00003353 }
Argyrios Kyrtzidisad65c692010-07-07 15:46:30 +00003354 Prev = NNS;
Chris Lattnerca025db2010-05-07 21:43:38 +00003355 }
3356 return NNS;
3357}
3358
3359SourceRange
3360PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar6d3bc082010-06-02 15:47:10 +00003361 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3362 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3363 return SourceRange(beg, end);
Chris Lattnerca025db2010-05-07 21:43:38 +00003364}
3365
Douglas Gregor1daeb692009-04-13 18:14:40 +00003366/// \brief Read an integral value
3367llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3368 unsigned BitWidth = Record[Idx++];
3369 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3370 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3371 Idx += NumWords;
3372 return Result;
3373}
3374
3375/// \brief Read a signed integral value
3376llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3377 bool isUnsigned = Record[Idx++];
3378 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3379}
3380
Douglas Gregore0a3a512009-04-14 21:55:33 +00003381/// \brief Read a floating-point value
3382llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00003383 return llvm::APFloat(ReadAPInt(Record, Idx));
3384}
3385
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003386// \brief Read a string
3387std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3388 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00003389 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003390 Idx += Len;
3391 return Result;
3392}
3393
Chris Lattnercba86142010-05-10 00:25:06 +00003394CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3395 unsigned &Idx) {
3396 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3397 return CXXTemporary::Create(*Context, Decl);
3398}
3399
Douglas Gregor55abb232009-04-10 20:39:37 +00003400DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00003401 return Diag(SourceLocation(), DiagID);
3402}
3403
3404DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003405 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00003406}
Douglas Gregora9af1d12009-04-17 00:04:06 +00003407
Douglas Gregora868bbd2009-04-21 22:25:48 +00003408/// \brief Retrieve the identifier table associated with the
3409/// preprocessor.
3410IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003411 assert(PP && "Forgot to set Preprocessor ?");
3412 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00003413}
3414
Douglas Gregora9af1d12009-04-17 00:04:06 +00003415/// \brief Record that the given ID maps to the given switch-case
3416/// statement.
3417void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3418 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3419 SwitchCaseStmts[ID] = SC;
3420}
3421
3422/// \brief Retrieve the switch-case statement with the given ID.
3423SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3424 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3425 return SwitchCaseStmts[ID];
3426}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003427
3428/// \brief Record that the given label statement has been
3429/// deserialized and has the given ID.
3430void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00003431 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003432 "Deserialized label twice");
3433 LabelStmts[ID] = S;
3434
3435 // If we've already seen any goto statements that point to this
3436 // label, resolve them now.
3437 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3438 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3439 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3440 Goto->second->setLabel(S);
3441 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00003442
3443 // If we've already seen any address-label statements that point to
3444 // this label, resolve them now.
3445 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00003446 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00003447 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00003448 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00003449 AddrLabel != AddrLabels.second; ++AddrLabel)
3450 AddrLabel->second->setLabel(S);
3451 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003452}
3453
3454/// \brief Set the label of the given statement to the label
3455/// identified by ID.
3456///
3457/// Depending on the order in which the label and other statements
3458/// referencing that label occur, this operation may complete
3459/// immediately (updating the statement) or it may queue the
3460/// statement to be back-patched later.
3461void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3462 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3463 if (Label != LabelStmts.end()) {
3464 // We've already seen this label, so set the label of the goto and
3465 // we're done.
3466 S->setLabel(Label->second);
3467 } else {
3468 // We haven't seen this label yet, so add this goto to the set of
3469 // unresolved goto statements.
3470 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3471 }
3472}
Douglas Gregor779d8652009-04-17 18:58:21 +00003473
3474/// \brief Set the label of the given expression to the label
3475/// identified by ID.
3476///
3477/// Depending on the order in which the label and other statements
3478/// referencing that label occur, this operation may complete
3479/// immediately (updating the statement) or it may queue the
3480/// statement to be back-patched later.
3481void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3482 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3483 if (Label != LabelStmts.end()) {
3484 // We've already seen this label, so set the label of the
3485 // label-address expression and we're done.
3486 S->setLabel(Label->second);
3487 } else {
3488 // We haven't seen this label yet, so add this label-address
3489 // expression to the set of unresolved label-address expressions.
3490 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3491 }
3492}
Douglas Gregor1342e842009-07-06 18:54:52 +00003493
3494
Mike Stump11289f42009-09-09 15:08:12 +00003495PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00003496 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
3497 Reader.CurrentlyLoadingTypeOrDecl = this;
3498}
3499
3500PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
3501 if (!Parent) {
3502 // If any identifiers with corresponding top-level declarations have
3503 // been loaded, load those declarations now.
3504 while (!Reader.PendingIdentifierInfos.empty()) {
3505 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
3506 Reader.PendingIdentifierInfos.front().DeclIDs,
3507 true);
3508 Reader.PendingIdentifierInfos.pop_front();
3509 }
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003510
3511 // We are not in recursive loading, so it's safe to pass the "interesting"
3512 // decls to the consumer.
3513 if (Reader.Consumer)
3514 Reader.PassInterestingDeclsToConsumer();
Douglas Gregor1342e842009-07-06 18:54:52 +00003515 }
3516
Mike Stump11289f42009-09-09 15:08:12 +00003517 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00003518}