blob: 9a9a1fc29bd449c609e932fe08d20609e471d6a2 [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 Redl393f8b72010-07-19 20:52:06 +0000421 Consumer(0), IdentifierOffsets(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000422 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
423 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000424 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregor9507d462010-03-19 22:13:20 +0000425 NumPreallocatedPreprocessingEntities(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000426 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump11289f42009-09-09 15:08:12 +0000427 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000428 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000429 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000430 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000431 RelocatablePCH = false;
432}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000433
434PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000435 Diagnostic &Diags, const char *isysroot)
Sebastian Redl85b2a6a2010-07-14 23:45:08 +0000436 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
Sebastian Redl34522812010-07-16 17:50:48 +0000437 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000438 IdentifierOffsets(0),
439 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
440 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000441 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregor9507d462010-03-19 22:13:20 +0000442 NumPreallocatedPreprocessingEntities(0),
Douglas Gregoraae92242010-03-19 21:51:54 +0000443 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump11289f42009-09-09 15:08:12 +0000444 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000445 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000446 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000447 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000448 RelocatablePCH = false;
449}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000450
Sebastian Redl34522812010-07-16 17:50:48 +0000451PCHReader::~PCHReader() {
452 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
453 delete Chain[e - i - 1];
454}
455
456PCHReader::PerFileData::PerFileData()
Sebastian Redl9e687992010-07-19 22:06:55 +0000457 : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
458 LocalNumDecls(0), DeclOffsets(0), IdentifierTableData(0),
459 IdentifierLookupTable(0)
Sebastian Redl34522812010-07-16 17:50:48 +0000460{}
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.
Sebastian Redl393f8b72010-07-19 20:52:06 +0000733bool PCHReader::ParseLineTable(PerFileData &F,
734 llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000735 unsigned Idx = 0;
736 LineTableInfo &LineTable = SourceMgr.getLineTable();
737
Sebastian Redl393f8b72010-07-19 20:52:06 +0000738 // FIXME: Handle multiple tables!
739 (void)F;
740
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000741 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000742 std::map<int, int> FileIDs;
743 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000744 // Extract the file name
745 unsigned FilenameLen = Record[Idx++];
746 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
747 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000748 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000749 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000750 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000751 }
752
753 // Parse the line entries
754 std::vector<LineEntry> Entries;
755 while (Idx < Record.size()) {
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000756 int FID = Record[Idx++];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000757
758 // Extract the line entries
759 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000760 assert(NumEntries && "Numentries is 00000");
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000761 Entries.clear();
762 Entries.reserve(NumEntries);
763 for (unsigned I = 0; I != NumEntries; ++I) {
764 unsigned FileOffset = Record[Idx++];
765 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000766 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump11289f42009-09-09 15:08:12 +0000767 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000768 = (SrcMgr::CharacteristicKind)Record[Idx++];
769 unsigned IncludeOffset = Record[Idx++];
770 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
771 FileKind, IncludeOffset));
772 }
773 LineTable.AddEntry(FID, Entries);
774 }
775
776 return false;
777}
778
Douglas Gregorc5046832009-04-27 18:38:38 +0000779namespace {
780
Benjamin Kramer16634c22009-11-28 10:07:24 +0000781class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000782public:
783 const bool hasStat;
784 const ino_t ino;
785 const dev_t dev;
786 const mode_t mode;
787 const time_t mtime;
788 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000789
Douglas Gregorc5046832009-04-27 18:38:38 +0000790 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000791 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
792
Douglas Gregorc5046832009-04-27 18:38:38 +0000793 PCHStatData()
794 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
795};
796
Benjamin Kramer16634c22009-11-28 10:07:24 +0000797class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000798 public:
799 typedef const char *external_key_type;
800 typedef const char *internal_key_type;
801
802 typedef PCHStatData data_type;
803
804 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000805 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000806 }
807
808 static internal_key_type GetInternalKey(const char *path) { return path; }
809
810 static bool EqualKey(internal_key_type a, internal_key_type b) {
811 return strcmp(a, b) == 0;
812 }
813
814 static std::pair<unsigned, unsigned>
815 ReadKeyDataLength(const unsigned char*& d) {
816 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
817 unsigned DataLen = (unsigned) *d++;
818 return std::make_pair(KeyLen + 1, DataLen);
819 }
820
821 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
822 return (const char *)d;
823 }
824
825 static data_type ReadData(const internal_key_type, const unsigned char *d,
826 unsigned /*DataLen*/) {
827 using namespace clang::io;
828
829 if (*d++ == 1)
830 return data_type();
831
832 ino_t ino = (ino_t) ReadUnalignedLE32(d);
833 dev_t dev = (dev_t) ReadUnalignedLE32(d);
834 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000835 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000836 off_t size = (off_t) ReadUnalignedLE64(d);
837 return data_type(ino, dev, mode, mtime, size);
838 }
839};
840
841/// \brief stat() cache for precompiled headers.
842///
843/// This cache is very similar to the stat cache used by pretokenized
844/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000845class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000846 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
847 CacheTy *Cache;
848
849 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000850public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000851 PCHStatCache(const unsigned char *Buckets,
852 const unsigned char *Base,
853 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000854 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000855 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
856 Cache = CacheTy::Create(Buckets, Base);
857 }
858
859 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000860
Douglas Gregorc5046832009-04-27 18:38:38 +0000861 int stat(const char *path, struct stat *buf) {
862 // Do the lookup for the file's data in the PCH file.
863 CacheTy::iterator I = Cache->find(path);
864
865 // If we don't get a hit in the PCH file just forward to 'stat'.
866 if (I == Cache->end()) {
867 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000868 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000869 }
Mike Stump11289f42009-09-09 15:08:12 +0000870
Douglas Gregorc5046832009-04-27 18:38:38 +0000871 ++NumStatHits;
872 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000873
Douglas Gregorc5046832009-04-27 18:38:38 +0000874 if (!Data.hasStat)
875 return 1;
876
877 buf->st_ino = Data.ino;
878 buf->st_dev = Data.dev;
879 buf->st_mtime = Data.mtime;
880 buf->st_mode = Data.mode;
881 buf->st_size = Data.size;
882 return 0;
883 }
884};
885} // end anonymous namespace
886
887
Sebastian Redl393f8b72010-07-19 20:52:06 +0000888/// \brief Read a source manager block
889PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000890 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000891
Sebastian Redl393f8b72010-07-19 20:52:06 +0000892 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl34522812010-07-16 17:50:48 +0000893
Douglas Gregor258ae542009-04-27 06:38:32 +0000894 // Set the source-location entry cursor to the current position in
895 // the stream. This cursor will be used to read the contents of the
896 // source manager block initially, and then lazily read
897 // source-location entries as needed.
Sebastian Redl393f8b72010-07-19 20:52:06 +0000898 SLocEntryCursor = F.Stream;
Douglas Gregor258ae542009-04-27 06:38:32 +0000899
900 // The stream itself is going to skip over the source manager block.
Sebastian Redl393f8b72010-07-19 20:52:06 +0000901 if (F.Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000902 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000903 return Failure;
904 }
905
906 // Enter the source manager block.
907 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000908 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000909 return Failure;
910 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000911
Douglas Gregora7f71a92009-04-10 03:52:48 +0000912 RecordData Record;
913 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000914 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000915 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000916 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000917 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000918 return Failure;
919 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000920 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregora7f71a92009-04-10 03:52:48 +0000923 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
924 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000925 SLocEntryCursor.ReadSubBlockID();
926 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000927 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000928 return Failure;
929 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000930 continue;
931 }
Mike Stump11289f42009-09-09 15:08:12 +0000932
Douglas Gregora7f71a92009-04-10 03:52:48 +0000933 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000934 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000935 continue;
936 }
Mike Stump11289f42009-09-09 15:08:12 +0000937
Douglas Gregora7f71a92009-04-10 03:52:48 +0000938 // Read a record.
939 const char *BlobStart;
940 unsigned BlobLen;
941 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000942 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000943 default: // Default behavior: ignore.
944 break;
945
Chris Lattner184e65d2009-04-14 23:22:57 +0000946 case pch::SM_LINE_TABLE:
Sebastian Redl393f8b72010-07-19 20:52:06 +0000947 if (ParseLineTable(F, Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000948 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000949 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000950
Douglas Gregor258ae542009-04-27 06:38:32 +0000951 case pch::SM_SLOC_FILE_ENTRY:
952 case pch::SM_SLOC_BUFFER_ENTRY:
953 case pch::SM_SLOC_INSTANTIATION_ENTRY:
954 // Once we hit one of the source location entries, we're done.
955 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000956 }
957 }
958}
959
Douglas Gregor258ae542009-04-27 06:38:32 +0000960/// \brief Read in the source location entry with the given ID.
961PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
962 if (ID == 0)
963 return Success;
964
965 if (ID > TotalNumSLocEntries) {
966 Error("source location entry ID out-of-range for PCH file");
967 return Failure;
968 }
969
Sebastian Redl34522812010-07-16 17:50:48 +0000970 llvm::BitstreamCursor &SLocEntryCursor = Chain[0]->SLocEntryCursor;
971
Douglas Gregor258ae542009-04-27 06:38:32 +0000972 ++NumSLocEntriesRead;
973 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
974 unsigned Code = SLocEntryCursor.ReadCode();
975 if (Code == llvm::bitc::END_BLOCK ||
976 Code == llvm::bitc::ENTER_SUBBLOCK ||
977 Code == llvm::bitc::DEFINE_ABBREV) {
978 Error("incorrectly-formatted source location entry in PCH file");
979 return Failure;
980 }
981
Douglas Gregor258ae542009-04-27 06:38:32 +0000982 RecordData Record;
983 const char *BlobStart;
984 unsigned BlobLen;
985 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
986 default:
987 Error("incorrectly-formatted source location entry in PCH file");
988 return Failure;
989
990 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000991 std::string Filename(BlobStart, BlobStart + BlobLen);
992 MaybeAddSystemRootToFilename(Filename);
993 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000994 if (File == 0) {
995 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000996 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000997 ErrorStr += "' referenced by PCH file";
998 Error(ErrorStr.c_str());
999 return Failure;
1000 }
Mike Stump11289f42009-09-09 15:08:12 +00001001
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001002 if (Record.size() < 10) {
Ted Kremenekabb1ddd2010-03-18 21:23:05 +00001003 Error("source location entry is incorrect");
1004 return Failure;
1005 }
1006
Douglas Gregor08288f22010-04-09 15:54:22 +00001007 if ((off_t)Record[4] != File->getSize()
1008#if !defined(LLVM_ON_WIN32)
1009 // In our regression testing, the Windows file system seems to
1010 // have inconsistent modification times that sometimes
1011 // erroneously trigger this error-handling path.
1012 || (time_t)Record[5] != File->getModificationTime()
1013#endif
1014 ) {
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001015 Diag(diag::err_fe_pch_file_modified)
1016 << Filename;
1017 return Failure;
1018 }
1019
Douglas Gregor258ae542009-04-27 06:38:32 +00001020 FileID FID = SourceMgr.createFileID(File,
1021 SourceLocation::getFromRawEncoding(Record[1]),
1022 (SrcMgr::CharacteristicKind)Record[2],
1023 ID, Record[0]);
1024 if (Record[3])
1025 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1026 .setHasLineDirectives();
1027
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001028 // Reconstruct header-search information for this file.
1029 HeaderFileInfo HFI;
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001030 HFI.isImport = Record[6];
1031 HFI.DirInfo = Record[7];
1032 HFI.NumIncludes = Record[8];
1033 HFI.ControllingMacroID = Record[9];
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001034 if (Listener)
1035 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor258ae542009-04-27 06:38:32 +00001036 break;
1037 }
1038
1039 case pch::SM_SLOC_BUFFER_ENTRY: {
1040 const char *Name = BlobStart;
1041 unsigned Offset = Record[0];
1042 unsigned Code = SLocEntryCursor.ReadCode();
1043 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001044 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +00001045 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001046
1047 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1048 Error("PCH record has invalid code");
1049 return Failure;
1050 }
1051
Douglas Gregor258ae542009-04-27 06:38:32 +00001052 llvm::MemoryBuffer *Buffer
Chris Lattner58c79342010-04-05 22:42:27 +00001053 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1054 Name);
Douglas Gregor258ae542009-04-27 06:38:32 +00001055 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +00001056
Douglas Gregore6648fb2009-04-28 20:33:11 +00001057 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl75fbb3b2010-07-14 17:49:11 +00001058 PCHPredefinesBlock Block = {
1059 BufferID,
1060 llvm::StringRef(BlobStart, BlobLen - 1)
1061 };
1062 PCHPredefinesBuffers.push_back(Block);
Douglas Gregore6648fb2009-04-28 20:33:11 +00001063 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001064
1065 break;
1066 }
1067
1068 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +00001069 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +00001070 = SourceLocation::getFromRawEncoding(Record[1]);
1071 SourceMgr.createInstantiationLoc(SpellingLoc,
1072 SourceLocation::getFromRawEncoding(Record[2]),
1073 SourceLocation::getFromRawEncoding(Record[3]),
1074 Record[4],
1075 ID,
1076 Record[0]);
1077 break;
Mike Stump11289f42009-09-09 15:08:12 +00001078 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001079 }
1080
1081 return Success;
1082}
1083
Chris Lattnere78a6be2009-04-27 01:05:14 +00001084/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1085/// specified cursor. Read the abbreviations that are at the top of the block
1086/// and then leave the cursor pointing into the block.
1087bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1088 unsigned BlockID) {
1089 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001090 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001091 return Failure;
1092 }
Mike Stump11289f42009-09-09 15:08:12 +00001093
Chris Lattnere78a6be2009-04-27 01:05:14 +00001094 while (true) {
1095 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001096
Chris Lattnere78a6be2009-04-27 01:05:14 +00001097 // We expect all abbrevs to be at the start of the block.
1098 if (Code != llvm::bitc::DEFINE_ABBREV)
1099 return false;
1100 Cursor.ReadAbbrevRecord();
1101 }
1102}
1103
Douglas Gregorc3366a52009-04-21 23:56:24 +00001104void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001105 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +00001106
Sebastian Redl34522812010-07-16 17:50:48 +00001107 llvm::BitstreamCursor &Stream = Chain[0]->Stream;
1108
Douglas Gregorc3366a52009-04-21 23:56:24 +00001109 // Keep track of where we are in the stream, then jump back there
1110 // after reading this macro.
1111 SavedStreamPosition SavedPosition(Stream);
1112
1113 Stream.JumpToBit(Offset);
1114 RecordData Record;
1115 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1116 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001117
Douglas Gregorc3366a52009-04-21 23:56:24 +00001118 while (true) {
1119 unsigned Code = Stream.ReadCode();
1120 switch (Code) {
1121 case llvm::bitc::END_BLOCK:
1122 return;
1123
1124 case llvm::bitc::ENTER_SUBBLOCK:
1125 // No known subblocks, always skip them.
1126 Stream.ReadSubBlockID();
1127 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001128 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001129 return;
1130 }
1131 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001132
Douglas Gregorc3366a52009-04-21 23:56:24 +00001133 case llvm::bitc::DEFINE_ABBREV:
1134 Stream.ReadAbbrevRecord();
1135 continue;
1136 default: break;
1137 }
1138
1139 // Read a record.
1140 Record.clear();
1141 pch::PreprocessorRecordTypes RecType =
1142 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1143 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001144 case pch::PP_MACRO_OBJECT_LIKE:
1145 case pch::PP_MACRO_FUNCTION_LIKE: {
1146 // If we already have a macro, that means that we've hit the end
1147 // of the definition of the macro we were looking for. We're
1148 // done.
1149 if (Macro)
1150 return;
1151
1152 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1153 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001154 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001155 return;
1156 }
1157 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1158 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001159
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001160 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001161 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001162
Douglas Gregoraae92242010-03-19 21:51:54 +00001163 unsigned NextIndex = 3;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001164 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1165 // Decode function-like macro info.
1166 bool isC99VarArgs = Record[3];
1167 bool isGNUVarArgs = Record[4];
1168 MacroArgs.clear();
1169 unsigned NumArgs = Record[5];
Douglas Gregoraae92242010-03-19 21:51:54 +00001170 NextIndex = 6 + NumArgs;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001171 for (unsigned i = 0; i != NumArgs; ++i)
1172 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1173
1174 // Install function-like macro info.
1175 MI->setIsFunctionLike();
1176 if (isC99VarArgs) MI->setIsC99Varargs();
1177 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001178 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001179 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001180 }
1181
1182 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001183 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001184
1185 // Remember that we saw this macro last so that we add the tokens that
1186 // form its body to it.
1187 Macro = MI;
Douglas Gregoraae92242010-03-19 21:51:54 +00001188
1189 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1190 // We have a macro definition. Load it now.
1191 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1192 getMacroDefinition(Record[NextIndex]));
1193 }
1194
Douglas Gregorc3366a52009-04-21 23:56:24 +00001195 ++NumMacrosRead;
1196 break;
1197 }
Mike Stump11289f42009-09-09 15:08:12 +00001198
Douglas Gregorc3366a52009-04-21 23:56:24 +00001199 case pch::PP_TOKEN: {
1200 // If we see a TOKEN before a PP_MACRO_*, then the file is
1201 // erroneous, just pretend we didn't see this.
1202 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001203
Douglas Gregorc3366a52009-04-21 23:56:24 +00001204 Token Tok;
1205 Tok.startToken();
1206 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1207 Tok.setLength(Record[1]);
1208 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1209 Tok.setIdentifierInfo(II);
1210 Tok.setKind((tok::TokenKind)Record[3]);
1211 Tok.setFlag((Token::TokenFlags)Record[4]);
1212 Macro->AddTokenToBody(Tok);
1213 break;
1214 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001215
1216 case pch::PP_MACRO_INSTANTIATION: {
1217 // If we already have a macro, that means that we've hit the end
1218 // of the definition of the macro we were looking for. We're
1219 // done.
1220 if (Macro)
1221 return;
1222
1223 if (!PP->getPreprocessingRecord()) {
1224 Error("missing preprocessing record in PCH file");
1225 return;
1226 }
1227
1228 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1229 if (PPRec.getPreprocessedEntity(Record[0]))
1230 return;
1231
1232 MacroInstantiation *MI
1233 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1234 SourceRange(
1235 SourceLocation::getFromRawEncoding(Record[1]),
1236 SourceLocation::getFromRawEncoding(Record[2])),
1237 getMacroDefinition(Record[4]));
1238 PPRec.SetPreallocatedEntity(Record[0], MI);
1239 return;
1240 }
1241
1242 case pch::PP_MACRO_DEFINITION: {
1243 // If we already have a macro, that means that we've hit the end
1244 // of the definition of the macro we were looking for. We're
1245 // done.
1246 if (Macro)
1247 return;
1248
1249 if (!PP->getPreprocessingRecord()) {
1250 Error("missing preprocessing record in PCH file");
1251 return;
1252 }
1253
1254 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1255 if (PPRec.getPreprocessedEntity(Record[0]))
1256 return;
1257
1258 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1259 Error("out-of-bounds macro definition record");
1260 return;
1261 }
1262
1263 MacroDefinition *MD
1264 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1265 SourceLocation::getFromRawEncoding(Record[5]),
1266 SourceRange(
1267 SourceLocation::getFromRawEncoding(Record[2]),
1268 SourceLocation::getFromRawEncoding(Record[3])));
1269 PPRec.SetPreallocatedEntity(Record[0], MD);
1270 MacroDefinitionsLoaded[Record[1]] = MD;
1271 return;
1272 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001273 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001274 }
1275}
1276
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001277void PCHReader::ReadDefinedMacros() {
Sebastian Redl34522812010-07-16 17:50:48 +00001278 llvm::BitstreamCursor &MacroCursor = Chain[0]->MacroCursor;
1279
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001280 // If there was no preprocessor block, do nothing.
1281 if (!MacroCursor.getBitStreamReader())
1282 return;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001283
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001284 llvm::BitstreamCursor Cursor = MacroCursor;
1285 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1286 Error("malformed preprocessor block record in PCH file");
1287 return;
1288 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001289
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001290 RecordData Record;
1291 while (true) {
1292 unsigned Code = Cursor.ReadCode();
1293 if (Code == llvm::bitc::END_BLOCK) {
1294 if (Cursor.ReadBlockEnd())
1295 Error("error at end of preprocessor block in PCH file");
1296 return;
1297 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001298
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001299 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1300 // No known subblocks, always skip them.
1301 Cursor.ReadSubBlockID();
1302 if (Cursor.SkipBlock()) {
1303 Error("malformed block record in PCH file");
1304 return;
1305 }
1306 continue;
1307 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001308
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001309 if (Code == llvm::bitc::DEFINE_ABBREV) {
1310 Cursor.ReadAbbrevRecord();
1311 continue;
1312 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001313
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001314 // Read a record.
1315 const char *BlobStart;
1316 unsigned BlobLen;
1317 Record.clear();
1318 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1319 default: // Default behavior: ignore.
1320 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001321
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001322 case pch::PP_MACRO_OBJECT_LIKE:
1323 case pch::PP_MACRO_FUNCTION_LIKE:
Douglas Gregoraae92242010-03-19 21:51:54 +00001324 DecodeIdentifierInfo(Record[0]);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001325 break;
1326
1327 case pch::PP_TOKEN:
1328 // Ignore tokens.
1329 break;
Douglas Gregoraae92242010-03-19 21:51:54 +00001330
1331 case pch::PP_MACRO_INSTANTIATION:
1332 case pch::PP_MACRO_DEFINITION:
1333 // Read the macro record.
1334 ReadMacroRecord(Cursor.GetCurrentBitNo());
1335 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001336 }
1337 }
1338}
1339
Douglas Gregoraae92242010-03-19 21:51:54 +00001340MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1341 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1342 return 0;
1343
1344 if (!MacroDefinitionsLoaded[ID])
1345 ReadMacroRecord(MacroDefinitionOffsets[ID]);
1346
1347 return MacroDefinitionsLoaded[ID];
1348}
1349
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001350/// \brief If we are loading a relocatable PCH file, and the filename is
1351/// not an absolute path, add the system root to the beginning of the file
1352/// name.
1353void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1354 // If this is not a relocatable PCH file, there's nothing to do.
1355 if (!RelocatablePCH)
1356 return;
Mike Stump11289f42009-09-09 15:08:12 +00001357
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001358 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001359 return;
1360
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001361 if (isysroot == 0) {
1362 // If no system root was given, default to '/'
1363 Filename.insert(Filename.begin(), '/');
1364 return;
1365 }
Mike Stump11289f42009-09-09 15:08:12 +00001366
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001367 unsigned Length = strlen(isysroot);
1368 if (isysroot[Length - 1] != '/')
1369 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001370
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001371 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1372}
1373
Mike Stump11289f42009-09-09 15:08:12 +00001374PCHReader::PCHReadResult
Sebastian Redl2abc0382010-07-16 20:41:52 +00001375PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl34522812010-07-16 17:50:48 +00001376 llvm::BitstreamCursor &Stream = F.Stream;
1377
Douglas Gregor55abb232009-04-10 20:39:37 +00001378 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001379 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001380 return Failure;
1381 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001382
1383 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001384 RecordData Record;
Sebastian Redl393f8b72010-07-19 20:52:06 +00001385 bool First = true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001386 while (!Stream.AtEndOfStream()) {
1387 unsigned Code = Stream.ReadCode();
1388 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001389 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001390 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001391 return Failure;
1392 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001393
Douglas Gregor55abb232009-04-10 20:39:37 +00001394 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001395 }
1396
1397 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1398 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001399 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001400 // We lazily load the decls block, but we want to set up the
1401 // DeclsCursor cursor to point into it. Clone our current bitcode
1402 // cursor to it, enter the block and read the abbrevs in that block.
1403 // With the main cursor, we just skip over it.
Sebastian Redl34522812010-07-16 17:50:48 +00001404 F.DeclsCursor = Stream;
Chris Lattnere78a6be2009-04-27 01:05:14 +00001405 if (Stream.SkipBlock() || // Skip with the main cursor.
1406 // Read the abbrevs.
Sebastian Redl34522812010-07-16 17:50:48 +00001407 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001408 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001409 return Failure;
1410 }
1411 break;
Mike Stump11289f42009-09-09 15:08:12 +00001412
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001413 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl34522812010-07-16 17:50:48 +00001414 F.MacroCursor = Stream;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001415 if (PP)
1416 PP->setExternalSource(this);
1417
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001418 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001419 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001420 return Failure;
1421 }
1422 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001423
Douglas Gregora7f71a92009-04-10 03:52:48 +00001424 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl393f8b72010-07-19 20:52:06 +00001425 switch (ReadSourceManagerBlock(F)) {
Douglas Gregor92863e42009-04-10 23:10:45 +00001426 case Success:
1427 break;
1428
1429 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001430 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001431 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001432
1433 case IgnorePCH:
1434 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001435 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001436 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001437 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00001438 First = false;
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001439 continue;
1440 }
1441
1442 if (Code == llvm::bitc::DEFINE_ABBREV) {
1443 Stream.ReadAbbrevRecord();
1444 continue;
1445 }
1446
1447 // Read and process a record.
1448 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001449 const char *BlobStart = 0;
1450 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001451 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001452 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001453 default: // Default behavior: ignore.
1454 break;
1455
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001456 case pch::METADATA: {
1457 if (Record[0] != pch::VERSION_MAJOR) {
1458 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1459 : diag::warn_pch_version_too_new);
1460 return IgnorePCH;
1461 }
1462
1463 RelocatablePCH = Record[4];
1464 if (Listener) {
1465 std::string TargetTriple(BlobStart, BlobLen);
1466 if (Listener->ReadTargetTriple(TargetTriple))
1467 return IgnorePCH;
1468 }
1469 break;
1470 }
1471
1472 case pch::CHAINED_METADATA: {
Sebastian Redl393f8b72010-07-19 20:52:06 +00001473 if (!First) {
1474 Error("CHAINED_METADATA is not first record in block");
1475 return Failure;
1476 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001477 if (Record[0] != pch::VERSION_MAJOR) {
1478 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1479 : diag::warn_pch_version_too_new);
1480 return IgnorePCH;
1481 }
1482
1483 // Load the chained file.
1484 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1485 case Failure: return Failure;
1486 // If we have to ignore the dependency, we'll have to ignore this too.
1487 case IgnorePCH: return IgnorePCH;
1488 case Success: break;
1489 }
1490 break;
1491 }
1492
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001493 case pch::TYPE_OFFSET:
Sebastian Redl9e687992010-07-19 22:06:55 +00001494 if (F.LocalNumTypes != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001495 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001496 return Failure;
1497 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001498 F.TypeOffsets = (const uint32_t *)BlobStart;
1499 F.LocalNumTypes = Record[0];
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001500 break;
1501
1502 case pch::DECL_OFFSET:
Sebastian Redl9e687992010-07-19 22:06:55 +00001503 if (F.LocalNumDecls != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001504 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001505 return Failure;
1506 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001507 F.DeclOffsets = (const uint32_t *)BlobStart;
1508 F.LocalNumDecls = Record[0];
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001509 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001510
1511 case pch::LANGUAGE_OPTIONS:
1512 if (ParseLanguageOptions(Record))
1513 return IgnorePCH;
1514 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001515
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001516 case pch::IDENTIFIER_TABLE:
Sebastian Redl393f8b72010-07-19 20:52:06 +00001517 F.IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001518 if (Record[0]) {
Sebastian Redl393f8b72010-07-19 20:52:06 +00001519 F.IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001520 = PCHIdentifierLookupTable::Create(
Sebastian Redl393f8b72010-07-19 20:52:06 +00001521 (const unsigned char *)F.IdentifierTableData + Record[0],
1522 (const unsigned char *)F.IdentifierTableData,
1523 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001524 if (PP)
1525 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001526 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001527 break;
1528
1529 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001530 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001531 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001532 return Failure;
1533 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001534 IdentifierOffsets = (const uint32_t *)BlobStart;
1535 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001536 if (PP)
1537 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001538 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001539
1540 case pch::EXTERNAL_DEFINITIONS:
1541 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001542 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001543 return Failure;
1544 }
1545 ExternalDefinitions.swap(Record);
1546 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001547
Douglas Gregor652d82a2009-04-18 05:55:16 +00001548 case pch::SPECIAL_TYPES:
1549 SpecialTypes.swap(Record);
1550 break;
1551
Douglas Gregor08f01292009-04-17 22:13:46 +00001552 case pch::STATISTICS:
1553 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001554 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001555 TotalLexicalDeclContexts = Record[2];
1556 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001557 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001558
Douglas Gregord4df8652009-04-22 22:02:47 +00001559 case pch::TENTATIVE_DEFINITIONS:
1560 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001561 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001562 return Failure;
1563 }
1564 TentativeDefinitions.swap(Record);
1565 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001566
Tanya Lattner90073802010-02-12 00:07:30 +00001567 case pch::UNUSED_STATIC_FUNCS:
1568 if (!UnusedStaticFuncs.empty()) {
1569 Error("duplicate UNUSED_STATIC_FUNCS record in PCH file");
1570 return Failure;
1571 }
1572 UnusedStaticFuncs.swap(Record);
1573 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001574
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001575 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1576 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001577 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001578 return Failure;
1579 }
1580 LocallyScopedExternalDecls.swap(Record);
1581 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001582
Douglas Gregor95c13f52009-04-25 17:48:32 +00001583 case pch::SELECTOR_OFFSETS:
1584 SelectorOffsets = (const uint32_t *)BlobStart;
1585 TotalNumSelectors = Record[0];
1586 SelectorsLoaded.resize(TotalNumSelectors);
1587 break;
1588
Douglas Gregorc78d3462009-04-24 21:10:55 +00001589 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001590 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1591 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001592 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001593 = PCHMethodPoolLookupTable::Create(
1594 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001595 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001596 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001597 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001598 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001599
1600 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001601 if (!Record.empty() && Listener)
1602 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001603 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001604
1605 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001606 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001607 TotalNumSLocEntries = Record[0];
Douglas Gregord54f3a12009-10-05 21:07:28 +00001608 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001609 break;
1610
1611 case pch::SOURCE_LOCATION_PRELOADS:
1612 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1613 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1614 if (Result != Success)
1615 return Result;
1616 }
1617 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001618
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001619 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001620 PCHStatCache *MyStatCache =
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001621 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1622 (const unsigned char *)BlobStart,
1623 NumStatHits, NumStatMisses);
1624 FileMgr.addStatCache(MyStatCache);
Sebastian Redl34522812010-07-16 17:50:48 +00001625 F.StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001626 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001627 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001628
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001629 case pch::EXT_VECTOR_DECLS:
1630 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001631 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001632 return Failure;
1633 }
1634 ExtVectorDecls.swap(Record);
1635 break;
1636
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00001637 case pch::VTABLE_USES:
1638 if (!VTableUses.empty()) {
1639 Error("duplicate VTABLE_USES record in PCH file");
1640 return Failure;
1641 }
1642 VTableUses.swap(Record);
1643 break;
1644
1645 case pch::DYNAMIC_CLASSES:
1646 if (!DynamicClasses.empty()) {
1647 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1648 return Failure;
1649 }
1650 DynamicClasses.swap(Record);
1651 break;
1652
Douglas Gregor45fe0362009-05-12 01:31:05 +00001653 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001654 ActualOriginalFileName.assign(BlobStart, BlobLen);
1655 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001656 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001657 break;
Mike Stump11289f42009-09-09 15:08:12 +00001658
Ted Kremenek17437132010-01-22 20:59:36 +00001659 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek8bd09292010-02-12 23:31:14 +00001660 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek2377a0e2010-01-22 20:55:35 +00001661 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Ted Kremenek8bd09292010-02-12 23:31:14 +00001662 if (llvm::StringRef(CurBranch) != PCHBranch) {
Douglas Gregord54f3a12009-10-05 21:07:28 +00001663 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1664 return IgnorePCH;
1665 }
1666 break;
1667 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001668
1669 case pch::MACRO_DEFINITION_OFFSETS:
1670 MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1671 if (PP) {
1672 if (!PP->getPreprocessingRecord())
1673 PP->createPreprocessingRecord();
1674 PP->getPreprocessingRecord()->SetExternalSource(*this, Record[0]);
1675 } else {
1676 NumPreallocatedPreprocessingEntities = Record[0];
1677 }
1678
1679 MacroDefinitionsLoaded.resize(Record[1]);
1680 break;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001681 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00001682 First = false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001683 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001684 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001685 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001686}
1687
Douglas Gregor92863e42009-04-10 23:10:45 +00001688PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001689 switch(ReadPCHCore(FileName)) {
Sebastian Redl2abc0382010-07-16 20:41:52 +00001690 case Failure: return Failure;
1691 case IgnorePCH: return IgnorePCH;
1692 case Success: break;
1693 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001694
1695 // Here comes stuff that we only do once the entire chain is loaded.
1696
Sebastian Redl9e687992010-07-19 22:06:55 +00001697 // Allocate space for loaded decls and types.
1698 unsigned TotalNumTypes = 0, TotalNumDecls = 0;
1699 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1700 TotalNumTypes += Chain[I]->LocalNumTypes;
1701 TotalNumDecls += Chain[I]->LocalNumDecls;
1702 }
1703 TypesLoaded.resize(TotalNumTypes);
1704 DeclsLoaded.resize(TotalNumDecls);
1705
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001706 // Check the predefines buffers.
1707 if (CheckPredefinesBuffers())
1708 return IgnorePCH;
1709
1710 if (PP) {
1711 // Initialization of keywords and pragmas occurs before the
1712 // PCH file is read, so there may be some identifiers that were
1713 // loaded into the IdentifierTable before we intercepted the
1714 // creation of identifiers. Iterate through the list of known
1715 // identifiers and determine whether we have to establish
1716 // preprocessor definitions or top-level identifier declaration
1717 // chains for those identifiers.
1718 //
1719 // We copy the IdentifierInfo pointers to a small vector first,
1720 // since de-serializing declarations or macro definitions can add
1721 // new entries into the identifier table, invalidating the
1722 // iterators.
1723 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1724 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1725 IdEnd = PP->getIdentifierTable().end();
1726 Id != IdEnd; ++Id)
1727 Identifiers.push_back(Id->second);
1728 PCHIdentifierLookupTable *IdTable
Sebastian Redl393f8b72010-07-19 20:52:06 +00001729 = (PCHIdentifierLookupTable *)Chain[0]->IdentifierLookupTable;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001730 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1731 IdentifierInfo *II = Identifiers[I];
1732 // Look in the on-disk hash table for an entry for
1733 PCHIdentifierLookupTrait Info(*this, II);
1734 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
1735 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1736 if (Pos == IdTable->end())
1737 continue;
1738
1739 // Dereferencing the iterator has the effect of populating the
1740 // IdentifierInfo node with the various declarations it needs.
1741 (void)*Pos;
1742 }
1743 }
1744
1745 if (Context)
1746 InitializeContext(*Context);
1747
1748 return Success;
1749}
1750
1751PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1752 Chain.push_back(new PerFileData());
Sebastian Redl34522812010-07-16 17:50:48 +00001753 PerFileData &F = *Chain.back();
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001754
1755 // Set the PCH file name.
1756 F.FileName = FileName;
1757
1758 // Open the PCH file.
1759 //
1760 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1761 std::string ErrStr;
1762 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1763 if (!F.Buffer) {
1764 Error(ErrStr.c_str());
1765 return IgnorePCH;
1766 }
1767
1768 // Initialize the stream
1769 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1770 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl34522812010-07-16 17:50:48 +00001771 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001772 Stream.init(F.StreamFile);
1773
1774 // Sniff for the signature.
1775 if (Stream.Read(8) != 'C' ||
1776 Stream.Read(8) != 'P' ||
1777 Stream.Read(8) != 'C' ||
1778 Stream.Read(8) != 'H') {
1779 Diag(diag::err_not_a_pch_file) << FileName;
1780 return Failure;
1781 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001782
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001783 while (!Stream.AtEndOfStream()) {
1784 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001785
Douglas Gregor92863e42009-04-10 23:10:45 +00001786 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001787 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001788 return Failure;
1789 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001790
1791 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001792
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001793 // We only know the PCH subblock ID.
1794 switch (BlockID) {
1795 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001796 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001797 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001798 return Failure;
1799 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001800 break;
1801 case pch::PCH_BLOCK_ID:
Sebastian Redl2abc0382010-07-16 20:41:52 +00001802 switch (ReadPCHBlock(F)) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001803 case Success:
1804 break;
1805
1806 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001807 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001808
1809 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001810 // FIXME: We could consider reading through to the end of this
1811 // PCH block, skipping subblocks, to see if there are other
1812 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001813
1814 // Clear out any preallocated source location entries, so that
1815 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001816 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001817
1818 // Remove the stat cache.
Sebastian Redl34522812010-07-16 17:50:48 +00001819 if (F.StatCache)
1820 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001821
Douglas Gregor92863e42009-04-10 23:10:45 +00001822 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001823 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001824 break;
1825 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001826 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001827 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001828 return Failure;
1829 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001830 break;
1831 }
Mike Stump11289f42009-09-09 15:08:12 +00001832 }
1833
Sebastian Redl2abc0382010-07-16 20:41:52 +00001834 return Success;
1835}
1836
Douglas Gregoraae92242010-03-19 21:51:54 +00001837void PCHReader::setPreprocessor(Preprocessor &pp) {
1838 PP = &pp;
1839
1840 if (NumPreallocatedPreprocessingEntities) {
1841 if (!PP->getPreprocessingRecord())
1842 PP->createPreprocessingRecord();
1843 PP->getPreprocessingRecord()->SetExternalSource(*this,
1844 NumPreallocatedPreprocessingEntities);
1845 NumPreallocatedPreprocessingEntities = 0;
1846 }
1847}
1848
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001849void PCHReader::InitializeContext(ASTContext &Ctx) {
1850 Context = &Ctx;
1851 assert(Context && "Passed null context!");
1852
1853 assert(PP && "Forgot to set Preprocessor ?");
1854 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1855 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001856 PP->setExternalSource(this);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001857
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001858 // Load the translation unit declaration
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00001859 GetTranslationUnitDecl();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001860
1861 // Load the special types.
1862 Context->setBuiltinVaListType(
1863 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1864 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1865 Context->setObjCIdType(GetType(Id));
1866 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1867 Context->setObjCSelType(GetType(Sel));
1868 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1869 Context->setObjCProtoType(GetType(Proto));
1870 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1871 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001872
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001873 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1874 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001875 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001876 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1877 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001878 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1879 QualType FileType = GetType(File);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001880 if (FileType.isNull()) {
1881 Error("FILE type is NULL");
1882 return;
1883 }
John McCall9dd450b2009-09-21 23:43:11 +00001884 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001885 Context->setFILEDecl(Typedef->getDecl());
1886 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001887 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001888 if (!Tag) {
1889 Error("Invalid FILE type in PCH file");
1890 return;
1891 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00001892 Context->setFILEDecl(Tag->getDecl());
1893 }
1894 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001895 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1896 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001897 if (Jmp_bufType.isNull()) {
1898 Error("jmp_bug type is NULL");
1899 return;
1900 }
John McCall9dd450b2009-09-21 23:43:11 +00001901 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001902 Context->setjmp_bufDecl(Typedef->getDecl());
1903 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001904 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001905 if (!Tag) {
1906 Error("Invalid jmp_bug type in PCH file");
1907 return;
1908 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001909 Context->setjmp_bufDecl(Tag->getDecl());
1910 }
1911 }
1912 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1913 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001914 if (Sigjmp_bufType.isNull()) {
1915 Error("sigjmp_buf type is NULL");
1916 return;
1917 }
John McCall9dd450b2009-09-21 23:43:11 +00001918 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001919 Context->setsigjmp_bufDecl(Typedef->getDecl());
1920 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001921 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001922 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1923 Context->setsigjmp_bufDecl(Tag->getDecl());
1924 }
1925 }
Mike Stump11289f42009-09-09 15:08:12 +00001926 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001927 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1928 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001929 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001930 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1931 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpd0153282009-10-20 02:12:22 +00001932 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1933 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00001934 if (unsigned String
1935 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1936 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001937 if (unsigned ObjCSelRedef
1938 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
1939 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
1940 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
1941 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +00001942
1943 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
1944 Context->setInt128Installed();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001945}
1946
Douglas Gregor45fe0362009-05-12 01:31:05 +00001947/// \brief Retrieve the name of the original source file name
1948/// directly from the PCH file, without actually loading the PCH
1949/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00001950std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1951 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00001952 // Open the PCH file.
1953 std::string ErrStr;
1954 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1955 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1956 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001957 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001958 return std::string();
1959 }
1960
1961 // Initialize the stream
1962 llvm::BitstreamReader StreamFile;
1963 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001964 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001965 (const unsigned char *)Buffer->getBufferEnd());
1966 Stream.init(StreamFile);
1967
1968 // Sniff for the signature.
1969 if (Stream.Read(8) != 'C' ||
1970 Stream.Read(8) != 'P' ||
1971 Stream.Read(8) != 'C' ||
1972 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001973 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001974 return std::string();
1975 }
1976
1977 RecordData Record;
1978 while (!Stream.AtEndOfStream()) {
1979 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001980
Douglas Gregor45fe0362009-05-12 01:31:05 +00001981 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1982 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001983
Douglas Gregor45fe0362009-05-12 01:31:05 +00001984 // We only know the PCH subblock ID.
1985 switch (BlockID) {
1986 case pch::PCH_BLOCK_ID:
1987 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001988 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001989 return std::string();
1990 }
1991 break;
Mike Stump11289f42009-09-09 15:08:12 +00001992
Douglas Gregor45fe0362009-05-12 01:31:05 +00001993 default:
1994 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001995 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001996 return std::string();
1997 }
1998 break;
1999 }
2000 continue;
2001 }
2002
2003 if (Code == llvm::bitc::END_BLOCK) {
2004 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002005 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002006 return std::string();
2007 }
2008 continue;
2009 }
2010
2011 if (Code == llvm::bitc::DEFINE_ABBREV) {
2012 Stream.ReadAbbrevRecord();
2013 continue;
2014 }
2015
2016 Record.clear();
2017 const char *BlobStart = 0;
2018 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002019 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00002020 == pch::ORIGINAL_FILE_NAME)
2021 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00002022 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00002023
2024 return std::string();
2025}
2026
Douglas Gregor55abb232009-04-10 20:39:37 +00002027/// \brief Parse the record that corresponds to a LangOptions data
2028/// structure.
2029///
2030/// This routine compares the language options used to generate the
2031/// PCH file against the language options set for the current
2032/// compilation. For each option, we classify differences between the
2033/// two compiler states as either "benign" or "important". Benign
2034/// differences don't matter, and we accept them without complaint
2035/// (and without modifying the language options). Differences between
2036/// the states for important options cause the PCH file to be
2037/// unusable, so we emit a warning and return true to indicate that
2038/// there was an error.
2039///
2040/// \returns true if the PCH file is unacceptable, false otherwise.
2041bool PCHReader::ParseLanguageOptions(
2042 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002043 if (Listener) {
2044 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00002045
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002046 #define PARSE_LANGOPT(Option) \
2047 LangOpts.Option = Record[Idx]; \
2048 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00002049
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002050 unsigned Idx = 0;
2051 PARSE_LANGOPT(Trigraphs);
2052 PARSE_LANGOPT(BCPLComment);
2053 PARSE_LANGOPT(DollarIdents);
2054 PARSE_LANGOPT(AsmPreprocessor);
2055 PARSE_LANGOPT(GNUMode);
Chandler Carruthe03aa552010-04-17 20:17:31 +00002056 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002057 PARSE_LANGOPT(ImplicitInt);
2058 PARSE_LANGOPT(Digraphs);
2059 PARSE_LANGOPT(HexFloats);
2060 PARSE_LANGOPT(C99);
2061 PARSE_LANGOPT(Microsoft);
2062 PARSE_LANGOPT(CPlusPlus);
2063 PARSE_LANGOPT(CPlusPlus0x);
2064 PARSE_LANGOPT(CXXOperatorNames);
2065 PARSE_LANGOPT(ObjC1);
2066 PARSE_LANGOPT(ObjC2);
2067 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00002068 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian62c56022010-04-22 21:01:59 +00002069 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002070 PARSE_LANGOPT(PascalStrings);
2071 PARSE_LANGOPT(WritableStrings);
2072 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00002073 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002074 PARSE_LANGOPT(Exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +00002075 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002076 PARSE_LANGOPT(NeXTRuntime);
2077 PARSE_LANGOPT(Freestanding);
2078 PARSE_LANGOPT(NoBuiltin);
2079 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00002080 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002081 PARSE_LANGOPT(Blocks);
2082 PARSE_LANGOPT(EmitAllDecls);
2083 PARSE_LANGOPT(MathErrno);
Chris Lattner51924e512010-06-26 21:25:03 +00002084 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2085 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002086 PARSE_LANGOPT(HeinousExtensions);
2087 PARSE_LANGOPT(Optimize);
2088 PARSE_LANGOPT(OptimizeSize);
2089 PARSE_LANGOPT(Static);
2090 PARSE_LANGOPT(PICLevel);
2091 PARSE_LANGOPT(GNUInline);
2092 PARSE_LANGOPT(NoInline);
2093 PARSE_LANGOPT(AccessControl);
2094 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00002095 PARSE_LANGOPT(ShortWChar);
Chris Lattner51924e512010-06-26 21:25:03 +00002096 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2097 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbar143021e2009-09-21 04:16:19 +00002098 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattner51924e512010-06-26 21:25:03 +00002099 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002100 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00002101 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00002102 PARSE_LANGOPT(CatchUndefined);
2103 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002104 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00002105
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002106 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00002107 }
Douglas Gregor55abb232009-04-10 20:39:37 +00002108
2109 return false;
2110}
2111
Douglas Gregoraae92242010-03-19 21:51:54 +00002112void PCHReader::ReadPreprocessedEntities() {
2113 ReadDefinedMacros();
2114}
2115
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002116/// \brief Read and return the type at the given offset.
2117///
2118/// This routine actually reads the record corresponding to the type
2119/// at the given offset in the bitstream. It is a helper routine for
2120/// GetType, which deals with reading type IDs.
2121QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Sebastian Redl34522812010-07-16 17:50:48 +00002122 llvm::BitstreamCursor &DeclsCursor = Chain[0]->DeclsCursor;
2123
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002124 // Keep track of where we are in the stream, then jump back there
2125 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00002126 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002127
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002128 ReadingKindTracker ReadingKind(Read_Type, *this);
2129
Douglas Gregor1342e842009-07-06 18:54:52 +00002130 // Note that we are loading a type record.
2131 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002132
Douglas Gregor12bfa382009-10-17 00:13:19 +00002133 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002134 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00002135 unsigned Code = DeclsCursor.ReadCode();
2136 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00002137 case pch::TYPE_EXT_QUAL: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002138 if (Record.size() != 2) {
2139 Error("Incorrect encoding of extended qualifier type");
2140 return QualType();
2141 }
Douglas Gregor455b8f42009-04-15 22:00:08 +00002142 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00002143 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2144 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00002145 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002146
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002147 case pch::TYPE_COMPLEX: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002148 if (Record.size() != 1) {
2149 Error("Incorrect encoding of complex type");
2150 return QualType();
2151 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002152 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002153 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002154 }
2155
2156 case pch::TYPE_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002157 if (Record.size() != 1) {
2158 Error("Incorrect encoding of pointer type");
2159 return QualType();
2160 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002161 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002162 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002163 }
2164
2165 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002166 if (Record.size() != 1) {
2167 Error("Incorrect encoding of block pointer type");
2168 return QualType();
2169 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002170 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002171 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002172 }
2173
2174 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002175 if (Record.size() != 1) {
2176 Error("Incorrect encoding of lvalue reference type");
2177 return QualType();
2178 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002179 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002180 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002181 }
2182
2183 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002184 if (Record.size() != 1) {
2185 Error("Incorrect encoding of rvalue reference type");
2186 return QualType();
2187 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002188 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002189 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002190 }
2191
2192 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidisee776bc2010-07-02 11:55:15 +00002193 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002194 Error("Incorrect encoding of member pointer type");
2195 return QualType();
2196 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002197 QualType PointeeType = GetType(Record[0]);
2198 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002199 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002200 }
2201
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002202 case pch::TYPE_CONSTANT_ARRAY: {
2203 QualType ElementType = GetType(Record[0]);
2204 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2205 unsigned IndexTypeQuals = Record[2];
2206 unsigned Idx = 3;
2207 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00002208 return Context->getConstantArrayType(ElementType, Size,
2209 ASM, IndexTypeQuals);
2210 }
2211
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002212 case pch::TYPE_INCOMPLETE_ARRAY: {
2213 QualType ElementType = GetType(Record[0]);
2214 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2215 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00002216 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002217 }
2218
2219 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002220 QualType ElementType = GetType(Record[0]);
2221 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2222 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00002223 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2224 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002225 return Context->getVariableArrayType(ElementType, ReadExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00002226 ASM, IndexTypeQuals,
2227 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002228 }
2229
2230 case pch::TYPE_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002231 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002232 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002233 return QualType();
2234 }
2235
2236 QualType ElementType = GetType(Record[0]);
2237 unsigned NumElements = Record[1];
Chris Lattner37141f42010-06-23 06:00:24 +00002238 unsigned AltiVecSpec = Record[2];
2239 return Context->getVectorType(ElementType, NumElements,
2240 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002241 }
2242
2243 case pch::TYPE_EXT_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002244 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002245 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002246 return QualType();
2247 }
2248
2249 QualType ElementType = GetType(Record[0]);
2250 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00002251 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002252 }
2253
2254 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002255 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002256 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002257 return QualType();
2258 }
2259 QualType ResultType = GetType(Record[0]);
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002260 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002261 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002262 }
2263
2264 case pch::TYPE_FUNCTION_PROTO: {
2265 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00002266 bool NoReturn = Record[1];
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002267 unsigned RegParm = Record[2];
2268 CallingConv CallConv = (CallingConv)Record[3];
2269 unsigned Idx = 4;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002270 unsigned NumParams = Record[Idx++];
2271 llvm::SmallVector<QualType, 16> ParamTypes;
2272 for (unsigned I = 0; I != NumParams; ++I)
2273 ParamTypes.push_back(GetType(Record[Idx++]));
2274 bool isVariadic = Record[Idx++];
2275 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002276 bool hasExceptionSpec = Record[Idx++];
2277 bool hasAnyExceptionSpec = Record[Idx++];
2278 unsigned NumExceptions = Record[Idx++];
2279 llvm::SmallVector<QualType, 2> Exceptions;
2280 for (unsigned I = 0; I != NumExceptions; ++I)
2281 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00002282 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002283 isVariadic, Quals, hasExceptionSpec,
2284 hasAnyExceptionSpec, NumExceptions,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002285 Exceptions.data(),
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002286 FunctionType::ExtInfo(NoReturn, RegParm,
2287 CallConv));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002288 }
2289
John McCallb96ec562009-12-04 22:46:56 +00002290 case pch::TYPE_UNRESOLVED_USING:
2291 return Context->getTypeDeclType(
2292 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2293
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002294 case pch::TYPE_TYPEDEF: {
2295 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002296 Error("incorrect encoding of typedef type");
2297 return QualType();
2298 }
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002299 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2300 QualType Canonical = GetType(Record[1]);
2301 return Context->getTypedefType(Decl, Canonical);
2302 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002303
2304 case pch::TYPE_TYPEOF_EXPR:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002305 return Context->getTypeOfExprType(ReadExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002306
2307 case pch::TYPE_TYPEOF: {
2308 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002309 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002310 return QualType();
2311 }
2312 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002313 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002314 }
Mike Stump11289f42009-09-09 15:08:12 +00002315
Anders Carlsson81df7b82009-06-24 19:06:50 +00002316 case pch::TYPE_DECLTYPE:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002317 return Context->getDecltypeType(ReadExpr());
Anders Carlsson81df7b82009-06-24 19:06:50 +00002318
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002319 case pch::TYPE_RECORD: {
2320 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002321 Error("incorrect encoding of record type");
2322 return QualType();
2323 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002324 bool IsDependent = Record[0];
2325 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2326 T->Dependent = IsDependent;
2327 return T;
2328 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002329
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002330 case pch::TYPE_ENUM: {
2331 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002332 Error("incorrect encoding of enum type");
2333 return QualType();
2334 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002335 bool IsDependent = Record[0];
2336 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2337 T->Dependent = IsDependent;
2338 return T;
2339 }
Douglas Gregor1daeb692009-04-13 18:14:40 +00002340
John McCallfcc33b02009-09-05 00:15:47 +00002341 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002342 unsigned Idx = 0;
2343 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2344 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2345 QualType NamedType = GetType(Record[Idx++]);
2346 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCallfcc33b02009-09-05 00:15:47 +00002347 }
2348
Steve Naroffc277ad12009-07-18 15:33:26 +00002349 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00002350 unsigned Idx = 0;
2351 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002352 return Context->getObjCInterfaceType(ItfD);
2353 }
2354
2355 case pch::TYPE_OBJC_OBJECT: {
2356 unsigned Idx = 0;
2357 QualType Base = GetType(Record[Idx++]);
Chris Lattner587cbe12009-04-22 06:45:28 +00002358 unsigned NumProtos = Record[Idx++];
2359 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2360 for (unsigned I = 0; I != NumProtos; ++I)
2361 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCall8b07ec22010-05-15 11:32:37 +00002362 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00002363 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002364
Steve Narofffb4330f2009-06-17 22:40:22 +00002365 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00002366 unsigned Idx = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002367 QualType Pointee = GetType(Record[Idx++]);
2368 return Context->getObjCObjectPointerType(Pointee);
Chris Lattner6e054af2009-04-22 06:40:03 +00002369 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00002370
John McCallcebee162009-10-18 09:09:24 +00002371 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2372 unsigned Idx = 0;
2373 QualType Parm = GetType(Record[Idx++]);
2374 QualType Replacement = GetType(Record[Idx++]);
2375 return
2376 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2377 Replacement);
2378 }
John McCalle78aac42010-03-10 03:28:59 +00002379
2380 case pch::TYPE_INJECTED_CLASS_NAME: {
2381 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2382 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidisdab33c52010-07-02 11:55:20 +00002383 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2384 // for PCH reading, too much interdependencies.
2385 return
2386 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCalle78aac42010-03-10 03:28:59 +00002387 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002388
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002389 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2390 unsigned Idx = 0;
2391 unsigned Depth = Record[Idx++];
2392 unsigned Index = Record[Idx++];
2393 bool Pack = Record[Idx++];
2394 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2395 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2396 }
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002397
2398 case pch::TYPE_DEPENDENT_NAME: {
2399 unsigned Idx = 0;
2400 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2401 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2402 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidise9290952010-07-02 11:55:24 +00002403 QualType Canon = GetType(Record[Idx++]);
2404 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002405 }
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002406
2407 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2408 unsigned Idx = 0;
2409 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2410 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2411 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2412 unsigned NumArgs = Record[Idx++];
2413 llvm::SmallVector<TemplateArgument, 8> Args;
2414 Args.reserve(NumArgs);
2415 while (NumArgs--)
2416 Args.push_back(ReadTemplateArgument(Record, Idx));
2417 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2418 Args.size(), Args.data());
2419 }
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00002420
2421 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2422 unsigned Idx = 0;
2423
2424 // ArrayType
2425 QualType ElementType = GetType(Record[Idx++]);
2426 ArrayType::ArraySizeModifier ASM
2427 = (ArrayType::ArraySizeModifier)Record[Idx++];
2428 unsigned IndexTypeQuals = Record[Idx++];
2429
2430 // DependentSizedArrayType
2431 Expr *NumElts = ReadExpr();
2432 SourceRange Brackets = ReadSourceRange(Record, Idx);
2433
2434 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2435 IndexTypeQuals, Brackets);
2436 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002437
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002438 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2439 unsigned Idx = 0;
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002440 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002441 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002442 llvm::SmallVector<TemplateArgument, 8> Args;
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00002443 ReadTemplateArgumentList(Args, Record, Idx);
2444 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002445 QualType T;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002446 if (Canon.isNull())
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002447 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2448 Args.size());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002449 else
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002450 T = Context->getTemplateSpecializationType(Name, Args.data(),
2451 Args.size(), Canon);
2452 T->Dependent = IsDependent;
2453 return T;
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002454 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002455 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002456 // Suppress a GCC warning
2457 return QualType();
2458}
2459
John McCall8f115c62009-10-16 21:56:05 +00002460namespace {
2461
2462class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2463 PCHReader &Reader;
2464 const PCHReader::RecordData &Record;
2465 unsigned &Idx;
2466
2467public:
2468 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2469 unsigned &Idx)
2470 : Reader(Reader), Record(Record), Idx(Idx) { }
2471
John McCall17001972009-10-18 01:05:36 +00002472 // We want compile-time assurance that we've enumerated all of
2473 // these, so unfortunately we have to declare them first, then
2474 // define them out-of-line.
2475#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002476#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002477 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002478#include "clang/AST/TypeLocNodes.def"
2479
John McCall17001972009-10-18 01:05:36 +00002480 void VisitFunctionTypeLoc(FunctionTypeLoc);
2481 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002482};
2483
2484}
2485
John McCall17001972009-10-18 01:05:36 +00002486void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002487 // nothing to do
2488}
John McCall17001972009-10-18 01:05:36 +00002489void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +00002490 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2491 if (TL.needsExtraLocalData()) {
2492 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2493 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2494 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2495 TL.setModeAttr(Record[Idx++]);
2496 }
John McCall8f115c62009-10-16 21:56:05 +00002497}
John McCall17001972009-10-18 01:05:36 +00002498void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2499 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002500}
John McCall17001972009-10-18 01:05:36 +00002501void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2502 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002503}
John McCall17001972009-10-18 01:05:36 +00002504void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2505 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002506}
John McCall17001972009-10-18 01:05:36 +00002507void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2508 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002509}
John McCall17001972009-10-18 01:05:36 +00002510void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2511 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002512}
John McCall17001972009-10-18 01:05:36 +00002513void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2514 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002515}
John McCall17001972009-10-18 01:05:36 +00002516void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2517 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2518 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002519 if (Record[Idx++])
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002520 TL.setSizeExpr(Reader.ReadExpr());
Douglas Gregor12bfa382009-10-17 00:13:19 +00002521 else
John McCall17001972009-10-18 01:05:36 +00002522 TL.setSizeExpr(0);
2523}
2524void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2525 VisitArrayTypeLoc(TL);
2526}
2527void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2528 VisitArrayTypeLoc(TL);
2529}
2530void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2531 VisitArrayTypeLoc(TL);
2532}
2533void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2534 DependentSizedArrayTypeLoc TL) {
2535 VisitArrayTypeLoc(TL);
2536}
2537void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2538 DependentSizedExtVectorTypeLoc TL) {
2539 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2540}
2541void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2542 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2543}
2544void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2545 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2546}
2547void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2548 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2549 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2550 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002551 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002552 }
2553}
2554void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2555 VisitFunctionTypeLoc(TL);
2556}
2557void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2558 VisitFunctionTypeLoc(TL);
2559}
John McCallb96ec562009-12-04 22:46:56 +00002560void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2561 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2562}
John McCall17001972009-10-18 01:05:36 +00002563void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2564 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2565}
2566void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002567 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2568 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2569 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002570}
2571void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002572 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2573 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2574 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2575 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002576}
2577void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2578 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2579}
2580void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2581 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2582}
2583void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2584 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2585}
John McCall17001972009-10-18 01:05:36 +00002586void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2587 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2588}
John McCallcebee162009-10-18 09:09:24 +00002589void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2590 SubstTemplateTypeParmTypeLoc TL) {
2591 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2592}
John McCall17001972009-10-18 01:05:36 +00002593void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2594 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002595 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2596 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2597 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2598 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2599 TL.setArgLocInfo(i,
2600 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2601 Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002602}
Abramo Bagnara6150c882010-05-11 21:36:43 +00002603void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002604 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2605 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002606}
John McCalle78aac42010-03-10 03:28:59 +00002607void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2608 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2609}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002610void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002611 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2612 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002613 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2614}
John McCallc392f372010-06-11 00:33:02 +00002615void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2616 DependentTemplateSpecializationTypeLoc TL) {
2617 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2618 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2619 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2620 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2621 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2622 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2623 TL.setArgLocInfo(I,
2624 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
2625 Record, Idx));
2626}
John McCall17001972009-10-18 01:05:36 +00002627void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2628 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002629}
2630void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2631 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall17001972009-10-18 01:05:36 +00002632 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2633 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2634 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2635 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002636}
John McCallfc93cf92009-10-22 22:37:11 +00002637void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2638 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallfc93cf92009-10-22 22:37:11 +00002639}
John McCall8f115c62009-10-16 21:56:05 +00002640
John McCallbcd03502009-12-07 02:54:59 +00002641TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002642 unsigned &Idx) {
2643 QualType InfoTy = GetType(Record[Idx++]);
2644 if (InfoTy.isNull())
2645 return 0;
2646
John McCallbcd03502009-12-07 02:54:59 +00002647 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCall8f115c62009-10-16 21:56:05 +00002648 TypeLocReader TLR(*this, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002649 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002650 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002651 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002652}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002653
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002654QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002655 unsigned FastQuals = ID & Qualifiers::FastMask;
2656 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002657
2658 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2659 QualType T;
2660 switch ((pch::PredefinedTypeIDs)Index) {
2661 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002662 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2663 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002664
2665 case pch::PREDEF_TYPE_CHAR_U_ID:
2666 case pch::PREDEF_TYPE_CHAR_S_ID:
2667 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002668 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002669 break;
2670
Chris Lattner8575daa2009-04-27 21:45:14 +00002671 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2672 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2673 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2674 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2675 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002676 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002677 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2678 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2679 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2680 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2681 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2682 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002683 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002684 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2685 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2686 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2687 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2688 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002689 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002690 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2691 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002692 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2693 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002694 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002695 }
2696
2697 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002698 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002699 }
2700
2701 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002702 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl409183f2010-07-14 20:26:45 +00002703 if (TypesLoaded[Index].isNull()) {
Sebastian Redl9e687992010-07-19 22:06:55 +00002704 TypesLoaded[Index] = ReadTypeRecord(Chain[0]->TypeOffsets[Index]);
Sebastian Redl409183f2010-07-14 20:26:45 +00002705 TypesLoaded[Index]->setFromPCH();
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002706 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002707 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2708 TypesLoaded[Index]);
Sebastian Redl409183f2010-07-14 20:26:45 +00002709 }
Mike Stump11289f42009-09-09 15:08:12 +00002710
John McCall8ccfcb52009-09-24 19:53:00 +00002711 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002712}
2713
John McCall0ad16662009-10-29 08:12:44 +00002714TemplateArgumentLocInfo
2715PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2716 const RecordData &Record,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002717 unsigned &Index) {
John McCall0ad16662009-10-29 08:12:44 +00002718 switch (Kind) {
2719 case TemplateArgument::Expression:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002720 return ReadExpr();
John McCall0ad16662009-10-29 08:12:44 +00002721 case TemplateArgument::Type:
John McCallbcd03502009-12-07 02:54:59 +00002722 return GetTypeSourceInfo(Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002723 case TemplateArgument::Template: {
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002724 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2725 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2726 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002727 }
John McCall0ad16662009-10-29 08:12:44 +00002728 case TemplateArgument::Null:
2729 case TemplateArgument::Integral:
2730 case TemplateArgument::Declaration:
2731 case TemplateArgument::Pack:
2732 return TemplateArgumentLocInfo();
2733 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002734 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002735 return TemplateArgumentLocInfo();
2736}
2737
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002738TemplateArgumentLoc
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002739PCHReader::ReadTemplateArgumentLoc(const RecordData &Record, unsigned &Index) {
2740 TemplateArgument Arg = ReadTemplateArgument(Record, Index);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002741
2742 if (Arg.getKind() == TemplateArgument::Expression) {
2743 if (Record[Index++]) // bool InfoHasSameExpr.
2744 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2745 }
2746 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002747 Record, Index));
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00002748}
2749
John McCall75b960e2010-06-01 09:23:16 +00002750Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2751 return GetDecl(ID);
2752}
2753
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002754TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002755 if (!DeclsLoaded[0]) {
Sebastian Redl9e687992010-07-19 22:06:55 +00002756 ReadDeclRecord(Chain[0]->DeclOffsets[0], 0);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002757 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002758 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002759 }
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002760
2761 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2762}
2763
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002764Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002765 if (ID == 0)
2766 return 0;
2767
Douglas Gregor745ed142009-04-25 18:35:21 +00002768 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002769 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002770 return 0;
2771 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002772
Douglas Gregor745ed142009-04-25 18:35:21 +00002773 unsigned Index = ID - 1;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002774 if (!DeclsLoaded[Index]) {
Sebastian Redl9e687992010-07-19 22:06:55 +00002775 ReadDeclRecord(Chain[0]->DeclOffsets[Index], Index);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002776 if (DeserializationListener)
2777 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2778 }
Douglas Gregor745ed142009-04-25 18:35:21 +00002779
2780 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002781}
2782
Chris Lattner9c28af02009-04-27 05:46:25 +00002783/// \brief Resolve the offset of a statement into a statement.
2784///
2785/// This operation will read a new statement from the external
2786/// source each time it is called, and is meant to be used via a
2787/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall75b960e2010-06-01 09:23:16 +00002788Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002789 // Since we know tha this statement is part of a decl, make sure to use the
2790 // decl cursor to read it.
Sebastian Redl34522812010-07-16 17:50:48 +00002791 Chain[0]->DeclsCursor.JumpToBit(Offset);
2792 return ReadStmtFromStream(Chain[0]->DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002793}
2794
John McCall75b960e2010-06-01 09:23:16 +00002795bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2796 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002797 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002798 "DeclContext has no lexical decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002799
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002800 uint64_t Offset = DeclContextOffsets[DC].first;
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002801 if (Offset == 0) {
2802 Error("DeclContext has no lexical decls in storage");
2803 return true;
2804 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002805
Sebastian Redl34522812010-07-16 17:50:48 +00002806 llvm::BitstreamCursor &DeclsCursor = Chain[0]->DeclsCursor;
2807
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002808 // Keep track of where we are in the stream, then jump back there
2809 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002810 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002811
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002812 // Load the record containing all of the declarations lexically in
2813 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002814 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002815 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002816 unsigned Code = DeclsCursor.ReadCode();
2817 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002818 if (RecCode != pch::DECL_CONTEXT_LEXICAL) {
2819 Error("Expected lexical block");
2820 return true;
2821 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002822
2823 // Load all of the declaration IDs
John McCall75b960e2010-06-01 09:23:16 +00002824 for (RecordData::iterator I = Record.begin(), E = Record.end(); I != E; ++I)
2825 Decls.push_back(GetDecl(*I));
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002826 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002827 return false;
2828}
2829
John McCall75b960e2010-06-01 09:23:16 +00002830DeclContext::lookup_result
2831PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2832 DeclarationName Name) {
Mike Stump11289f42009-09-09 15:08:12 +00002833 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002834 "DeclContext has no visible decls in storage");
2835 uint64_t Offset = DeclContextOffsets[DC].second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002836 if (Offset == 0) {
2837 Error("DeclContext has no visible decls in storage");
John McCall75b960e2010-06-01 09:23:16 +00002838 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2839 DeclContext::lookup_iterator());
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002840 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002841
Sebastian Redl34522812010-07-16 17:50:48 +00002842 llvm::BitstreamCursor &DeclsCursor = Chain[0]->DeclsCursor;
2843
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002844 // Keep track of where we are in the stream, then jump back there
2845 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002846 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002847
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002848 // Load the record containing all of the declarations visible in
2849 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002850 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002851 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002852 unsigned Code = DeclsCursor.ReadCode();
2853 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002854 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2855 Error("Expected visible block");
John McCall75b960e2010-06-01 09:23:16 +00002856 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2857 DeclContext::lookup_iterator());
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002858 }
2859
John McCall75b960e2010-06-01 09:23:16 +00002860 llvm::SmallVector<VisibleDeclaration, 64> Decls;
2861 if (Record.empty()) {
2862 SetExternalVisibleDecls(DC, Decls);
2863 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2864 DeclContext::lookup_iterator());
2865 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002866
2867 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002868 while (Idx < Record.size()) {
2869 Decls.push_back(VisibleDeclaration());
2870 Decls.back().Name = ReadDeclarationName(Record, Idx);
2871
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002872 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002873 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002874 LoadedDecls.reserve(Size);
2875 for (unsigned I = 0; I < Size; ++I)
2876 LoadedDecls.push_back(Record[Idx++]);
2877 }
2878
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002879 ++NumVisibleDeclContextsRead;
John McCall75b960e2010-06-01 09:23:16 +00002880
2881 SetExternalVisibleDecls(DC, Decls);
2882 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002883}
2884
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00002885void PCHReader::PassInterestingDeclsToConsumer() {
2886 assert(Consumer);
2887 while (!InterestingDecls.empty()) {
2888 DeclGroupRef DG(InterestingDecls.front());
2889 InterestingDecls.pop_front();
2890 Consumer->HandleTopLevelDecl(DG);
2891 }
2892}
2893
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002894void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002895 this->Consumer = Consumer;
2896
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002897 if (!Consumer)
2898 return;
2899
2900 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00002901 // Force deserialization of this decl, which will cause it to be queued for
2902 // passing to the consumer.
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002903 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002904 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002905
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00002906 PassInterestingDeclsToConsumer();
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002907}
2908
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002909void PCHReader::PrintStats() {
2910 std::fprintf(stderr, "*** PCH Statistics:\n");
2911
Mike Stump11289f42009-09-09 15:08:12 +00002912 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002913 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00002914 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00002915 unsigned NumDeclsLoaded
2916 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2917 (Decl *)0);
2918 unsigned NumIdentifiersLoaded
2919 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2920 IdentifiersLoaded.end(),
2921 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002922 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002923 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2924 SelectorsLoaded.end(),
2925 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002926
Douglas Gregorc5046832009-04-27 18:38:38 +00002927 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2928 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002929 if (TotalNumSLocEntries)
2930 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2931 NumSLocEntriesRead, TotalNumSLocEntries,
2932 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002933 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002934 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002935 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2936 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2937 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002938 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002939 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2940 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002941 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002942 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002943 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2944 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002945 if (TotalNumSelectors)
2946 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2947 NumSelectorsLoaded, TotalNumSelectors,
2948 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2949 if (TotalNumStatements)
2950 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2951 NumStatementsRead, TotalNumStatements,
2952 ((float)NumStatementsRead/TotalNumStatements * 100));
2953 if (TotalNumMacros)
2954 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2955 NumMacrosRead, TotalNumMacros,
2956 ((float)NumMacrosRead/TotalNumMacros * 100));
2957 if (TotalLexicalDeclContexts)
2958 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2959 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2960 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2961 * 100));
2962 if (TotalVisibleDeclContexts)
2963 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2964 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2965 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2966 * 100));
2967 if (TotalSelectorsInMethodPool) {
2968 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2969 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2970 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2971 * 100));
2972 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2973 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002974 std::fprintf(stderr, "\n");
2975}
2976
Douglas Gregora868bbd2009-04-21 22:25:48 +00002977void PCHReader::InitializeSema(Sema &S) {
2978 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002979 S.ExternalSource = this;
2980
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002981 // Makes sure any declarations that were deserialized "too early"
2982 // still get added to the identifier's declaration chains.
2983 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2984 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2985 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002986 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002987 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002988
2989 // If there were any tentative definitions, deserialize them and add
Sebastian Redl35351a92010-01-31 22:27:38 +00002990 // them to Sema's list of tentative definitions.
Douglas Gregord4df8652009-04-22 22:02:47 +00002991 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2992 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redl35351a92010-01-31 22:27:38 +00002993 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregord4df8652009-04-22 22:02:47 +00002994 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00002995
Tanya Lattner90073802010-02-12 00:07:30 +00002996 // If there were any unused static functions, deserialize them and add to
2997 // Sema's list of unused static functions.
2998 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
2999 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3000 SemaObj->UnusedStaticFuncs.push_back(FD);
3001 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00003002
3003 // If there were any locally-scoped external declarations,
3004 // deserialize them and add them to Sema's table of locally-scoped
3005 // external declarations.
3006 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3007 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3008 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3009 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00003010
3011 // If there were any ext_vector type declarations, deserialize them
3012 // and add them to Sema's vector of such declarations.
3013 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3014 SemaObj->ExtVectorDecls.push_back(
3015 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00003016
3017 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3018 // Can we cut them down before writing them ?
3019
3020 // If there were any VTable uses, deserialize the information and add it
3021 // to Sema's vector and map of VTable uses.
3022 unsigned Idx = 0;
3023 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3024 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3025 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3026 bool DefinitionRequired = VTableUses[Idx++];
3027 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3028 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3029 }
3030
3031 // If there were any dynamic classes declarations, deserialize them
3032 // and add them to Sema's vector of such declarations.
3033 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3034 SemaObj->DynamicClasses.push_back(
3035 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003036}
3037
3038IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
3039 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00003040 PCHIdentifierLookupTable *IdTable
Sebastian Redl393f8b72010-07-19 20:52:06 +00003041 = (PCHIdentifierLookupTable *)Chain[0]->IdentifierLookupTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003042 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3043 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3044 if (Pos == IdTable->end())
3045 return 0;
3046
3047 // Dereferencing the iterator has the effect of building the
3048 // IdentifierInfo node and populating it with the various
3049 // declarations it needs.
3050 return *Pos;
3051}
3052
Mike Stump11289f42009-09-09 15:08:12 +00003053std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00003054PCHReader::ReadMethodPool(Selector Sel) {
3055 if (!MethodPoolLookupTable)
3056 return std::pair<ObjCMethodList, ObjCMethodList>();
3057
3058 // Try to find this selector within our on-disk hash table.
3059 PCHMethodPoolLookupTable *PoolTable
3060 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
3061 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00003062 if (Pos == PoolTable->end()) {
3063 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003064 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00003065 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003066
Douglas Gregor95c13f52009-04-25 17:48:32 +00003067 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003068 return *Pos;
3069}
3070
Douglas Gregor0e149972009-04-25 19:10:14 +00003071void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00003072 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003073 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00003074 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003075}
3076
Douglas Gregor1342e842009-07-06 18:54:52 +00003077/// \brief Set the globally-visible declarations associated with the given
3078/// identifier.
3079///
3080/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00003081/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00003082/// them.
3083///
3084/// \param II an IdentifierInfo that refers to one or more globally-visible
3085/// declarations.
3086///
3087/// \param DeclIDs the set of declaration IDs with the name @p II that are
3088/// visible at global scope.
3089///
3090/// \param Nonrecursive should be true to indicate that the caller knows that
3091/// this call is non-recursive, and therefore the globally-visible declarations
3092/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00003093void
3094PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00003095 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3096 bool Nonrecursive) {
3097 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
3098 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3099 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3100 PII.II = II;
3101 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3102 PII.DeclIDs.push_back(DeclIDs[I]);
3103 return;
3104 }
Mike Stump11289f42009-09-09 15:08:12 +00003105
Douglas Gregor1342e842009-07-06 18:54:52 +00003106 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3107 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3108 if (SemaObj) {
3109 // Introduce this declaration into the translation-unit scope
3110 // and add it to the declaration chain for this identifier, so
3111 // that (unqualified) name lookup will find it.
3112 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3113 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3114 } else {
3115 // Queue this declaration so that it will be added to the
3116 // translation unit scope and identifier's declaration chain
3117 // once a Sema object is known.
3118 PreloadedDecls.push_back(D);
3119 }
3120 }
3121}
3122
Chris Lattnerc523d8e2009-04-11 21:15:38 +00003123IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003124 if (ID == 0)
3125 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003126
Sebastian Redl393f8b72010-07-19 20:52:06 +00003127 if (!Chain[0]->IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003128 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003129 return 0;
3130 }
Mike Stump11289f42009-09-09 15:08:12 +00003131
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003132 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00003133 if (!IdentifiersLoaded[ID - 1]) {
3134 uint32_t Offset = IdentifierOffsets[ID - 1];
Sebastian Redl393f8b72010-07-19 20:52:06 +00003135 const char *Str = Chain[0]->IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00003136
Douglas Gregorab4df582009-04-28 20:01:51 +00003137 // All of the strings in the PCH file are preceded by a 16-bit
3138 // length. Extract that 16-bit length to avoid having to execute
3139 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00003140 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3141 // unsigned integers. This is important to avoid integer overflow when
3142 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00003143 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00003144 unsigned StrLen = (((unsigned) StrLenPtr[0])
3145 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00003146 IdentifiersLoaded[ID - 1]
Kovarththanan Rajaratnama3b09592010-03-12 10:32:27 +00003147 = &PP->getIdentifierTable().get(Str, StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003148 }
Mike Stump11289f42009-09-09 15:08:12 +00003149
Douglas Gregor0e149972009-04-25 19:10:14 +00003150 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003151}
3152
Douglas Gregor258ae542009-04-27 06:38:32 +00003153void PCHReader::ReadSLocEntry(unsigned ID) {
3154 ReadSLocEntryRecord(ID);
3155}
3156
Steve Naroff2ddea052009-04-23 10:39:46 +00003157Selector PCHReader::DecodeSelector(unsigned ID) {
3158 if (ID == 0)
3159 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00003160
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003161 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00003162 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00003163
3164 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003165 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00003166 return Selector();
3167 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003168
3169 unsigned Index = ID - 1;
3170 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
3171 // Load this selector from the selector table.
3172 // FIXME: endianness portability issues with SelectorOffsets table
3173 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003174 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00003175 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
3176 }
3177
3178 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00003179}
3180
John McCall75b960e2010-06-01 09:23:16 +00003181Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003182 return DecodeSelector(ID);
3183}
3184
John McCall75b960e2010-06-01 09:23:16 +00003185uint32_t PCHReader::GetNumExternalSelectors() {
Douglas Gregord720daf2010-04-06 17:30:22 +00003186 return TotalNumSelectors + 1;
3187}
3188
Mike Stump11289f42009-09-09 15:08:12 +00003189DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003190PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3191 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3192 switch (Kind) {
3193 case DeclarationName::Identifier:
3194 return DeclarationName(GetIdentifierInfo(Record, Idx));
3195
3196 case DeclarationName::ObjCZeroArgSelector:
3197 case DeclarationName::ObjCOneArgSelector:
3198 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00003199 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003200
3201 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003202 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003203 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003204
3205 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003206 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003207 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003208
3209 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003210 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003211 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003212
3213 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003214 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003215 (OverloadedOperatorKind)Record[Idx++]);
3216
Alexis Hunt3d221f22009-11-29 07:34:05 +00003217 case DeclarationName::CXXLiteralOperatorName:
3218 return Context->DeclarationNames.getCXXLiteralOperatorName(
3219 GetIdentifierInfo(Record, Idx));
3220
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003221 case DeclarationName::CXXUsingDirective:
3222 return DeclarationName::getUsingDirectiveName();
3223 }
3224
3225 // Required to silence GCC warning
3226 return DeclarationName();
3227}
Douglas Gregor55abb232009-04-10 20:39:37 +00003228
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003229TemplateName
3230PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3231 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3232 switch (Kind) {
3233 case TemplateName::Template:
3234 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3235
3236 case TemplateName::OverloadedTemplate: {
3237 unsigned size = Record[Idx++];
3238 UnresolvedSet<8> Decls;
3239 while (size--)
3240 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3241
3242 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3243 }
3244
3245 case TemplateName::QualifiedTemplate: {
3246 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3247 bool hasTemplKeyword = Record[Idx++];
3248 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3249 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3250 }
3251
3252 case TemplateName::DependentTemplate: {
3253 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3254 if (Record[Idx++]) // isIdentifier
3255 return Context->getDependentTemplateName(NNS,
3256 GetIdentifierInfo(Record, Idx));
3257 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00003258 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003259 }
3260 }
3261
3262 assert(0 && "Unhandled template name kind!");
3263 return TemplateName();
3264}
3265
3266TemplateArgument
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00003267PCHReader::ReadTemplateArgument(const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003268 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3269 case TemplateArgument::Null:
3270 return TemplateArgument();
3271 case TemplateArgument::Type:
3272 return TemplateArgument(GetType(Record[Idx++]));
3273 case TemplateArgument::Declaration:
3274 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidis0b0369a2010-06-28 09:31:34 +00003275 case TemplateArgument::Integral: {
3276 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3277 QualType T = GetType(Record[Idx++]);
3278 return TemplateArgument(Value, T);
3279 }
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003280 case TemplateArgument::Template:
3281 return TemplateArgument(ReadTemplateName(Record, Idx));
3282 case TemplateArgument::Expression:
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00003283 return TemplateArgument(ReadExpr());
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003284 case TemplateArgument::Pack: {
3285 unsigned NumArgs = Record[Idx++];
3286 llvm::SmallVector<TemplateArgument, 8> Args;
3287 Args.reserve(NumArgs);
3288 while (NumArgs--)
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00003289 Args.push_back(ReadTemplateArgument(Record, Idx));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003290 TemplateArgument TemplArg;
3291 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3292 return TemplArg;
3293 }
3294 }
3295
3296 assert(0 && "Unhandled template argument kind!");
3297 return TemplateArgument();
3298}
3299
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003300TemplateParameterList *
3301PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3302 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3303 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3304 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3305
3306 unsigned NumParams = Record[Idx++];
3307 llvm::SmallVector<NamedDecl *, 16> Params;
3308 Params.reserve(NumParams);
3309 while (NumParams--)
3310 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3311
3312 TemplateParameterList* TemplateParams =
3313 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3314 Params.data(), Params.size(), RAngleLoc);
3315 return TemplateParams;
3316}
3317
3318void
3319PCHReader::
3320ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
3321 const RecordData &Record, unsigned &Idx) {
3322 unsigned NumTemplateArgs = Record[Idx++];
3323 TemplArgs.reserve(NumTemplateArgs);
3324 while (NumTemplateArgs--)
3325 TemplArgs.push_back(ReadTemplateArgument(Record, Idx));
3326}
3327
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00003328/// \brief Read a UnresolvedSet structure.
3329void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3330 const RecordData &Record, unsigned &Idx) {
3331 unsigned NumDecls = Record[Idx++];
3332 while (NumDecls--) {
3333 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3334 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3335 Set.addDecl(D, AS);
3336 }
3337}
3338
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003339CXXBaseSpecifier
3340PCHReader::ReadCXXBaseSpecifier(const RecordData &Record, unsigned &Idx) {
3341 bool isVirtual = static_cast<bool>(Record[Idx++]);
3342 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3343 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
3344 QualType T = GetType(Record[Idx++]);
3345 SourceRange Range = ReadSourceRange(Record, Idx);
3346 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, T);
3347}
3348
Chris Lattnerca025db2010-05-07 21:43:38 +00003349NestedNameSpecifier *
3350PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3351 unsigned N = Record[Idx++];
3352 NestedNameSpecifier *NNS = 0, *Prev = 0;
3353 for (unsigned I = 0; I != N; ++I) {
3354 NestedNameSpecifier::SpecifierKind Kind
3355 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3356 switch (Kind) {
3357 case NestedNameSpecifier::Identifier: {
3358 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3359 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3360 break;
3361 }
3362
3363 case NestedNameSpecifier::Namespace: {
3364 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3365 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3366 break;
3367 }
3368
3369 case NestedNameSpecifier::TypeSpec:
3370 case NestedNameSpecifier::TypeSpecWithTemplate: {
3371 Type *T = GetType(Record[Idx++]).getTypePtr();
3372 bool Template = Record[Idx++];
3373 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3374 break;
3375 }
3376
3377 case NestedNameSpecifier::Global: {
3378 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3379 // No associated value, and there can't be a prefix.
3380 break;
3381 }
Chris Lattnerca025db2010-05-07 21:43:38 +00003382 }
Argyrios Kyrtzidisad65c692010-07-07 15:46:30 +00003383 Prev = NNS;
Chris Lattnerca025db2010-05-07 21:43:38 +00003384 }
3385 return NNS;
3386}
3387
3388SourceRange
3389PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar6d3bc082010-06-02 15:47:10 +00003390 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3391 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3392 return SourceRange(beg, end);
Chris Lattnerca025db2010-05-07 21:43:38 +00003393}
3394
Douglas Gregor1daeb692009-04-13 18:14:40 +00003395/// \brief Read an integral value
3396llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3397 unsigned BitWidth = Record[Idx++];
3398 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3399 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3400 Idx += NumWords;
3401 return Result;
3402}
3403
3404/// \brief Read a signed integral value
3405llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3406 bool isUnsigned = Record[Idx++];
3407 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3408}
3409
Douglas Gregore0a3a512009-04-14 21:55:33 +00003410/// \brief Read a floating-point value
3411llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00003412 return llvm::APFloat(ReadAPInt(Record, Idx));
3413}
3414
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003415// \brief Read a string
3416std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3417 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00003418 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003419 Idx += Len;
3420 return Result;
3421}
3422
Chris Lattnercba86142010-05-10 00:25:06 +00003423CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3424 unsigned &Idx) {
3425 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3426 return CXXTemporary::Create(*Context, Decl);
3427}
3428
Douglas Gregor55abb232009-04-10 20:39:37 +00003429DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00003430 return Diag(SourceLocation(), DiagID);
3431}
3432
3433DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003434 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00003435}
Douglas Gregora9af1d12009-04-17 00:04:06 +00003436
Douglas Gregora868bbd2009-04-21 22:25:48 +00003437/// \brief Retrieve the identifier table associated with the
3438/// preprocessor.
3439IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003440 assert(PP && "Forgot to set Preprocessor ?");
3441 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00003442}
3443
Douglas Gregora9af1d12009-04-17 00:04:06 +00003444/// \brief Record that the given ID maps to the given switch-case
3445/// statement.
3446void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3447 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3448 SwitchCaseStmts[ID] = SC;
3449}
3450
3451/// \brief Retrieve the switch-case statement with the given ID.
3452SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3453 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3454 return SwitchCaseStmts[ID];
3455}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003456
3457/// \brief Record that the given label statement has been
3458/// deserialized and has the given ID.
3459void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00003460 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003461 "Deserialized label twice");
3462 LabelStmts[ID] = S;
3463
3464 // If we've already seen any goto statements that point to this
3465 // label, resolve them now.
3466 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3467 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3468 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3469 Goto->second->setLabel(S);
3470 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00003471
3472 // If we've already seen any address-label statements that point to
3473 // this label, resolve them now.
3474 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00003475 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00003476 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00003477 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00003478 AddrLabel != AddrLabels.second; ++AddrLabel)
3479 AddrLabel->second->setLabel(S);
3480 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003481}
3482
3483/// \brief Set the label of the given statement to the label
3484/// identified by ID.
3485///
3486/// Depending on the order in which the label and other statements
3487/// referencing that label occur, this operation may complete
3488/// immediately (updating the statement) or it may queue the
3489/// statement to be back-patched later.
3490void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3491 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3492 if (Label != LabelStmts.end()) {
3493 // We've already seen this label, so set the label of the goto and
3494 // we're done.
3495 S->setLabel(Label->second);
3496 } else {
3497 // We haven't seen this label yet, so add this goto to the set of
3498 // unresolved goto statements.
3499 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3500 }
3501}
Douglas Gregor779d8652009-04-17 18:58:21 +00003502
3503/// \brief Set the label of the given expression to the label
3504/// identified by ID.
3505///
3506/// Depending on the order in which the label and other statements
3507/// referencing that label occur, this operation may complete
3508/// immediately (updating the statement) or it may queue the
3509/// statement to be back-patched later.
3510void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3511 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3512 if (Label != LabelStmts.end()) {
3513 // We've already seen this label, so set the label of the
3514 // label-address expression and we're done.
3515 S->setLabel(Label->second);
3516 } else {
3517 // We haven't seen this label yet, so add this label-address
3518 // expression to the set of unresolved label-address expressions.
3519 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3520 }
3521}
Douglas Gregor1342e842009-07-06 18:54:52 +00003522
3523
Mike Stump11289f42009-09-09 15:08:12 +00003524PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00003525 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
3526 Reader.CurrentlyLoadingTypeOrDecl = this;
3527}
3528
3529PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
3530 if (!Parent) {
3531 // If any identifiers with corresponding top-level declarations have
3532 // been loaded, load those declarations now.
3533 while (!Reader.PendingIdentifierInfos.empty()) {
3534 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
3535 Reader.PendingIdentifierInfos.front().DeclIDs,
3536 true);
3537 Reader.PendingIdentifierInfos.pop_front();
3538 }
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003539
3540 // We are not in recursive loading, so it's safe to pass the "interesting"
3541 // decls to the consumer.
3542 if (Reader.Consumer)
3543 Reader.PassInterestingDeclsToConsumer();
Douglas Gregor1342e842009-07-06 18:54:52 +00003544 }
3545
Mike Stump11289f42009-09-09 15:08:12 +00003546 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00003547}