blob: 35909a05556605cd71928a529690bdba9ed0cb79 [file] [log] [blame]
Douglas Gregor2cf26342009-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 Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Sebastian Redl30c514c2010-07-14 23:45:08 +000016#include "clang/Frontend/PCHDeserializationListener.h"
Daniel Dunbarc7162932009-11-11 23:58:53 +000017#include "clang/Frontend/Utils.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000018#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000021#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000023#include "clang/AST/TypeLocVisitor.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000024#include "clang/Lex/MacroInfo.h"
Douglas Gregor6a5a23f2010-03-19 21:51:54 +000025#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000026#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000027#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000028#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000029#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000030#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000031#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000032#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000033#include "clang/Basic/Version.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000035#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000036#include "llvm/Support/MemoryBuffer.h"
John McCall833ca992009-10-29 08:12:44 +000037#include "llvm/Support/ErrorHandling.h"
Daniel Dunbard5b21972009-11-18 19:50:41 +000038#include "llvm/System/Path.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000039#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000040#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000041#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000042#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000043using namespace clang;
44
45//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-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 Carrutheb5d7b72010-04-17 20:17:31 +000066 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
Argyrios Kyrtzidis11e51102009-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 Jahanian412e7982010-02-09 19:31:38 +000078 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +000079 PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
80 diag::warn_pch_no_constant_cfstrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000081 PARSE_LANGOPT_BENIGN(PascalStrings);
82 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000083 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000084 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000085 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000086 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +000087 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Argyrios Kyrtzidis11e51102009-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 Stump1eb44332009-09-09 15:08:12 +000091 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000092 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000093 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-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 Lattnera4d71452010-06-26 21:25:03 +000097 PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
Mike Stump1eb44332009-09-09 15:08:12 +000098 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-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 Thompsona6fda122009-11-05 20:14:16 +0000115 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000116 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000117 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000118 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
119 return true;
120 }
121 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000122 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
123 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000124 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000125 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stump9c276ae2009-12-12 01:27:46 +0000126 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000127 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Douglas Gregora0068fc2010-07-09 17:35:33 +0000128 PARSE_LANGOPT_BENIGN(SpellChecking);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +0000129#undef PARSE_LANGOPT_IMPORTANT
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000130#undef PARSE_LANGOPT_BENIGN
131
132 return false;
133}
134
Daniel Dunbardc3c0d22009-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000142}
143
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000144struct EmptyStringRef {
Benjamin Kramerec1b1cc2010-07-14 23:19:41 +0000145 bool operator ()(llvm::StringRef r) const { return r.empty(); }
Sebastian Redl7e9ad8b2010-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 Dunbarc76c9e02010-07-16 00:00:11 +0000173 (void) RN;
Sebastian Redl7e9ad8b2010-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 Dunbar7b5a1212009-11-11 05:29:04 +0000225 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000226 std::string &SuggestedPredefines) {
Daniel Dunbarc7162932009-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 Dunbar7b5a1212009-11-11 05:29:04 +0000231 llvm::SmallString<256> PCHInclude;
232 PCHInclude += "#include \"";
Daniel Dunbarc7162932009-11-11 23:58:53 +0000233 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar7b5a1212009-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 Kremenekd5d7b3f2010-03-18 00:56:54 +0000238 if (Left == PP.getPredefines()) {
239 Error("Missing PCH include entry!");
240 return true;
241 }
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000242
Sebastian Redl7e9ad8b2010-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000252 return false;
253
254 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Daniel Dunbar10014aa2009-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 Dunbare6750492009-11-13 16:46:11 +0000258 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
Sebastian Redl7e9ad8b2010-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 Dunbare6750492009-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000265
Daniel Dunbar4d5936a2009-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000268 std::sort(CmdLineLines.begin(), CmdLineLines.end());
269 std::sort(PCHLines.begin(), PCHLines.end());
270
Daniel Dunbar4d5936a2009-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 Kyrtzidis11e51102009-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 Dunbar4d5936a2009-11-11 05:26:28 +0000281 llvm::StringRef Missing = MissingPredefines[I];
282 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000283 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
284 return true;
285 }
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000287 // This is a macro definition. Determine the name of the macro we're
288 // defining.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000289 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000290 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-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 Dunbar4d5936a2009-11-11 05:26:28 +0000294 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000295
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000296 // Determine whether this macro was given a different definition on the
297 // command line.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000298 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000299 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbare6750492009-11-13 16:46:11 +0000300 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000301 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
302 MacroDefStart);
303 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000304 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000305 // Different macro; we're done.
306 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000307 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000308 }
Mike Stump1eb44332009-09-09 15:08:12 +0000309
310 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000311 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000312 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000313 (*ConflictPos)[MacroDefLen] != '(')
314 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000316 // We found a conflicting macro definition.
317 break;
318 }
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Argyrios Kyrtzidis11e51102009-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 Redl7e9ad8b2010-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 Dunbar4d5936a2009-11-11 05:26:28 +0000331 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000332
333 ConflictingDefines = true;
334 continue;
335 }
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Daniel Dunbar10014aa2009-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000339 if (ConflictingDefines)
340 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Argyrios Kyrtzidis11e51102009-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 Redl7e9ad8b2010-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000354 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
355 }
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000357 if (ConflictingDefines)
358 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Argyrios Kyrtzidis11e51102009-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 Dunbar4d5936a2009-11-11 05:26:28 +0000364 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000365 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
366 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000367 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000368 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000369 llvm::StringRef &Extra = ExtraPredefines[I];
370 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-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 Stump1eb44332009-09-09 15:08:12 +0000378 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-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 Dunbar4d5936a2009-11-11 05:26:28 +0000382 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-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 Dunbar4d5936a2009-11-11 05:26:28 +0000387 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar4fda42e2009-11-11 00:52:00 +0000388 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis11e51102009-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 Gregor12fab312010-03-16 16:35:32 +0000402void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
403 unsigned ID) {
404 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
405 ++NumHeaderInfos;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000406}
407
408void PCHValidator::ReadCounter(unsigned Value) {
409 PP.setCounterValue(Value);
410}
411
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000412//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000413// PCH reader implementation
414//===----------------------------------------------------------------------===//
415
Mike Stump1eb44332009-09-09 15:08:12 +0000416PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000417 const char *isysroot, bool DisableValidation)
Sebastian Redl30c514c2010-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 Redl2da08f92010-07-19 22:28:42 +0000421 Consumer(0), MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000422 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000423 TotalNumSelectors(0), isysroot(isysroot),
424 DisableValidation(DisableValidation), NumStatHits(0), NumStatMisses(0),
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000425 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
426 TotalNumStatements(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0),
427 NumMethodPoolMisses(0), TotalNumMacros(0), NumLexicalDeclContextsRead(0),
428 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +0000429 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000430 RelocatablePCH = false;
431}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000432
433PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000434 Diagnostic &Diags, const char *isysroot,
435 bool DisableValidation)
Sebastian Redl30c514c2010-07-14 23:45:08 +0000436 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
Sebastian Redl9137a522010-07-16 17:50:48 +0000437 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000438 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
439 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000440 TotalNumSelectors(0), isysroot(isysroot),
441 DisableValidation(DisableValidation), NumStatHits(0), NumStatMisses(0),
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000442 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
443 TotalNumStatements(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0),
444 NumMethodPoolMisses(0), TotalNumMacros(0), NumLexicalDeclContextsRead(0),
445 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +0000446 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000447 RelocatablePCH = false;
448}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000449
Sebastian Redl9137a522010-07-16 17:50:48 +0000450PCHReader::~PCHReader() {
451 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
452 delete Chain[e - i - 1];
453}
454
455PCHReader::PerFileData::PerFileData()
Sebastian Redl12d6da02010-07-19 22:06:55 +0000456 : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
Sebastian Redl2da08f92010-07-19 22:28:42 +0000457 LocalNumDecls(0), DeclOffsets(0), LocalNumIdentifiers(0),
Sebastian Redl04e6fd42010-07-21 20:07:32 +0000458 IdentifierOffsets(0), IdentifierTableData(0), IdentifierLookupTable(0),
459 LocalNumMacroDefinitions(0), MacroDefinitionOffsets(0),
460 NumPreallocatedPreprocessingEntities(0)
Sebastian Redl9137a522010-07-16 17:50:48 +0000461{}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000462
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000463void
464PCHReader::setDeserializationListener(PCHDeserializationListener *Listener) {
465 DeserializationListener = Listener;
466 if (DeserializationListener)
467 DeserializationListener->SetReader(this);
468}
469
Chris Lattner4c6f9522009-04-27 05:14:47 +0000470
Douglas Gregor668c1a42009-04-21 22:25:48 +0000471namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000472class PCHMethodPoolLookupTrait {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000473 PCHReader &Reader;
474
475public:
476 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
477
478 typedef Selector external_key_type;
479 typedef external_key_type internal_key_type;
480
481 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000483 static bool EqualKey(const internal_key_type& a,
484 const internal_key_type& b) {
485 return a == b;
486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000488 static unsigned ComputeHash(Selector Sel) {
489 unsigned N = Sel.getNumArgs();
490 if (N == 0)
491 ++N;
492 unsigned R = 5381;
493 for (unsigned I = 0; I != N; ++I)
494 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000495 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000496 return R;
497 }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000499 // This hopefully will just get inlined and removed by the optimizer.
500 static const internal_key_type&
501 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000503 static std::pair<unsigned, unsigned>
504 ReadKeyDataLength(const unsigned char*& d) {
505 using namespace clang::io;
506 unsigned KeyLen = ReadUnalignedLE16(d);
507 unsigned DataLen = ReadUnalignedLE16(d);
508 return std::make_pair(KeyLen, DataLen);
509 }
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Douglas Gregor83941df2009-04-25 17:48:32 +0000511 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000512 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000513 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000514 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000515 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000516 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
517 if (N == 0)
518 return SelTable.getNullarySelector(FirstII);
519 else if (N == 1)
520 return SelTable.getUnarySelector(FirstII);
521
522 llvm::SmallVector<IdentifierInfo *, 16> Args;
523 Args.push_back(FirstII);
524 for (unsigned I = 1; I != N; ++I)
525 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
526
Douglas Gregor75fdb232009-05-22 22:45:36 +0000527 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000528 }
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000530 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
531 using namespace clang::io;
532 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
533 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
534
535 data_type Result;
536
537 // Load instance methods
538 ObjCMethodList *Prev = 0;
539 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000540 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000541 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
542 if (!Result.first.Method) {
543 // This is the first method, which is the easy case.
544 Result.first.Method = Method;
545 Prev = &Result.first;
546 continue;
547 }
548
Ted Kremenek298ed872010-02-11 00:53:01 +0000549 ObjCMethodList *Mem =
550 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
551 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000552 Prev = Prev->Next;
553 }
554
555 // Load factory methods
556 Prev = 0;
557 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000558 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000559 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
560 if (!Result.second.Method) {
561 // This is the first method, which is the easy case.
562 Result.second.Method = Method;
563 Prev = &Result.second;
564 continue;
565 }
566
Ted Kremenek298ed872010-02-11 00:53:01 +0000567 ObjCMethodList *Mem =
568 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
569 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000570 Prev = Prev->Next;
571 }
572
573 return Result;
574 }
575};
Mike Stump1eb44332009-09-09 15:08:12 +0000576
577} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000578
579/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000580typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000581 PCHMethodPoolLookupTable;
582
583namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000584class PCHIdentifierLookupTrait {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000585 PCHReader &Reader;
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000586 llvm::BitstreamCursor &Stream;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000587
588 // If we know the IdentifierInfo in advance, it is here and we will
589 // not build a new one. Used when deserializing information about an
590 // identifier that was constructed before the PCH file was read.
591 IdentifierInfo *KnownII;
592
593public:
594 typedef IdentifierInfo * data_type;
595
596 typedef const std::pair<const char*, unsigned> external_key_type;
597
598 typedef external_key_type internal_key_type;
599
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000600 PCHIdentifierLookupTrait(PCHReader &Reader, llvm::BitstreamCursor &Stream,
601 IdentifierInfo *II = 0)
602 : Reader(Reader), Stream(Stream), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Douglas Gregor668c1a42009-04-21 22:25:48 +0000604 static bool EqualKey(const internal_key_type& a,
605 const internal_key_type& b) {
606 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
607 : false;
608 }
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Douglas Gregor668c1a42009-04-21 22:25:48 +0000610 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000611 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Douglas Gregor668c1a42009-04-21 22:25:48 +0000614 // This hopefully will just get inlined and removed by the optimizer.
615 static const internal_key_type&
616 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Douglas Gregor668c1a42009-04-21 22:25:48 +0000618 static std::pair<unsigned, unsigned>
619 ReadKeyDataLength(const unsigned char*& d) {
620 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000621 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000622 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000623 return std::make_pair(KeyLen, DataLen);
624 }
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Douglas Gregor668c1a42009-04-21 22:25:48 +0000626 static std::pair<const char*, unsigned>
627 ReadKey(const unsigned char* d, unsigned n) {
628 assert(n >= 2 && d[n-1] == '\0');
629 return std::make_pair((const char*) d, n-1);
630 }
Mike Stump1eb44332009-09-09 15:08:12 +0000631
632 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000633 const unsigned char* d,
634 unsigned DataLen) {
635 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000636 pch::IdentID ID = ReadUnalignedLE32(d);
637 bool IsInteresting = ID & 0x01;
638
639 // Wipe out the "is interesting" bit.
640 ID = ID >> 1;
641
642 if (!IsInteresting) {
Sebastian Redl083abdf2010-07-27 23:01:28 +0000643 // For uninteresting identifiers, just build the IdentifierInfo
Douglas Gregora92193e2009-04-28 21:18:29 +0000644 // and associate it with the persistent ID.
645 IdentifierInfo *II = KnownII;
646 if (!II)
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000647 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregora92193e2009-04-28 21:18:29 +0000648 Reader.SetIdentifierInfo(ID, II);
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000649 II->setIsFromPCH();
Douglas Gregora92193e2009-04-28 21:18:29 +0000650 return II;
651 }
652
Douglas Gregor5998da52009-04-28 21:32:13 +0000653 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000654 bool CPlusPlusOperatorKeyword = Bits & 0x01;
655 Bits >>= 1;
656 bool Poisoned = Bits & 0x01;
657 Bits >>= 1;
658 bool ExtensionToken = Bits & 0x01;
659 Bits >>= 1;
660 bool hasMacroDefinition = Bits & 0x01;
661 Bits >>= 1;
662 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
663 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Douglas Gregor2deaea32009-04-22 18:49:13 +0000665 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000666 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000667
668 // Build the IdentifierInfo itself and link the identifier ID with
669 // the new IdentifierInfo.
670 IdentifierInfo *II = KnownII;
671 if (!II)
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000672 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000673 Reader.SetIdentifierInfo(ID, II);
674
Douglas Gregor2deaea32009-04-22 18:49:13 +0000675 // Set or check the various bits in the IdentifierInfo structure.
676 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000677 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000678 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000679 "Incorrect extension token flag");
680 (void)ExtensionToken;
681 II->setIsPoisoned(Poisoned);
682 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
683 "Incorrect C++ operator keyword flag");
684 (void)CPlusPlusOperatorKeyword;
685
Douglas Gregor37e26842009-04-21 23:56:24 +0000686 // If this identifier is a macro, deserialize the macro
687 // definition.
688 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000689 uint32_t Offset = ReadUnalignedLE32(d);
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000690 Reader.ReadMacroRecord(Stream, Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000691 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000692 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000693
694 // Read all of the declarations visible at global scope with this
695 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000696 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000697 if (DataLen > 0) {
698 llvm::SmallVector<uint32_t, 4> DeclIDs;
699 for (; DataLen > 0; DataLen -= 4)
700 DeclIDs.push_back(ReadUnalignedLE32(d));
701 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000702 }
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000704 II->setIsFromPCH();
Douglas Gregor668c1a42009-04-21 22:25:48 +0000705 return II;
706 }
707};
Mike Stump1eb44332009-09-09 15:08:12 +0000708
709} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000710
711/// \brief The on-disk hash table used to contain information about
712/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000713typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000714 PCHIdentifierLookupTable;
715
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000716void PCHReader::Error(const char *Msg) {
717 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000718}
719
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000720/// \brief Check the contents of the concatenation of all predefines buffers in
721/// the PCH chain against the contents of the predefines buffer of the current
722/// compiler invocation.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000723///
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000724/// The contents should be the same. If not, then some command-line option
725/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000726///
727/// \returns true if there was a mismatch (in which case the PCH file
728/// should be ignored), or false otherwise.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000729bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000730 if (Listener)
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000731 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000732 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000733 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000734 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000735}
736
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000737//===----------------------------------------------------------------------===//
738// Source Manager Deserialization
739//===----------------------------------------------------------------------===//
740
Douglas Gregorbd945002009-04-13 16:31:14 +0000741/// \brief Read the line table in the source manager block.
742/// \returns true if ther was an error.
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000743bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000744 unsigned Idx = 0;
745 LineTableInfo &LineTable = SourceMgr.getLineTable();
746
747 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000748 std::map<int, int> FileIDs;
749 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000750 // Extract the file name
751 unsigned FilenameLen = Record[Idx++];
752 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
753 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000754 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000755 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000756 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000757 }
758
759 // Parse the line entries
760 std::vector<LineEntry> Entries;
761 while (Idx < Record.size()) {
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000762 int FID = Record[Idx++];
Douglas Gregorbd945002009-04-13 16:31:14 +0000763
764 // Extract the line entries
765 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000766 assert(NumEntries && "Numentries is 00000");
Douglas Gregorbd945002009-04-13 16:31:14 +0000767 Entries.clear();
768 Entries.reserve(NumEntries);
769 for (unsigned I = 0; I != NumEntries; ++I) {
770 unsigned FileOffset = Record[Idx++];
771 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000772 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump1eb44332009-09-09 15:08:12 +0000773 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000774 = (SrcMgr::CharacteristicKind)Record[Idx++];
775 unsigned IncludeOffset = Record[Idx++];
776 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
777 FileKind, IncludeOffset));
778 }
779 LineTable.AddEntry(FID, Entries);
780 }
781
782 return false;
783}
784
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000785namespace {
786
Benjamin Kramerbd218282009-11-28 10:07:24 +0000787class PCHStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000788public:
789 const bool hasStat;
790 const ino_t ino;
791 const dev_t dev;
792 const mode_t mode;
793 const time_t mtime;
794 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000796 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000797 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
798
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000799 PCHStatData()
800 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
801};
802
Benjamin Kramerbd218282009-11-28 10:07:24 +0000803class PCHStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000804 public:
805 typedef const char *external_key_type;
806 typedef const char *internal_key_type;
807
808 typedef PCHStatData data_type;
809
810 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000811 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000812 }
813
814 static internal_key_type GetInternalKey(const char *path) { return path; }
815
816 static bool EqualKey(internal_key_type a, internal_key_type b) {
817 return strcmp(a, b) == 0;
818 }
819
820 static std::pair<unsigned, unsigned>
821 ReadKeyDataLength(const unsigned char*& d) {
822 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
823 unsigned DataLen = (unsigned) *d++;
824 return std::make_pair(KeyLen + 1, DataLen);
825 }
826
827 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
828 return (const char *)d;
829 }
830
831 static data_type ReadData(const internal_key_type, const unsigned char *d,
832 unsigned /*DataLen*/) {
833 using namespace clang::io;
834
835 if (*d++ == 1)
836 return data_type();
837
838 ino_t ino = (ino_t) ReadUnalignedLE32(d);
839 dev_t dev = (dev_t) ReadUnalignedLE32(d);
840 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000841 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000842 off_t size = (off_t) ReadUnalignedLE64(d);
843 return data_type(ino, dev, mode, mtime, size);
844 }
845};
846
847/// \brief stat() cache for precompiled headers.
848///
849/// This cache is very similar to the stat cache used by pretokenized
850/// headers.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000851class PCHStatCache : public StatSysCallCache {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000852 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
853 CacheTy *Cache;
854
855 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000856public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000857 PCHStatCache(const unsigned char *Buckets,
858 const unsigned char *Base,
859 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000860 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000861 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
862 Cache = CacheTy::Create(Buckets, Base);
863 }
864
865 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000867 int stat(const char *path, struct stat *buf) {
868 // Do the lookup for the file's data in the PCH file.
869 CacheTy::iterator I = Cache->find(path);
870
871 // If we don't get a hit in the PCH file just forward to 'stat'.
872 if (I == Cache->end()) {
873 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000874 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000875 }
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000877 ++NumStatHits;
878 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000880 if (!Data.hasStat)
881 return 1;
882
883 buf->st_ino = Data.ino;
884 buf->st_dev = Data.dev;
885 buf->st_mtime = Data.mtime;
886 buf->st_mode = Data.mode;
887 buf->st_size = Data.size;
888 return 0;
889 }
890};
891} // end anonymous namespace
892
893
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000894/// \brief Read a source manager block
895PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000896 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000897
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000898 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +0000899
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000900 // Set the source-location entry cursor to the current position in
901 // the stream. This cursor will be used to read the contents of the
902 // source manager block initially, and then lazily read
903 // source-location entries as needed.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000904 SLocEntryCursor = F.Stream;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000905
906 // The stream itself is going to skip over the source manager block.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000907 if (F.Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000908 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000909 return Failure;
910 }
911
912 // Enter the source manager block.
913 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000914 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000915 return Failure;
916 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000917
Douglas Gregor14f79002009-04-10 03:52:48 +0000918 RecordData Record;
919 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000920 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000921 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000922 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000923 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000924 return Failure;
925 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000926 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000927 }
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Douglas Gregor14f79002009-04-10 03:52:48 +0000929 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
930 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000931 SLocEntryCursor.ReadSubBlockID();
932 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000933 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000934 return Failure;
935 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000936 continue;
937 }
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Douglas Gregor14f79002009-04-10 03:52:48 +0000939 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000940 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000941 continue;
942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Douglas Gregor14f79002009-04-10 03:52:48 +0000944 // Read a record.
945 const char *BlobStart;
946 unsigned BlobLen;
947 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000948 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000949 default: // Default behavior: ignore.
950 break;
951
Chris Lattner2c78b872009-04-14 23:22:57 +0000952 case pch::SM_LINE_TABLE:
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000953 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000954 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000955 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000956
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000957 case pch::SM_SLOC_FILE_ENTRY:
958 case pch::SM_SLOC_BUFFER_ENTRY:
959 case pch::SM_SLOC_INSTANTIATION_ENTRY:
960 // Once we hit one of the source location entries, we're done.
961 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000962 }
963 }
964}
965
Sebastian Redl190faf72010-07-20 21:50:20 +0000966/// \brief Get a cursor that's correctly positioned for reading the source
967/// location entry with the given ID.
968llvm::BitstreamCursor &PCHReader::SLocCursorForID(unsigned ID) {
969 assert(ID != 0 && ID <= TotalNumSLocEntries &&
970 "SLocCursorForID should only be called for real IDs.");
971
972 ID -= 1;
973 PerFileData *F = 0;
974 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
975 F = Chain[N - I - 1];
976 if (ID < F->LocalNumSLocEntries)
977 break;
978 ID -= F->LocalNumSLocEntries;
979 }
980 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
981
982 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
983 return F->SLocEntryCursor;
984}
985
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000986/// \brief Read in the source location entry with the given ID.
987PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
988 if (ID == 0)
989 return Success;
990
991 if (ID > TotalNumSLocEntries) {
992 Error("source location entry ID out-of-range for PCH file");
993 return Failure;
994 }
995
Sebastian Redl190faf72010-07-20 21:50:20 +0000996 llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
Sebastian Redl9137a522010-07-16 17:50:48 +0000997
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000998 ++NumSLocEntriesRead;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000999 unsigned Code = SLocEntryCursor.ReadCode();
1000 if (Code == llvm::bitc::END_BLOCK ||
1001 Code == llvm::bitc::ENTER_SUBBLOCK ||
1002 Code == llvm::bitc::DEFINE_ABBREV) {
1003 Error("incorrectly-formatted source location entry in PCH file");
1004 return Failure;
1005 }
1006
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001007 RecordData Record;
1008 const char *BlobStart;
1009 unsigned BlobLen;
1010 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1011 default:
1012 Error("incorrectly-formatted source location entry in PCH file");
1013 return Failure;
1014
1015 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001016 std::string Filename(BlobStart, BlobStart + BlobLen);
1017 MaybeAddSystemRootToFilename(Filename);
1018 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001019 if (File == 0) {
1020 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +00001021 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001022 ErrorStr += "' referenced by PCH file";
1023 Error(ErrorStr.c_str());
1024 return Failure;
1025 }
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Douglas Gregor2d52be52010-03-21 22:49:54 +00001027 if (Record.size() < 10) {
Ted Kremenek1857f622010-03-18 21:23:05 +00001028 Error("source location entry is incorrect");
1029 return Failure;
1030 }
1031
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001032 if (!DisableValidation &&
1033 ((off_t)Record[4] != File->getSize()
Douglas Gregor9f692a02010-04-09 15:54:22 +00001034#if !defined(LLVM_ON_WIN32)
1035 // In our regression testing, the Windows file system seems to
1036 // have inconsistent modification times that sometimes
1037 // erroneously trigger this error-handling path.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001038 || (time_t)Record[5] != File->getModificationTime()
Douglas Gregor9f692a02010-04-09 15:54:22 +00001039#endif
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001040 )) {
Douglas Gregor2d52be52010-03-21 22:49:54 +00001041 Diag(diag::err_fe_pch_file_modified)
1042 << Filename;
1043 return Failure;
1044 }
1045
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001046 FileID FID = SourceMgr.createFileID(File,
1047 SourceLocation::getFromRawEncoding(Record[1]),
1048 (SrcMgr::CharacteristicKind)Record[2],
1049 ID, Record[0]);
1050 if (Record[3])
1051 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1052 .setHasLineDirectives();
1053
Douglas Gregor12fab312010-03-16 16:35:32 +00001054 // Reconstruct header-search information for this file.
1055 HeaderFileInfo HFI;
Douglas Gregor2d52be52010-03-21 22:49:54 +00001056 HFI.isImport = Record[6];
1057 HFI.DirInfo = Record[7];
1058 HFI.NumIncludes = Record[8];
1059 HFI.ControllingMacroID = Record[9];
Douglas Gregor12fab312010-03-16 16:35:32 +00001060 if (Listener)
1061 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001062 break;
1063 }
1064
1065 case pch::SM_SLOC_BUFFER_ENTRY: {
1066 const char *Name = BlobStart;
1067 unsigned Offset = Record[0];
1068 unsigned Code = SLocEntryCursor.ReadCode();
1069 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001070 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001071 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001072
1073 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1074 Error("PCH record has invalid code");
1075 return Failure;
1076 }
1077
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001078 llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001079 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1080 Name);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001081 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Douglas Gregor92b059e2009-04-28 20:33:11 +00001083 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001084 PCHPredefinesBlock Block = {
1085 BufferID,
1086 llvm::StringRef(BlobStart, BlobLen - 1)
1087 };
1088 PCHPredefinesBuffers.push_back(Block);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001089 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001090
1091 break;
1092 }
1093
1094 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +00001095 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001096 = SourceLocation::getFromRawEncoding(Record[1]);
1097 SourceMgr.createInstantiationLoc(SpellingLoc,
1098 SourceLocation::getFromRawEncoding(Record[2]),
1099 SourceLocation::getFromRawEncoding(Record[3]),
1100 Record[4],
1101 ID,
1102 Record[0]);
1103 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001104 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001105 }
1106
1107 return Success;
1108}
1109
Chris Lattner6367f6d2009-04-27 01:05:14 +00001110/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1111/// specified cursor. Read the abbreviations that are at the top of the block
1112/// and then leave the cursor pointing into the block.
1113bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1114 unsigned BlockID) {
1115 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001116 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001117 return Failure;
1118 }
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Chris Lattner6367f6d2009-04-27 01:05:14 +00001120 while (true) {
1121 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Chris Lattner6367f6d2009-04-27 01:05:14 +00001123 // We expect all abbrevs to be at the start of the block.
1124 if (Code != llvm::bitc::DEFINE_ABBREV)
1125 return false;
1126 Cursor.ReadAbbrevRecord();
1127 }
1128}
1129
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001130void PCHReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001131 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Douglas Gregor37e26842009-04-21 23:56:24 +00001133 // Keep track of where we are in the stream, then jump back there
1134 // after reading this macro.
1135 SavedStreamPosition SavedPosition(Stream);
1136
1137 Stream.JumpToBit(Offset);
1138 RecordData Record;
1139 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1140 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Douglas Gregor37e26842009-04-21 23:56:24 +00001142 while (true) {
1143 unsigned Code = Stream.ReadCode();
1144 switch (Code) {
1145 case llvm::bitc::END_BLOCK:
1146 return;
1147
1148 case llvm::bitc::ENTER_SUBBLOCK:
1149 // No known subblocks, always skip them.
1150 Stream.ReadSubBlockID();
1151 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001152 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001153 return;
1154 }
1155 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Douglas Gregor37e26842009-04-21 23:56:24 +00001157 case llvm::bitc::DEFINE_ABBREV:
1158 Stream.ReadAbbrevRecord();
1159 continue;
1160 default: break;
1161 }
1162
1163 // Read a record.
1164 Record.clear();
1165 pch::PreprocessorRecordTypes RecType =
1166 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1167 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001168 case pch::PP_MACRO_OBJECT_LIKE:
1169 case pch::PP_MACRO_FUNCTION_LIKE: {
1170 // If we already have a macro, that means that we've hit the end
1171 // of the definition of the macro we were looking for. We're
1172 // done.
1173 if (Macro)
1174 return;
1175
1176 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1177 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001178 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001179 return;
1180 }
1181 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1182 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001184 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001185 MI->setIsUsed(isUsed);
Sebastian Redl083abdf2010-07-27 23:01:28 +00001186 MI->setIsFromPCH();
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001188 unsigned NextIndex = 3;
Douglas Gregor37e26842009-04-21 23:56:24 +00001189 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1190 // Decode function-like macro info.
1191 bool isC99VarArgs = Record[3];
1192 bool isGNUVarArgs = Record[4];
1193 MacroArgs.clear();
1194 unsigned NumArgs = Record[5];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001195 NextIndex = 6 + NumArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001196 for (unsigned i = 0; i != NumArgs; ++i)
1197 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1198
1199 // Install function-like macro info.
1200 MI->setIsFunctionLike();
1201 if (isC99VarArgs) MI->setIsC99Varargs();
1202 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001203 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001204 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001205 }
1206
1207 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001208 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001209
1210 // Remember that we saw this macro last so that we add the tokens that
1211 // form its body to it.
1212 Macro = MI;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001213
1214 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1215 // We have a macro definition. Load it now.
1216 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1217 getMacroDefinition(Record[NextIndex]));
1218 }
1219
Douglas Gregor37e26842009-04-21 23:56:24 +00001220 ++NumMacrosRead;
1221 break;
1222 }
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Douglas Gregor37e26842009-04-21 23:56:24 +00001224 case pch::PP_TOKEN: {
1225 // If we see a TOKEN before a PP_MACRO_*, then the file is
1226 // erroneous, just pretend we didn't see this.
1227 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Douglas Gregor37e26842009-04-21 23:56:24 +00001229 Token Tok;
1230 Tok.startToken();
1231 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1232 Tok.setLength(Record[1]);
1233 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1234 Tok.setIdentifierInfo(II);
1235 Tok.setKind((tok::TokenKind)Record[3]);
1236 Tok.setFlag((Token::TokenFlags)Record[4]);
1237 Macro->AddTokenToBody(Tok);
1238 break;
1239 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001240
1241 case pch::PP_MACRO_INSTANTIATION: {
1242 // If we already have a macro, that means that we've hit the end
1243 // of the definition of the macro we were looking for. We're
1244 // done.
1245 if (Macro)
1246 return;
1247
1248 if (!PP->getPreprocessingRecord()) {
1249 Error("missing preprocessing record in PCH file");
1250 return;
1251 }
1252
1253 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1254 if (PPRec.getPreprocessedEntity(Record[0]))
1255 return;
1256
1257 MacroInstantiation *MI
1258 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1259 SourceRange(
1260 SourceLocation::getFromRawEncoding(Record[1]),
1261 SourceLocation::getFromRawEncoding(Record[2])),
1262 getMacroDefinition(Record[4]));
1263 PPRec.SetPreallocatedEntity(Record[0], MI);
1264 return;
1265 }
1266
1267 case pch::PP_MACRO_DEFINITION: {
1268 // If we already have a macro, that means that we've hit the end
1269 // of the definition of the macro we were looking for. We're
1270 // done.
1271 if (Macro)
1272 return;
1273
1274 if (!PP->getPreprocessingRecord()) {
1275 Error("missing preprocessing record in PCH file");
1276 return;
1277 }
1278
1279 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1280 if (PPRec.getPreprocessedEntity(Record[0]))
1281 return;
1282
1283 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1284 Error("out-of-bounds macro definition record");
1285 return;
1286 }
1287
1288 MacroDefinition *MD
1289 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1290 SourceLocation::getFromRawEncoding(Record[5]),
1291 SourceRange(
1292 SourceLocation::getFromRawEncoding(Record[2]),
1293 SourceLocation::getFromRawEncoding(Record[3])));
1294 PPRec.SetPreallocatedEntity(Record[0], MD);
1295 MacroDefinitionsLoaded[Record[1]] = MD;
1296 return;
1297 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001298 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001299 }
1300}
1301
Douglas Gregor88a35862010-01-04 19:18:44 +00001302void PCHReader::ReadDefinedMacros() {
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001303 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1304 llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00001305
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001306 // If there was no preprocessor block, skip this file.
1307 if (!MacroCursor.getBitStreamReader())
1308 continue;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001309
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001310 llvm::BitstreamCursor Cursor = MacroCursor;
1311 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1312 Error("malformed preprocessor block record in PCH file");
Douglas Gregor88a35862010-01-04 19:18:44 +00001313 return;
1314 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001315
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001316 RecordData Record;
1317 while (true) {
1318 unsigned Code = Cursor.ReadCode();
1319 if (Code == llvm::bitc::END_BLOCK) {
1320 if (Cursor.ReadBlockEnd()) {
1321 Error("error at end of preprocessor block in PCH file");
1322 return;
1323 }
1324 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001325 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001326
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001327 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1328 // No known subblocks, always skip them.
1329 Cursor.ReadSubBlockID();
1330 if (Cursor.SkipBlock()) {
1331 Error("malformed block record in PCH file");
1332 return;
1333 }
1334 continue;
1335 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001336
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001337 if (Code == llvm::bitc::DEFINE_ABBREV) {
1338 Cursor.ReadAbbrevRecord();
1339 continue;
1340 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001341
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001342 // Read a record.
1343 const char *BlobStart;
1344 unsigned BlobLen;
1345 Record.clear();
1346 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1347 default: // Default behavior: ignore.
1348 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001349
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001350 case pch::PP_MACRO_OBJECT_LIKE:
1351 case pch::PP_MACRO_FUNCTION_LIKE:
1352 DecodeIdentifierInfo(Record[0]);
1353 break;
1354
1355 case pch::PP_TOKEN:
1356 // Ignore tokens.
1357 break;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001358
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001359 case pch::PP_MACRO_INSTANTIATION:
1360 case pch::PP_MACRO_DEFINITION:
1361 // Read the macro record.
1362 ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1363 break;
1364 }
Douglas Gregor88a35862010-01-04 19:18:44 +00001365 }
1366 }
1367}
1368
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001369MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1370 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1371 return 0;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001372
1373 if (!MacroDefinitionsLoaded[ID]) {
1374 unsigned Index = ID;
1375 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1376 PerFileData &F = *Chain[N - I - 1];
1377 if (Index < F.LocalNumMacroDefinitions) {
1378 ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1379 break;
1380 }
1381 Index -= F.LocalNumMacroDefinitions;
1382 }
1383 assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1384 }
1385
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001386 return MacroDefinitionsLoaded[ID];
1387}
1388
Douglas Gregore650c8c2009-07-07 00:12:59 +00001389/// \brief If we are loading a relocatable PCH file, and the filename is
1390/// not an absolute path, add the system root to the beginning of the file
1391/// name.
1392void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1393 // If this is not a relocatable PCH file, there's nothing to do.
1394 if (!RelocatablePCH)
1395 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Daniel Dunbard5b21972009-11-18 19:50:41 +00001397 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001398 return;
1399
Douglas Gregore650c8c2009-07-07 00:12:59 +00001400 if (isysroot == 0) {
1401 // If no system root was given, default to '/'
1402 Filename.insert(Filename.begin(), '/');
1403 return;
1404 }
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Douglas Gregore650c8c2009-07-07 00:12:59 +00001406 unsigned Length = strlen(isysroot);
1407 if (isysroot[Length - 1] != '/')
1408 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Douglas Gregore650c8c2009-07-07 00:12:59 +00001410 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1411}
1412
Mike Stump1eb44332009-09-09 15:08:12 +00001413PCHReader::PCHReadResult
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001414PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl9137a522010-07-16 17:50:48 +00001415 llvm::BitstreamCursor &Stream = F.Stream;
1416
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001417 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001418 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001419 return Failure;
1420 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001421
1422 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001423 RecordData Record;
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001424 bool First = true;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001425 while (!Stream.AtEndOfStream()) {
1426 unsigned Code = Stream.ReadCode();
1427 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001428 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001429 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001430 return Failure;
1431 }
Chris Lattner7356a312009-04-11 21:15:38 +00001432
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001433 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001434 }
1435
1436 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1437 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001438 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001439 // We lazily load the decls block, but we want to set up the
1440 // DeclsCursor cursor to point into it. Clone our current bitcode
1441 // cursor to it, enter the block and read the abbrevs in that block.
1442 // With the main cursor, we just skip over it.
Sebastian Redl9137a522010-07-16 17:50:48 +00001443 F.DeclsCursor = Stream;
Chris Lattner6367f6d2009-04-27 01:05:14 +00001444 if (Stream.SkipBlock() || // Skip with the main cursor.
1445 // Read the abbrevs.
Sebastian Redl9137a522010-07-16 17:50:48 +00001446 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001447 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001448 return Failure;
1449 }
1450 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Chris Lattner7356a312009-04-11 21:15:38 +00001452 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl9137a522010-07-16 17:50:48 +00001453 F.MacroCursor = Stream;
Douglas Gregor88a35862010-01-04 19:18:44 +00001454 if (PP)
1455 PP->setExternalSource(this);
1456
Chris Lattner7356a312009-04-11 21:15:38 +00001457 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001458 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001459 return Failure;
1460 }
1461 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001462
Douglas Gregor14f79002009-04-10 03:52:48 +00001463 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001464 switch (ReadSourceManagerBlock(F)) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001465 case Success:
1466 break;
1467
1468 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001469 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001470 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001471
1472 case IgnorePCH:
1473 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001474 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001475 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001476 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001477 First = false;
Douglas Gregor8038d512009-04-10 17:25:41 +00001478 continue;
1479 }
1480
1481 if (Code == llvm::bitc::DEFINE_ABBREV) {
1482 Stream.ReadAbbrevRecord();
1483 continue;
1484 }
1485
1486 // Read and process a record.
1487 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001488 const char *BlobStart = 0;
1489 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001490 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001491 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001492 default: // Default behavior: ignore.
1493 break;
1494
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001495 case pch::METADATA: {
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001496 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001497 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1498 : diag::warn_pch_version_too_new);
1499 return IgnorePCH;
1500 }
1501
1502 RelocatablePCH = Record[4];
1503 if (Listener) {
1504 std::string TargetTriple(BlobStart, BlobLen);
1505 if (Listener->ReadTargetTriple(TargetTriple))
1506 return IgnorePCH;
1507 }
1508 break;
1509 }
1510
1511 case pch::CHAINED_METADATA: {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001512 if (!First) {
1513 Error("CHAINED_METADATA is not first record in block");
1514 return Failure;
1515 }
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001516 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001517 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1518 : diag::warn_pch_version_too_new);
1519 return IgnorePCH;
1520 }
1521
1522 // Load the chained file.
1523 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1524 case Failure: return Failure;
1525 // If we have to ignore the dependency, we'll have to ignore this too.
1526 case IgnorePCH: return IgnorePCH;
1527 case Success: break;
1528 }
1529 break;
1530 }
1531
Douglas Gregor8038d512009-04-10 17:25:41 +00001532 case pch::TYPE_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001533 if (F.LocalNumTypes != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001534 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001535 return Failure;
1536 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001537 F.TypeOffsets = (const uint32_t *)BlobStart;
1538 F.LocalNumTypes = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001539 break;
1540
1541 case pch::DECL_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001542 if (F.LocalNumDecls != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001543 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001544 return Failure;
1545 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001546 F.DeclOffsets = (const uint32_t *)BlobStart;
1547 F.LocalNumDecls = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001548 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001549
Sebastian Redld692af72010-07-27 18:24:41 +00001550 case pch::TU_UPDATE_LEXICAL: {
1551 DeclContextInfo Info = {
1552 /* No visible information */ 0, 0,
1553 reinterpret_cast<const pch::DeclID *>(BlobStart),
1554 BlobLen / sizeof(pch::DeclID)
1555 };
1556 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1557 break;
1558 }
1559
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00001560 case pch::REDECLS_UPDATE_LATEST: {
1561 assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
1562 for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
1563 pch::DeclID First = Record[i], Latest = Record[i+1];
1564 assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
1565 Latest > FirstLatestDeclIDs[First]) &&
1566 "The new latest is supposed to come after the previous latest");
1567 FirstLatestDeclIDs[First] = Latest;
1568 }
1569 break;
1570 }
1571
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001572 case pch::LANGUAGE_OPTIONS:
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001573 if (ParseLanguageOptions(Record) && !DisableValidation)
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001574 return IgnorePCH;
1575 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001576
Douglas Gregorafaf3082009-04-11 00:14:32 +00001577 case pch::IDENTIFIER_TABLE:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001578 F.IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001579 if (Record[0]) {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001580 F.IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001581 = PCHIdentifierLookupTable::Create(
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001582 (const unsigned char *)F.IdentifierTableData + Record[0],
1583 (const unsigned char *)F.IdentifierTableData,
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001584 PCHIdentifierLookupTrait(*this, F.Stream));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001585 if (PP)
1586 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001587 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001588 break;
1589
1590 case pch::IDENTIFIER_OFFSET:
Sebastian Redl2da08f92010-07-19 22:28:42 +00001591 if (F.LocalNumIdentifiers != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001592 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001593 return Failure;
1594 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001595 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1596 F.LocalNumIdentifiers = Record[0];
Douglas Gregorafaf3082009-04-11 00:14:32 +00001597 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001598
1599 case pch::EXTERNAL_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001600 // Optimization for the first block.
1601 if (ExternalDefinitions.empty())
1602 ExternalDefinitions.swap(Record);
1603 else
1604 ExternalDefinitions.insert(ExternalDefinitions.end(),
1605 Record.begin(), Record.end());
Douglas Gregorfdd01722009-04-14 00:24:19 +00001606 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001607
Douglas Gregorad1de002009-04-18 05:55:16 +00001608 case pch::SPECIAL_TYPES:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001609 // Optimization for the first block
1610 if (SpecialTypes.empty())
1611 SpecialTypes.swap(Record);
1612 else
1613 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
Douglas Gregorad1de002009-04-18 05:55:16 +00001614 break;
1615
Douglas Gregor3e1af842009-04-17 22:13:46 +00001616 case pch::STATISTICS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001617 TotalNumStatements += Record[0];
1618 TotalNumMacros += Record[1];
1619 TotalLexicalDeclContexts += Record[2];
1620 TotalVisibleDeclContexts += Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001621 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001622
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001623 case pch::TENTATIVE_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001624 // Optimization for the first block.
1625 if (TentativeDefinitions.empty())
1626 TentativeDefinitions.swap(Record);
1627 else
1628 TentativeDefinitions.insert(TentativeDefinitions.end(),
1629 Record.begin(), Record.end());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001630 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001631
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001632 case pch::UNUSED_STATIC_FUNCS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001633 // Optimization for the first block.
1634 if (UnusedStaticFuncs.empty())
1635 UnusedStaticFuncs.swap(Record);
1636 else
1637 UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
1638 Record.begin(), Record.end());
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001639 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001640
Douglas Gregor14c22f22009-04-22 22:18:58 +00001641 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001642 // Optimization for the first block.
1643 if (LocallyScopedExternalDecls.empty())
1644 LocallyScopedExternalDecls.swap(Record);
1645 else
1646 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1647 Record.begin(), Record.end());
Douglas Gregor14c22f22009-04-22 22:18:58 +00001648 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001649
Douglas Gregor83941df2009-04-25 17:48:32 +00001650 case pch::SELECTOR_OFFSETS:
1651 SelectorOffsets = (const uint32_t *)BlobStart;
1652 TotalNumSelectors = Record[0];
1653 SelectorsLoaded.resize(TotalNumSelectors);
1654 break;
1655
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001656 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001657 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1658 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001659 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001660 = PCHMethodPoolLookupTable::Create(
1661 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001662 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001663 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001664 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001665 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001666
Fariborz Jahanian32019832010-07-23 19:11:11 +00001667 case pch::REFERENCED_SELECTOR_POOL: {
1668 unsigned int numEl = Record[0]*2;
1669 for (unsigned int i = 1; i <= numEl; i++)
1670 F.ReferencedSelectorsData.push_back(Record[i]);
Fariborz Jahanian32019832010-07-23 19:11:11 +00001671 break;
Sebastian Redl681d7232010-07-27 00:17:23 +00001672 }
Fariborz Jahanian32019832010-07-23 19:11:11 +00001673
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001674 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001675 if (!Record.empty() && Listener)
1676 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001677 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001678
1679 case pch::SOURCE_LOCATION_OFFSETS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001680 F.SLocOffsets = (const uint32_t *)BlobStart;
1681 F.LocalNumSLocEntries = Record[0];
1682 // We cannot delay this until all PCHs are loaded, because then source
1683 // location preloads would also have to be delayed.
1684 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001685 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001686 break;
1687
1688 case pch::SOURCE_LOCATION_PRELOADS:
1689 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1690 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1691 if (Result != Success)
1692 return Result;
1693 }
1694 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001695
Douglas Gregor52e71082009-10-16 18:18:30 +00001696 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001697 PCHStatCache *MyStatCache =
Douglas Gregor52e71082009-10-16 18:18:30 +00001698 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1699 (const unsigned char *)BlobStart,
1700 NumStatHits, NumStatMisses);
1701 FileMgr.addStatCache(MyStatCache);
Sebastian Redl9137a522010-07-16 17:50:48 +00001702 F.StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001703 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001704 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001705
Douglas Gregorb81c1702009-04-27 20:06:05 +00001706 case pch::EXT_VECTOR_DECLS:
Sebastian Redla9f23682010-07-28 21:38:49 +00001707 // Optimization for the first block.
1708 if (ExtVectorDecls.empty())
1709 ExtVectorDecls.swap(Record);
1710 else
1711 ExtVectorDecls.insert(ExtVectorDecls.end(),
1712 Record.begin(), Record.end());
Douglas Gregorb81c1702009-04-27 20:06:05 +00001713 break;
1714
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001715 case pch::VTABLE_USES:
1716 if (!VTableUses.empty()) {
1717 Error("duplicate VTABLE_USES record in PCH file");
1718 return Failure;
1719 }
1720 VTableUses.swap(Record);
1721 break;
1722
1723 case pch::DYNAMIC_CLASSES:
1724 if (!DynamicClasses.empty()) {
1725 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1726 return Failure;
1727 }
1728 DynamicClasses.swap(Record);
1729 break;
1730
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001731 case pch::SEMA_DECL_REFS:
1732 if (!SemaDeclRefs.empty()) {
1733 Error("duplicate SEMA_DECL_REFS record in PCH file");
1734 return Failure;
1735 }
1736 SemaDeclRefs.swap(Record);
1737 break;
1738
Douglas Gregorb64c1932009-05-12 01:31:05 +00001739 case pch::ORIGINAL_FILE_NAME:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001740 // The primary PCH will be the last to get here, so it will be the one
1741 // that's used.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001742 ActualOriginalFileName.assign(BlobStart, BlobLen);
1743 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001744 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001745 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Ted Kremenek5b4ec632010-01-22 20:59:36 +00001747 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek974be4d2010-02-12 23:31:14 +00001748 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek517e6762010-01-22 20:55:35 +00001749 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001750 if (llvm::StringRef(CurBranch) != PCHBranch && !DisableValidation) {
Douglas Gregor445e23e2009-10-05 21:07:28 +00001751 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1752 return IgnorePCH;
1753 }
1754 break;
1755 }
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001756
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001757 case pch::MACRO_DEFINITION_OFFSETS:
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001758 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1759 F.NumPreallocatedPreprocessingEntities = Record[0];
1760 F.LocalNumMacroDefinitions = Record[1];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001761 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001762 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001763 First = false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001764 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001765 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001766 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001767}
1768
Douglas Gregore1d918e2009-04-10 23:10:45 +00001769PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001770 switch(ReadPCHCore(FileName)) {
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001771 case Failure: return Failure;
1772 case IgnorePCH: return IgnorePCH;
1773 case Success: break;
1774 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001775
1776 // Here comes stuff that we only do once the entire chain is loaded.
1777
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001778 // Allocate space for loaded identifiers, decls and types.
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001779 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
1780 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001781 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Sebastian Redl2da08f92010-07-19 22:28:42 +00001782 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001783 TotalNumTypes += Chain[I]->LocalNumTypes;
1784 TotalNumDecls += Chain[I]->LocalNumDecls;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001785 TotalNumPreallocatedPreprocessingEntities +=
1786 Chain[I]->NumPreallocatedPreprocessingEntities;
1787 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001788 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001789 IdentifiersLoaded.resize(TotalNumIdentifiers);
Sebastian Redl12d6da02010-07-19 22:06:55 +00001790 TypesLoaded.resize(TotalNumTypes);
1791 DeclsLoaded.resize(TotalNumDecls);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001792 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
1793 if (PP) {
1794 if (TotalNumIdentifiers > 0)
1795 PP->getHeaderSearchInfo().SetExternalLookup(this);
1796 if (TotalNumPreallocatedPreprocessingEntities > 0) {
1797 if (!PP->getPreprocessingRecord())
1798 PP->createPreprocessingRecord();
1799 PP->getPreprocessingRecord()->SetExternalSource(*this,
1800 TotalNumPreallocatedPreprocessingEntities);
1801 }
1802 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001803
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001804 // Check the predefines buffers.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001805 if (!DisableValidation && CheckPredefinesBuffers())
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001806 return IgnorePCH;
1807
1808 if (PP) {
1809 // Initialization of keywords and pragmas occurs before the
1810 // PCH file is read, so there may be some identifiers that were
1811 // loaded into the IdentifierTable before we intercepted the
1812 // creation of identifiers. Iterate through the list of known
1813 // identifiers and determine whether we have to establish
1814 // preprocessor definitions or top-level identifier declaration
1815 // chains for those identifiers.
1816 //
1817 // We copy the IdentifierInfo pointers to a small vector first,
1818 // since de-serializing declarations or macro definitions can add
1819 // new entries into the identifier table, invalidating the
1820 // iterators.
1821 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1822 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1823 IdEnd = PP->getIdentifierTable().end();
1824 Id != IdEnd; ++Id)
1825 Identifiers.push_back(Id->second);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001826 // We need to search the tables in all files.
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001827 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1828 PCHIdentifierLookupTable *IdTable
1829 = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00001830 // Not all PCH files necessarily have identifier tables, only the useful
1831 // ones.
1832 if (!IdTable)
1833 continue;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001834 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1835 IdentifierInfo *II = Identifiers[I];
1836 // Look in the on-disk hash tables for an entry for this identifier
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001837 PCHIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001838 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001839 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1840 if (Pos == IdTable->end())
1841 continue;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001842
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001843 // Dereferencing the iterator has the effect of populating the
1844 // IdentifierInfo node with the various declarations it needs.
1845 (void)*Pos;
1846 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001847 }
1848 }
1849
1850 if (Context)
1851 InitializeContext(*Context);
1852
1853 return Success;
1854}
1855
1856PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1857 Chain.push_back(new PerFileData());
Sebastian Redl9137a522010-07-16 17:50:48 +00001858 PerFileData &F = *Chain.back();
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001859
1860 // Set the PCH file name.
1861 F.FileName = FileName;
1862
1863 // Open the PCH file.
1864 //
1865 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1866 std::string ErrStr;
1867 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1868 if (!F.Buffer) {
1869 Error(ErrStr.c_str());
1870 return IgnorePCH;
1871 }
1872
1873 // Initialize the stream
1874 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1875 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl9137a522010-07-16 17:50:48 +00001876 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001877 Stream.init(F.StreamFile);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001878 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001879
1880 // Sniff for the signature.
1881 if (Stream.Read(8) != 'C' ||
1882 Stream.Read(8) != 'P' ||
1883 Stream.Read(8) != 'C' ||
1884 Stream.Read(8) != 'H') {
1885 Diag(diag::err_not_a_pch_file) << FileName;
1886 return Failure;
1887 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001888
Douglas Gregor2cf26342009-04-09 22:27:44 +00001889 while (!Stream.AtEndOfStream()) {
1890 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Douglas Gregore1d918e2009-04-10 23:10:45 +00001892 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001893 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001894 return Failure;
1895 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001896
1897 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001898
Douglas Gregor2cf26342009-04-09 22:27:44 +00001899 // We only know the PCH subblock ID.
1900 switch (BlockID) {
1901 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001902 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001903 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001904 return Failure;
1905 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001906 break;
1907 case pch::PCH_BLOCK_ID:
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001908 switch (ReadPCHBlock(F)) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001909 case Success:
1910 break;
1911
1912 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001913 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001914
1915 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001916 // FIXME: We could consider reading through to the end of this
1917 // PCH block, skipping subblocks, to see if there are other
1918 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001919
1920 // Clear out any preallocated source location entries, so that
1921 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001922 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001923
1924 // Remove the stat cache.
Sebastian Redl9137a522010-07-16 17:50:48 +00001925 if (F.StatCache)
1926 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001927
Douglas Gregore1d918e2009-04-10 23:10:45 +00001928 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001929 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001930 break;
1931 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001932 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001933 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001934 return Failure;
1935 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001936 break;
1937 }
Mike Stump1eb44332009-09-09 15:08:12 +00001938 }
1939
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001940 return Success;
1941}
1942
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001943void PCHReader::setPreprocessor(Preprocessor &pp) {
1944 PP = &pp;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001945
1946 unsigned TotalNum = 0;
1947 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
1948 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
1949 if (TotalNum) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001950 if (!PP->getPreprocessingRecord())
1951 PP->createPreprocessingRecord();
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001952 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001953 }
1954}
1955
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001956void PCHReader::InitializeContext(ASTContext &Ctx) {
1957 Context = &Ctx;
1958 assert(Context && "Passed null context!");
1959
1960 assert(PP && "Forgot to set Preprocessor ?");
1961 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1962 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00001963 PP->setExternalSource(this);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001964
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001965 // Load the translation unit declaration
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00001966 GetTranslationUnitDecl();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001967
1968 // Load the special types.
1969 Context->setBuiltinVaListType(
1970 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1971 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1972 Context->setObjCIdType(GetType(Id));
1973 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1974 Context->setObjCSelType(GetType(Sel));
1975 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1976 Context->setObjCProtoType(GetType(Proto));
1977 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1978 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001979
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001980 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1981 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001982 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001983 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1984 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001985 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1986 QualType FileType = GetType(File);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001987 if (FileType.isNull()) {
1988 Error("FILE type is NULL");
1989 return;
1990 }
John McCall183700f2009-09-21 23:43:11 +00001991 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001992 Context->setFILEDecl(Typedef->getDecl());
1993 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001994 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001995 if (!Tag) {
1996 Error("Invalid FILE type in PCH file");
1997 return;
1998 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001999 Context->setFILEDecl(Tag->getDecl());
2000 }
2001 }
Mike Stump782fa302009-07-28 02:25:19 +00002002 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
2003 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002004 if (Jmp_bufType.isNull()) {
2005 Error("jmp_bug type is NULL");
2006 return;
2007 }
John McCall183700f2009-09-21 23:43:11 +00002008 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00002009 Context->setjmp_bufDecl(Typedef->getDecl());
2010 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002011 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002012 if (!Tag) {
2013 Error("Invalid jmp_bug type in PCH file");
2014 return;
2015 }
Mike Stump782fa302009-07-28 02:25:19 +00002016 Context->setjmp_bufDecl(Tag->getDecl());
2017 }
2018 }
2019 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
2020 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002021 if (Sigjmp_bufType.isNull()) {
2022 Error("sigjmp_buf type is NULL");
2023 return;
2024 }
John McCall183700f2009-09-21 23:43:11 +00002025 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00002026 Context->setsigjmp_bufDecl(Typedef->getDecl());
2027 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002028 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00002029 assert(Tag && "Invalid sigjmp_buf type in PCH file");
2030 Context->setsigjmp_bufDecl(Tag->getDecl());
2031 }
2032 }
Mike Stump1eb44332009-09-09 15:08:12 +00002033 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00002034 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2035 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00002036 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00002037 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2038 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00002039 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2040 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00002041 if (unsigned String
2042 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2043 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002044 if (unsigned ObjCSelRedef
2045 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2046 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2047 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
2048 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +00002049
2050 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
2051 Context->setInt128Installed();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002052}
2053
Douglas Gregorb64c1932009-05-12 01:31:05 +00002054/// \brief Retrieve the name of the original source file name
2055/// directly from the PCH file, without actually loading the PCH
2056/// file.
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002057std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
2058 Diagnostic &Diags) {
Douglas Gregorb64c1932009-05-12 01:31:05 +00002059 // Open the PCH file.
2060 std::string ErrStr;
2061 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2062 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
2063 if (!Buffer) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002064 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002065 return std::string();
2066 }
2067
2068 // Initialize the stream
2069 llvm::BitstreamReader StreamFile;
2070 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00002071 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00002072 (const unsigned char *)Buffer->getBufferEnd());
2073 Stream.init(StreamFile);
2074
2075 // Sniff for the signature.
2076 if (Stream.Read(8) != 'C' ||
2077 Stream.Read(8) != 'P' ||
2078 Stream.Read(8) != 'C' ||
2079 Stream.Read(8) != 'H') {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002080 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002081 return std::string();
2082 }
2083
2084 RecordData Record;
2085 while (!Stream.AtEndOfStream()) {
2086 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Douglas Gregorb64c1932009-05-12 01:31:05 +00002088 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2089 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Douglas Gregorb64c1932009-05-12 01:31:05 +00002091 // We only know the PCH subblock ID.
2092 switch (BlockID) {
2093 case pch::PCH_BLOCK_ID:
2094 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002095 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002096 return std::string();
2097 }
2098 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Douglas Gregorb64c1932009-05-12 01:31:05 +00002100 default:
2101 if (Stream.SkipBlock()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002102 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002103 return std::string();
2104 }
2105 break;
2106 }
2107 continue;
2108 }
2109
2110 if (Code == llvm::bitc::END_BLOCK) {
2111 if (Stream.ReadBlockEnd()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002112 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002113 return std::string();
2114 }
2115 continue;
2116 }
2117
2118 if (Code == llvm::bitc::DEFINE_ABBREV) {
2119 Stream.ReadAbbrevRecord();
2120 continue;
2121 }
2122
2123 Record.clear();
2124 const char *BlobStart = 0;
2125 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002126 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00002127 == pch::ORIGINAL_FILE_NAME)
2128 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00002129 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00002130
2131 return std::string();
2132}
2133
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002134/// \brief Parse the record that corresponds to a LangOptions data
2135/// structure.
2136///
2137/// This routine compares the language options used to generate the
2138/// PCH file against the language options set for the current
2139/// compilation. For each option, we classify differences between the
2140/// two compiler states as either "benign" or "important". Benign
2141/// differences don't matter, and we accept them without complaint
2142/// (and without modifying the language options). Differences between
2143/// the states for important options cause the PCH file to be
2144/// unusable, so we emit a warning and return true to indicate that
2145/// there was an error.
2146///
2147/// \returns true if the PCH file is unacceptable, false otherwise.
2148bool PCHReader::ParseLanguageOptions(
2149 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002150 if (Listener) {
2151 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002153 #define PARSE_LANGOPT(Option) \
2154 LangOpts.Option = Record[Idx]; \
2155 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002157 unsigned Idx = 0;
2158 PARSE_LANGOPT(Trigraphs);
2159 PARSE_LANGOPT(BCPLComment);
2160 PARSE_LANGOPT(DollarIdents);
2161 PARSE_LANGOPT(AsmPreprocessor);
2162 PARSE_LANGOPT(GNUMode);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +00002163 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002164 PARSE_LANGOPT(ImplicitInt);
2165 PARSE_LANGOPT(Digraphs);
2166 PARSE_LANGOPT(HexFloats);
2167 PARSE_LANGOPT(C99);
2168 PARSE_LANGOPT(Microsoft);
2169 PARSE_LANGOPT(CPlusPlus);
2170 PARSE_LANGOPT(CPlusPlus0x);
2171 PARSE_LANGOPT(CXXOperatorNames);
2172 PARSE_LANGOPT(ObjC1);
2173 PARSE_LANGOPT(ObjC2);
2174 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002175 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +00002176 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002177 PARSE_LANGOPT(PascalStrings);
2178 PARSE_LANGOPT(WritableStrings);
2179 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002180 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002181 PARSE_LANGOPT(Exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +00002182 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002183 PARSE_LANGOPT(NeXTRuntime);
2184 PARSE_LANGOPT(Freestanding);
2185 PARSE_LANGOPT(NoBuiltin);
2186 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00002187 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002188 PARSE_LANGOPT(Blocks);
2189 PARSE_LANGOPT(EmitAllDecls);
2190 PARSE_LANGOPT(MathErrno);
Chris Lattnera4d71452010-06-26 21:25:03 +00002191 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2192 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002193 PARSE_LANGOPT(HeinousExtensions);
2194 PARSE_LANGOPT(Optimize);
2195 PARSE_LANGOPT(OptimizeSize);
2196 PARSE_LANGOPT(Static);
2197 PARSE_LANGOPT(PICLevel);
2198 PARSE_LANGOPT(GNUInline);
2199 PARSE_LANGOPT(NoInline);
2200 PARSE_LANGOPT(AccessControl);
2201 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00002202 PARSE_LANGOPT(ShortWChar);
Chris Lattnera4d71452010-06-26 21:25:03 +00002203 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2204 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbarab8e2812009-09-21 04:16:19 +00002205 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattnera4d71452010-06-26 21:25:03 +00002206 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002207 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002208 PARSE_LANGOPT(OpenCL);
Mike Stump9c276ae2009-12-12 01:27:46 +00002209 PARSE_LANGOPT(CatchUndefined);
2210 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002211 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002212
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002213 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002214 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002215
2216 return false;
2217}
2218
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002219void PCHReader::ReadPreprocessedEntities() {
2220 ReadDefinedMacros();
2221}
2222
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002223/// \brief Get the correct cursor and offset for loading a type.
2224PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
2225 PerFileData *F = 0;
2226 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2227 F = Chain[N - I - 1];
2228 if (Index < F->LocalNumTypes)
2229 break;
2230 Index -= F->LocalNumTypes;
2231 }
2232 assert(F && F->LocalNumTypes > Index && "Broken chain");
Sebastian Redl971dd442010-07-20 22:55:31 +00002233 return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002234}
2235
2236/// \brief Read and return the type with the given index..
Douglas Gregor2cf26342009-04-09 22:27:44 +00002237///
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002238/// The index is the type ID, shifted and minus the number of predefs. This
2239/// routine actually reads the record corresponding to the type at the given
2240/// location. It is a helper routine for GetType, which deals with reading type
2241/// IDs.
2242QualType PCHReader::ReadTypeRecord(unsigned Index) {
2243 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redl971dd442010-07-20 22:55:31 +00002244 llvm::BitstreamCursor &DeclsCursor = *Loc.first;
Sebastian Redl9137a522010-07-16 17:50:48 +00002245
Douglas Gregor0b748912009-04-14 21:18:50 +00002246 // Keep track of where we are in the stream, then jump back there
2247 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002248 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002249
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002250 ReadingKindTracker ReadingKind(Read_Type, *this);
2251
Douglas Gregord89275b2009-07-06 18:54:52 +00002252 // Note that we are loading a type record.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00002253 Deserializing AType(this);
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002255 DeclsCursor.JumpToBit(Loc.second);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002256 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002257 unsigned Code = DeclsCursor.ReadCode();
2258 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00002259 case pch::TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002260 if (Record.size() != 2) {
2261 Error("Incorrect encoding of extended qualifier type");
2262 return QualType();
2263 }
Douglas Gregor6d473962009-04-15 22:00:08 +00002264 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00002265 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2266 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00002267 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002268
Douglas Gregor2cf26342009-04-09 22:27:44 +00002269 case pch::TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002270 if (Record.size() != 1) {
2271 Error("Incorrect encoding of complex type");
2272 return QualType();
2273 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002274 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002275 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002276 }
2277
2278 case pch::TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002279 if (Record.size() != 1) {
2280 Error("Incorrect encoding of pointer type");
2281 return QualType();
2282 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002283 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002284 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002285 }
2286
2287 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002288 if (Record.size() != 1) {
2289 Error("Incorrect encoding of block pointer type");
2290 return QualType();
2291 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002292 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002293 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002294 }
2295
2296 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002297 if (Record.size() != 1) {
2298 Error("Incorrect encoding of lvalue reference type");
2299 return QualType();
2300 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002301 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002302 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002303 }
2304
2305 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002306 if (Record.size() != 1) {
2307 Error("Incorrect encoding of rvalue reference type");
2308 return QualType();
2309 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002310 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002311 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002312 }
2313
2314 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidis240437b2010-07-02 11:55:15 +00002315 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002316 Error("Incorrect encoding of member pointer type");
2317 return QualType();
2318 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002319 QualType PointeeType = GetType(Record[0]);
2320 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002321 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00002322 }
2323
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002324 case pch::TYPE_CONSTANT_ARRAY: {
2325 QualType ElementType = GetType(Record[0]);
2326 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2327 unsigned IndexTypeQuals = Record[2];
2328 unsigned Idx = 3;
2329 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002330 return Context->getConstantArrayType(ElementType, Size,
2331 ASM, IndexTypeQuals);
2332 }
2333
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002334 case pch::TYPE_INCOMPLETE_ARRAY: {
2335 QualType ElementType = GetType(Record[0]);
2336 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2337 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002338 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002339 }
2340
2341 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00002342 QualType ElementType = GetType(Record[0]);
2343 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2344 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002345 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2346 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Sebastian Redl577d4792010-07-22 22:43:28 +00002347 return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002348 ASM, IndexTypeQuals,
2349 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002350 }
2351
2352 case pch::TYPE_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002353 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002354 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002355 return QualType();
2356 }
2357
2358 QualType ElementType = GetType(Record[0]);
2359 unsigned NumElements = Record[1];
Chris Lattner788b0fd2010-06-23 06:00:24 +00002360 unsigned AltiVecSpec = Record[2];
2361 return Context->getVectorType(ElementType, NumElements,
2362 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002363 }
2364
2365 case pch::TYPE_EXT_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002366 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002367 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002368 return QualType();
2369 }
2370
2371 QualType ElementType = GetType(Record[0]);
2372 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002373 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002374 }
2375
2376 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola425ef722010-03-30 22:15:11 +00002377 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002378 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002379 return QualType();
2380 }
2381 QualType ResultType = GetType(Record[0]);
Rafael Espindola425ef722010-03-30 22:15:11 +00002382 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindola264ba482010-03-30 20:24:48 +00002383 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002384 }
2385
2386 case pch::TYPE_FUNCTION_PROTO: {
2387 QualType ResultType = GetType(Record[0]);
Douglas Gregor91236662009-12-22 18:11:50 +00002388 bool NoReturn = Record[1];
Rafael Espindola425ef722010-03-30 22:15:11 +00002389 unsigned RegParm = Record[2];
2390 CallingConv CallConv = (CallingConv)Record[3];
2391 unsigned Idx = 4;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002392 unsigned NumParams = Record[Idx++];
2393 llvm::SmallVector<QualType, 16> ParamTypes;
2394 for (unsigned I = 0; I != NumParams; ++I)
2395 ParamTypes.push_back(GetType(Record[Idx++]));
2396 bool isVariadic = Record[Idx++];
2397 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00002398 bool hasExceptionSpec = Record[Idx++];
2399 bool hasAnyExceptionSpec = Record[Idx++];
2400 unsigned NumExceptions = Record[Idx++];
2401 llvm::SmallVector<QualType, 2> Exceptions;
2402 for (unsigned I = 0; I != NumExceptions; ++I)
2403 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00002404 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00002405 isVariadic, Quals, hasExceptionSpec,
2406 hasAnyExceptionSpec, NumExceptions,
Rafael Espindola264ba482010-03-30 20:24:48 +00002407 Exceptions.data(),
Rafael Espindola425ef722010-03-30 22:15:11 +00002408 FunctionType::ExtInfo(NoReturn, RegParm,
2409 CallConv));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002410 }
2411
John McCalled976492009-12-04 22:46:56 +00002412 case pch::TYPE_UNRESOLVED_USING:
2413 return Context->getTypeDeclType(
2414 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2415
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002416 case pch::TYPE_TYPEDEF: {
2417 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002418 Error("incorrect encoding of typedef type");
2419 return QualType();
2420 }
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002421 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2422 QualType Canonical = GetType(Record[1]);
2423 return Context->getTypedefType(Decl, Canonical);
2424 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002425
2426 case pch::TYPE_TYPEOF_EXPR:
Sebastian Redl577d4792010-07-22 22:43:28 +00002427 return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002428
2429 case pch::TYPE_TYPEOF: {
2430 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002431 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002432 return QualType();
2433 }
2434 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002435 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002436 }
Mike Stump1eb44332009-09-09 15:08:12 +00002437
Anders Carlsson395b4752009-06-24 19:06:50 +00002438 case pch::TYPE_DECLTYPE:
Sebastian Redl577d4792010-07-22 22:43:28 +00002439 return Context->getDecltypeType(ReadExpr(DeclsCursor));
Anders Carlsson395b4752009-06-24 19:06:50 +00002440
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002441 case pch::TYPE_RECORD: {
2442 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002443 Error("incorrect encoding of record type");
2444 return QualType();
2445 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002446 bool IsDependent = Record[0];
2447 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2448 T->Dependent = IsDependent;
2449 return T;
2450 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002451
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002452 case pch::TYPE_ENUM: {
2453 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002454 Error("incorrect encoding of enum type");
2455 return QualType();
2456 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002457 bool IsDependent = Record[0];
2458 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2459 T->Dependent = IsDependent;
2460 return T;
2461 }
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002462
John McCall7da24312009-09-05 00:15:47 +00002463 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002464 unsigned Idx = 0;
2465 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2466 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2467 QualType NamedType = GetType(Record[Idx++]);
2468 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCall7da24312009-09-05 00:15:47 +00002469 }
2470
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002471 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002472 unsigned Idx = 0;
2473 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002474 return Context->getObjCInterfaceType(ItfD);
2475 }
2476
2477 case pch::TYPE_OBJC_OBJECT: {
2478 unsigned Idx = 0;
2479 QualType Base = GetType(Record[Idx++]);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002480 unsigned NumProtos = Record[Idx++];
2481 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2482 for (unsigned I = 0; I != NumProtos; ++I)
2483 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCallc12c5bb2010-05-15 11:32:37 +00002484 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002485 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002486
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002487 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002488 unsigned Idx = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002489 QualType Pointee = GetType(Record[Idx++]);
2490 return Context->getObjCObjectPointerType(Pointee);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002491 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00002492
John McCall49a832b2009-10-18 09:09:24 +00002493 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2494 unsigned Idx = 0;
2495 QualType Parm = GetType(Record[Idx++]);
2496 QualType Replacement = GetType(Record[Idx++]);
2497 return
2498 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2499 Replacement);
2500 }
John McCall3cb0ebd2010-03-10 03:28:59 +00002501
2502 case pch::TYPE_INJECTED_CLASS_NAME: {
2503 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2504 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00002505 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2506 // for PCH reading, too much interdependencies.
2507 return
2508 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCall3cb0ebd2010-03-10 03:28:59 +00002509 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002510
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002511 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2512 unsigned Idx = 0;
2513 unsigned Depth = Record[Idx++];
2514 unsigned Index = Record[Idx++];
2515 bool Pack = Record[Idx++];
2516 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2517 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2518 }
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002519
2520 case pch::TYPE_DEPENDENT_NAME: {
2521 unsigned Idx = 0;
2522 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2523 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2524 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidisf48d45e2010-07-02 11:55:24 +00002525 QualType Canon = GetType(Record[Idx++]);
2526 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002527 }
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002528
2529 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2530 unsigned Idx = 0;
2531 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2532 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2533 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2534 unsigned NumArgs = Record[Idx++];
2535 llvm::SmallVector<TemplateArgument, 8> Args;
2536 Args.reserve(NumArgs);
2537 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00002538 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002539 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2540 Args.size(), Args.data());
2541 }
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002542
2543 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2544 unsigned Idx = 0;
2545
2546 // ArrayType
2547 QualType ElementType = GetType(Record[Idx++]);
2548 ArrayType::ArraySizeModifier ASM
2549 = (ArrayType::ArraySizeModifier)Record[Idx++];
2550 unsigned IndexTypeQuals = Record[Idx++];
2551
2552 // DependentSizedArrayType
Sebastian Redl577d4792010-07-22 22:43:28 +00002553 Expr *NumElts = ReadExpr(DeclsCursor);
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002554 SourceRange Brackets = ReadSourceRange(Record, Idx);
2555
2556 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2557 IndexTypeQuals, Brackets);
2558 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002559
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002560 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2561 unsigned Idx = 0;
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002562 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002563 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002564 llvm::SmallVector<TemplateArgument, 8> Args;
Sebastian Redl577d4792010-07-22 22:43:28 +00002565 ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00002566 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002567 QualType T;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002568 if (Canon.isNull())
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002569 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2570 Args.size());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002571 else
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002572 T = Context->getTemplateSpecializationType(Name, Args.data(),
2573 Args.size(), Canon);
2574 T->Dependent = IsDependent;
2575 return T;
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002576 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002577 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002578 // Suppress a GCC warning
2579 return QualType();
2580}
2581
John McCalla1ee0c52009-10-16 21:56:05 +00002582namespace {
2583
2584class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2585 PCHReader &Reader;
Sebastian Redl577d4792010-07-22 22:43:28 +00002586 llvm::BitstreamCursor &DeclsCursor;
John McCalla1ee0c52009-10-16 21:56:05 +00002587 const PCHReader::RecordData &Record;
2588 unsigned &Idx;
2589
2590public:
Sebastian Redl577d4792010-07-22 22:43:28 +00002591 TypeLocReader(PCHReader &Reader, llvm::BitstreamCursor &Cursor,
2592 const PCHReader::RecordData &Record, unsigned &Idx)
2593 : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
John McCalla1ee0c52009-10-16 21:56:05 +00002594
John McCall51bd8032009-10-18 01:05:36 +00002595 // We want compile-time assurance that we've enumerated all of
2596 // these, so unfortunately we have to declare them first, then
2597 // define them out-of-line.
2598#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00002599#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002600 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002601#include "clang/AST/TypeLocNodes.def"
2602
John McCall51bd8032009-10-18 01:05:36 +00002603 void VisitFunctionTypeLoc(FunctionTypeLoc);
2604 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002605};
2606
2607}
2608
John McCall51bd8032009-10-18 01:05:36 +00002609void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002610 // nothing to do
2611}
John McCall51bd8032009-10-18 01:05:36 +00002612void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorddf889a2010-01-18 18:04:31 +00002613 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2614 if (TL.needsExtraLocalData()) {
2615 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2616 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2617 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2618 TL.setModeAttr(Record[Idx++]);
2619 }
John McCalla1ee0c52009-10-16 21:56:05 +00002620}
John McCall51bd8032009-10-18 01:05:36 +00002621void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2622 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002623}
John McCall51bd8032009-10-18 01:05:36 +00002624void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2625 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002626}
John McCall51bd8032009-10-18 01:05:36 +00002627void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2628 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002629}
John McCall51bd8032009-10-18 01:05:36 +00002630void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2631 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002632}
John McCall51bd8032009-10-18 01:05:36 +00002633void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2634 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002635}
John McCall51bd8032009-10-18 01:05:36 +00002636void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2637 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002638}
John McCall51bd8032009-10-18 01:05:36 +00002639void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2640 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2641 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002642 if (Record[Idx++])
Sebastian Redl577d4792010-07-22 22:43:28 +00002643 TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002644 else
John McCall51bd8032009-10-18 01:05:36 +00002645 TL.setSizeExpr(0);
2646}
2647void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2648 VisitArrayTypeLoc(TL);
2649}
2650void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2651 VisitArrayTypeLoc(TL);
2652}
2653void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2654 VisitArrayTypeLoc(TL);
2655}
2656void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2657 DependentSizedArrayTypeLoc TL) {
2658 VisitArrayTypeLoc(TL);
2659}
2660void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2661 DependentSizedExtVectorTypeLoc TL) {
2662 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2663}
2664void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2665 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2666}
2667void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2668 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2669}
2670void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2671 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2672 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2673 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002674 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002675 }
2676}
2677void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2678 VisitFunctionTypeLoc(TL);
2679}
2680void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2681 VisitFunctionTypeLoc(TL);
2682}
John McCalled976492009-12-04 22:46:56 +00002683void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2684 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2685}
John McCall51bd8032009-10-18 01:05:36 +00002686void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2687 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2688}
2689void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002690 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2691 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2692 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002693}
2694void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002695 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2696 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2697 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Sebastian Redl577d4792010-07-22 22:43:28 +00002698 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002699}
2700void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2701 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2702}
2703void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2704 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2705}
2706void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2707 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2708}
John McCall51bd8032009-10-18 01:05:36 +00002709void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2710 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2711}
John McCall49a832b2009-10-18 09:09:24 +00002712void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2713 SubstTemplateTypeParmTypeLoc TL) {
2714 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2715}
John McCall51bd8032009-10-18 01:05:36 +00002716void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2717 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002718 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2719 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2720 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2721 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2722 TL.setArgLocInfo(i,
2723 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002724 DeclsCursor, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002725}
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002726void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002727 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2728 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002729}
John McCall3cb0ebd2010-03-10 03:28:59 +00002730void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2731 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2732}
Douglas Gregor4714c122010-03-31 17:34:00 +00002733void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002734 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2735 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002736 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2737}
John McCall33500952010-06-11 00:33:02 +00002738void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2739 DependentTemplateSpecializationTypeLoc TL) {
2740 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2741 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2742 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2743 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2744 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2745 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2746 TL.setArgLocInfo(I,
2747 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002748 DeclsCursor, Record, Idx));
John McCall33500952010-06-11 00:33:02 +00002749}
John McCall51bd8032009-10-18 01:05:36 +00002750void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2751 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002752}
2753void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2754 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall51bd8032009-10-18 01:05:36 +00002755 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2756 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2757 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2758 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002759}
John McCall54e14c42009-10-22 22:37:11 +00002760void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2761 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall54e14c42009-10-22 22:37:11 +00002762}
John McCalla1ee0c52009-10-16 21:56:05 +00002763
Sebastian Redl577d4792010-07-22 22:43:28 +00002764TypeSourceInfo *PCHReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2765 const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00002766 unsigned &Idx) {
2767 QualType InfoTy = GetType(Record[Idx++]);
2768 if (InfoTy.isNull())
2769 return 0;
2770
John McCalla93c9342009-12-07 02:54:59 +00002771 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
Sebastian Redl577d4792010-07-22 22:43:28 +00002772 TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00002773 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00002774 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00002775 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00002776}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002777
Douglas Gregor8038d512009-04-10 17:25:41 +00002778QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002779 unsigned FastQuals = ID & Qualifiers::FastMask;
2780 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002781
2782 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2783 QualType T;
2784 switch ((pch::PredefinedTypeIDs)Index) {
2785 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002786 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2787 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002788
2789 case pch::PREDEF_TYPE_CHAR_U_ID:
2790 case pch::PREDEF_TYPE_CHAR_S_ID:
2791 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002792 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002793 break;
2794
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002795 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2796 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2797 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2798 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2799 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002800 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002801 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2802 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2803 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2804 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2805 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2806 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002807 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002808 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2809 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2810 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2811 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2812 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002813 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002814 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2815 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002816 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2817 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002818 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002819 }
2820
2821 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002822 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002823 }
2824
2825 Index -= pch::NUM_PREDEF_TYPE_IDS;
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002826 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl07a353c2010-07-14 20:26:45 +00002827 if (TypesLoaded[Index].isNull()) {
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002828 TypesLoaded[Index] = ReadTypeRecord(Index);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002829 TypesLoaded[Index]->setFromPCH();
Sebastian Redl30c514c2010-07-14 23:45:08 +00002830 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002831 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2832 TypesLoaded[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002833 }
Mike Stump1eb44332009-09-09 15:08:12 +00002834
John McCall0953e762009-09-24 19:53:00 +00002835 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002836}
2837
John McCall833ca992009-10-29 08:12:44 +00002838TemplateArgumentLocInfo
2839PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Sebastian Redl577d4792010-07-22 22:43:28 +00002840 llvm::BitstreamCursor &DeclsCursor,
John McCall833ca992009-10-29 08:12:44 +00002841 const RecordData &Record,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002842 unsigned &Index) {
John McCall833ca992009-10-29 08:12:44 +00002843 switch (Kind) {
2844 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00002845 return ReadExpr(DeclsCursor);
John McCall833ca992009-10-29 08:12:44 +00002846 case TemplateArgument::Type:
Sebastian Redl577d4792010-07-22 22:43:28 +00002847 return GetTypeSourceInfo(DeclsCursor, Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002848 case TemplateArgument::Template: {
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002849 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2850 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2851 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor788cd062009-11-11 01:00:40 +00002852 }
John McCall833ca992009-10-29 08:12:44 +00002853 case TemplateArgument::Null:
2854 case TemplateArgument::Integral:
2855 case TemplateArgument::Declaration:
2856 case TemplateArgument::Pack:
2857 return TemplateArgumentLocInfo();
2858 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002859 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00002860 return TemplateArgumentLocInfo();
2861}
2862
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002863TemplateArgumentLoc
Sebastian Redl577d4792010-07-22 22:43:28 +00002864PCHReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
2865 const RecordData &Record, unsigned &Index) {
2866 TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002867
2868 if (Arg.getKind() == TemplateArgument::Expression) {
2869 if (Record[Index++]) // bool InfoHasSameExpr.
2870 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2871 }
2872 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002873 DeclsCursor,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002874 Record, Index));
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00002875}
2876
John McCall76bd1f32010-06-01 09:23:16 +00002877Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2878 return GetDecl(ID);
2879}
2880
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002881TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl30c514c2010-07-14 23:45:08 +00002882 if (!DeclsLoaded[0]) {
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00002883 ReadDeclRecord(0, 0);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002884 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002885 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002886 }
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002887
2888 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2889}
2890
Douglas Gregor8038d512009-04-10 17:25:41 +00002891Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002892 if (ID == 0)
2893 return 0;
2894
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002895 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002896 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002897 return 0;
2898 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002899
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002900 unsigned Index = ID - 1;
Sebastian Redl30c514c2010-07-14 23:45:08 +00002901 if (!DeclsLoaded[Index]) {
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00002902 ReadDeclRecord(Index, ID);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002903 if (DeserializationListener)
2904 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2905 }
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002906
2907 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002908}
2909
Chris Lattner887e2b32009-04-27 05:46:25 +00002910/// \brief Resolve the offset of a statement into a statement.
2911///
2912/// This operation will read a new statement from the external
2913/// source each time it is called, and is meant to be used via a
2914/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall76bd1f32010-06-01 09:23:16 +00002915Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002916 // Offset here is a global offset across the entire chain.
2917 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2918 PerFileData &F = *Chain[N - I - 1];
2919 if (Offset < F.SizeInBits) {
2920 // Since we know that this statement is part of a decl, make sure to use
2921 // the decl cursor to read it.
2922 F.DeclsCursor.JumpToBit(Offset);
2923 return ReadStmtFromStream(F.DeclsCursor);
2924 }
2925 Offset -= F.SizeInBits;
2926 }
2927 llvm_unreachable("Broken chain");
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002928}
2929
John McCall76bd1f32010-06-01 09:23:16 +00002930bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2931 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002932 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002933 "DeclContext has no lexical decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002934
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002935 // There might be lexical decls in multiple parts of the chain, for the TU
2936 // at least.
2937 DeclContextInfos &Infos = DeclContextOffsets[DC];
2938 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2939 I != E; ++I) {
Sebastian Redl681d7232010-07-27 00:17:23 +00002940 // IDs can be 0 if this context doesn't contain declarations.
2941 if (!I->LexicalDecls)
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002942 continue;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002943
2944 // Load all of the declaration IDs
Sebastian Redl681d7232010-07-27 00:17:23 +00002945 for (const pch::DeclID *ID = I->LexicalDecls,
2946 *IDE = ID + I->NumLexicalDecls;
2947 ID != IDE; ++ID)
2948 Decls.push_back(GetDecl(*ID));
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002949 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002950
Douglas Gregor25123082009-04-22 22:34:57 +00002951 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002952 return false;
2953}
2954
John McCall76bd1f32010-06-01 09:23:16 +00002955DeclContext::lookup_result
2956PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2957 DeclarationName Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00002958 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002959 "DeclContext has no visible decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002960
John McCall76bd1f32010-06-01 09:23:16 +00002961 llvm::SmallVector<VisibleDeclaration, 64> Decls;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002962 // There might be lexical decls in multiple parts of the chain, for the TU
2963 // and namespaces.
2964 DeclContextInfos &Infos = DeclContextOffsets[DC];
2965 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2966 I != E; ++I) {
2967 uint64_t Offset = I->OffsetToVisibleDecls;
2968 if (Offset == 0)
2969 continue;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002970
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002971 llvm::BitstreamCursor &DeclsCursor = *I->Stream;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002972
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002973 // Keep track of where we are in the stream, then jump back there
2974 // after reading this context.
2975 SavedStreamPosition SavedPosition(DeclsCursor);
2976
2977 // Load the record containing all of the declarations visible in
2978 // this context.
2979 DeclsCursor.JumpToBit(Offset);
2980 RecordData Record;
2981 unsigned Code = DeclsCursor.ReadCode();
2982 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2983 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2984 Error("Expected visible block");
2985 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2986 DeclContext::lookup_iterator());
2987 }
2988
2989 if (Record.empty())
2990 continue;
2991
2992 unsigned Idx = 0;
2993 while (Idx < Record.size()) {
2994 Decls.push_back(VisibleDeclaration());
2995 Decls.back().Name = ReadDeclarationName(Record, Idx);
2996
2997 unsigned Size = Record[Idx++];
2998 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
2999 LoadedDecls.reserve(Size);
3000 for (unsigned J = 0; J < Size; ++J)
3001 LoadedDecls.push_back(Record[Idx++]);
3002 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003003 }
3004
Douglas Gregor25123082009-04-22 22:34:57 +00003005 ++NumVisibleDeclContextsRead;
John McCall76bd1f32010-06-01 09:23:16 +00003006
3007 SetExternalVisibleDecls(DC, Decls);
3008 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregor2cf26342009-04-09 22:27:44 +00003009}
3010
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003011void PCHReader::PassInterestingDeclsToConsumer() {
3012 assert(Consumer);
3013 while (!InterestingDecls.empty()) {
3014 DeclGroupRef DG(InterestingDecls.front());
3015 InterestingDecls.pop_front();
3016 Consumer->HandleTopLevelDecl(DG);
3017 }
3018}
3019
Douglas Gregorfdd01722009-04-14 00:24:19 +00003020void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00003021 this->Consumer = Consumer;
3022
Douglas Gregorfdd01722009-04-14 00:24:19 +00003023 if (!Consumer)
3024 return;
3025
3026 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003027 // Force deserialization of this decl, which will cause it to be queued for
3028 // passing to the consumer.
Daniel Dunbar04a0b502009-09-17 03:06:44 +00003029 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00003030 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00003031
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003032 PassInterestingDeclsToConsumer();
Douglas Gregorfdd01722009-04-14 00:24:19 +00003033}
3034
Douglas Gregor2cf26342009-04-09 22:27:44 +00003035void PCHReader::PrintStats() {
3036 std::fprintf(stderr, "*** PCH Statistics:\n");
3037
Mike Stump1eb44332009-09-09 15:08:12 +00003038 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003039 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00003040 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003041 unsigned NumDeclsLoaded
3042 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3043 (Decl *)0);
3044 unsigned NumIdentifiersLoaded
3045 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3046 IdentifiersLoaded.end(),
3047 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00003048 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003049 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3050 SelectorsLoaded.end(),
3051 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00003052
Douglas Gregor4fed3f42009-04-27 18:38:38 +00003053 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
3054 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003055 if (TotalNumSLocEntries)
3056 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
3057 NumSLocEntriesRead, TotalNumSLocEntries,
3058 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003059 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003060 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003061 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3062 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3063 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003064 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003065 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3066 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003067 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003068 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003069 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3070 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00003071 if (TotalNumSelectors)
3072 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
3073 NumSelectorsLoaded, TotalNumSelectors,
3074 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
3075 if (TotalNumStatements)
3076 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3077 NumStatementsRead, TotalNumStatements,
3078 ((float)NumStatementsRead/TotalNumStatements * 100));
3079 if (TotalNumMacros)
3080 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3081 NumMacrosRead, TotalNumMacros,
3082 ((float)NumMacrosRead/TotalNumMacros * 100));
3083 if (TotalLexicalDeclContexts)
3084 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3085 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3086 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3087 * 100));
3088 if (TotalVisibleDeclContexts)
3089 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3090 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3091 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3092 * 100));
3093 if (TotalSelectorsInMethodPool) {
3094 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
3095 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
3096 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
3097 * 100));
3098 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
3099 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003100 std::fprintf(stderr, "\n");
3101}
3102
Douglas Gregor668c1a42009-04-21 22:25:48 +00003103void PCHReader::InitializeSema(Sema &S) {
3104 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003105 S.ExternalSource = this;
3106
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003107 // Makes sure any declarations that were deserialized "too early"
3108 // still get added to the identifier's declaration chains.
3109 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3110 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3111 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003112 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003113 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003114
3115 // If there were any tentative definitions, deserialize them and add
Sebastian Redle9d12b62010-01-31 22:27:38 +00003116 // them to Sema's list of tentative definitions.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003117 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3118 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redle9d12b62010-01-31 22:27:38 +00003119 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003120 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00003121
Tanya Lattnere6bbc012010-02-12 00:07:30 +00003122 // If there were any unused static functions, deserialize them and add to
3123 // Sema's list of unused static functions.
3124 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
3125 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3126 SemaObj->UnusedStaticFuncs.push_back(FD);
3127 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00003128
3129 // If there were any locally-scoped external declarations,
3130 // deserialize them and add them to Sema's table of locally-scoped
3131 // external declarations.
3132 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3133 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3134 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3135 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00003136
3137 // If there were any ext_vector type declarations, deserialize them
3138 // and add them to Sema's vector of such declarations.
3139 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3140 SemaObj->ExtVectorDecls.push_back(
3141 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003142
3143 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3144 // Can we cut them down before writing them ?
3145
3146 // If there were any VTable uses, deserialize the information and add it
3147 // to Sema's vector and map of VTable uses.
Argyrios Kyrtzidisbe4ebcd2010-08-03 17:29:52 +00003148 if (!VTableUses.empty()) {
3149 unsigned Idx = 0;
3150 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3151 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3152 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3153 bool DefinitionRequired = VTableUses[Idx++];
3154 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3155 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3156 }
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003157 }
3158
3159 // If there were any dynamic classes declarations, deserialize them
3160 // and add them to Sema's vector of such declarations.
3161 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3162 SemaObj->DynamicClasses.push_back(
3163 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Fariborz Jahanian32019832010-07-23 19:11:11 +00003164
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003165 // Load the offsets of the declarations that Sema references.
3166 // They will be lazily deserialized when needed.
3167 if (!SemaDeclRefs.empty()) {
3168 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
3169 SemaObj->StdNamespace = SemaDeclRefs[0];
3170 SemaObj->StdBadAlloc = SemaDeclRefs[1];
3171 }
3172
Fariborz Jahanian32019832010-07-23 19:11:11 +00003173 // If there are @selector references added them to its pool. This is for
3174 // implementation of -Wselector.
3175 PerFileData &F = *Chain[0];
3176 if (!F.ReferencedSelectorsData.empty()) {
3177 unsigned int DataSize = F.ReferencedSelectorsData.size()-1;
3178 unsigned I = 0;
3179 while (I < DataSize) {
3180 Selector Sel = DecodeSelector(F.ReferencedSelectorsData[I++]);
3181 SourceLocation SelLoc =
3182 SourceLocation::getFromRawEncoding(F.ReferencedSelectorsData[I++]);
3183 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3184 }
3185 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00003186}
3187
3188IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003189 // Try to find this name within our on-disk hash tables. We start with the
3190 // most recent one, since that one contains the most up-to-date info.
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003191 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3192 PCHIdentifierLookupTable *IdTable
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003193 = (PCHIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00003194 if (!IdTable)
3195 continue;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003196 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3197 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3198 if (Pos == IdTable->end())
3199 continue;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003200
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003201 // Dereferencing the iterator has the effect of building the
3202 // IdentifierInfo node and populating it with the various
3203 // declarations it needs.
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003204 return *Pos;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003205 }
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003206 return 0;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003207}
3208
Mike Stump1eb44332009-09-09 15:08:12 +00003209std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003210PCHReader::ReadMethodPool(Selector Sel) {
3211 if (!MethodPoolLookupTable)
3212 return std::pair<ObjCMethodList, ObjCMethodList>();
3213
3214 // Try to find this selector within our on-disk hash table.
3215 PCHMethodPoolLookupTable *PoolTable
3216 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
3217 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00003218 if (Pos == PoolTable->end()) {
3219 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003220 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00003221 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003222
Douglas Gregor83941df2009-04-25 17:48:32 +00003223 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003224 return *Pos;
3225}
3226
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003227void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00003228 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00003229 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003230 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003231 if (DeserializationListener)
3232 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003233}
3234
Douglas Gregord89275b2009-07-06 18:54:52 +00003235/// \brief Set the globally-visible declarations associated with the given
3236/// identifier.
3237///
3238/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00003239/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00003240/// them.
3241///
3242/// \param II an IdentifierInfo that refers to one or more globally-visible
3243/// declarations.
3244///
3245/// \param DeclIDs the set of declaration IDs with the name @p II that are
3246/// visible at global scope.
3247///
3248/// \param Nonrecursive should be true to indicate that the caller knows that
3249/// this call is non-recursive, and therefore the globally-visible declarations
3250/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00003251void
3252PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00003253 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3254 bool Nonrecursive) {
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003255 if (NumCurrentElementsDeserializing && !Nonrecursive) {
Douglas Gregord89275b2009-07-06 18:54:52 +00003256 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3257 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3258 PII.II = II;
3259 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3260 PII.DeclIDs.push_back(DeclIDs[I]);
3261 return;
3262 }
Mike Stump1eb44332009-09-09 15:08:12 +00003263
Douglas Gregord89275b2009-07-06 18:54:52 +00003264 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3265 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3266 if (SemaObj) {
3267 // Introduce this declaration into the translation-unit scope
3268 // and add it to the declaration chain for this identifier, so
3269 // that (unqualified) name lookup will find it.
3270 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3271 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3272 } else {
3273 // Queue this declaration so that it will be added to the
3274 // translation unit scope and identifier's declaration chain
3275 // once a Sema object is known.
3276 PreloadedDecls.push_back(D);
3277 }
3278 }
3279}
3280
Chris Lattner7356a312009-04-11 21:15:38 +00003281IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00003282 if (ID == 0)
3283 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003284
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003285 if (IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003286 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00003287 return 0;
3288 }
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003290 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003291 ID -= 1;
3292 if (!IdentifiersLoaded[ID]) {
3293 unsigned Index = ID;
3294 const char *Str = 0;
3295 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3296 PerFileData *F = Chain[N - I - 1];
3297 if (Index < F->LocalNumIdentifiers) {
3298 uint32_t Offset = F->IdentifierOffsets[Index];
3299 Str = F->IdentifierTableData + Offset;
3300 break;
3301 }
3302 Index -= F->LocalNumIdentifiers;
3303 }
3304 assert(Str && "Broken Chain");
Douglas Gregord6595a42009-04-25 21:04:17 +00003305
Douglas Gregor02fc7512009-04-28 20:01:51 +00003306 // All of the strings in the PCH file are preceded by a 16-bit
3307 // length. Extract that 16-bit length to avoid having to execute
3308 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00003309 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3310 // unsigned integers. This is important to avoid integer overflow when
3311 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00003312 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00003313 unsigned StrLen = (((unsigned) StrLenPtr[0])
3314 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003315 IdentifiersLoaded[ID]
Kovarththanan Rajaratnam811f4262010-03-12 10:32:27 +00003316 = &PP->getIdentifierTable().get(Str, StrLen);
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003317 if (DeserializationListener)
3318 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregorafaf3082009-04-11 00:14:32 +00003319 }
Mike Stump1eb44332009-09-09 15:08:12 +00003320
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003321 return IdentifiersLoaded[ID];
Douglas Gregor2cf26342009-04-09 22:27:44 +00003322}
3323
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003324void PCHReader::ReadSLocEntry(unsigned ID) {
3325 ReadSLocEntryRecord(ID);
3326}
3327
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003328Selector PCHReader::DecodeSelector(unsigned ID) {
3329 if (ID == 0)
3330 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Douglas Gregora02b1472009-04-28 21:53:25 +00003332 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003333 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00003334
3335 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003336 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003337 return Selector();
3338 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003339
3340 unsigned Index = ID - 1;
3341 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
3342 // Load this selector from the selector table.
3343 // FIXME: endianness portability issues with SelectorOffsets table
3344 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00003345 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00003346 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
3347 }
3348
3349 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003350}
3351
John McCall76bd1f32010-06-01 09:23:16 +00003352Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003353 return DecodeSelector(ID);
3354}
3355
John McCall76bd1f32010-06-01 09:23:16 +00003356uint32_t PCHReader::GetNumExternalSelectors() {
Douglas Gregor719770d2010-04-06 17:30:22 +00003357 return TotalNumSelectors + 1;
3358}
3359
Mike Stump1eb44332009-09-09 15:08:12 +00003360DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00003361PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3362 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3363 switch (Kind) {
3364 case DeclarationName::Identifier:
3365 return DeclarationName(GetIdentifierInfo(Record, Idx));
3366
3367 case DeclarationName::ObjCZeroArgSelector:
3368 case DeclarationName::ObjCOneArgSelector:
3369 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00003370 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003371
3372 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003373 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003374 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003375
3376 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003377 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003378 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003379
3380 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003381 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003382 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003383
3384 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003385 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00003386 (OverloadedOperatorKind)Record[Idx++]);
3387
Sean Hunt3e518bd2009-11-29 07:34:05 +00003388 case DeclarationName::CXXLiteralOperatorName:
3389 return Context->DeclarationNames.getCXXLiteralOperatorName(
3390 GetIdentifierInfo(Record, Idx));
3391
Douglas Gregor2cf26342009-04-09 22:27:44 +00003392 case DeclarationName::CXXUsingDirective:
3393 return DeclarationName::getUsingDirectiveName();
3394 }
3395
3396 // Required to silence GCC warning
3397 return DeclarationName();
3398}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003399
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003400TemplateName
3401PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3402 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3403 switch (Kind) {
3404 case TemplateName::Template:
3405 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3406
3407 case TemplateName::OverloadedTemplate: {
3408 unsigned size = Record[Idx++];
3409 UnresolvedSet<8> Decls;
3410 while (size--)
3411 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3412
3413 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3414 }
3415
3416 case TemplateName::QualifiedTemplate: {
3417 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3418 bool hasTemplKeyword = Record[Idx++];
3419 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3420 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3421 }
3422
3423 case TemplateName::DependentTemplate: {
3424 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3425 if (Record[Idx++]) // isIdentifier
3426 return Context->getDependentTemplateName(NNS,
3427 GetIdentifierInfo(Record, Idx));
3428 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00003429 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003430 }
3431 }
3432
3433 assert(0 && "Unhandled template name kind!");
3434 return TemplateName();
3435}
3436
3437TemplateArgument
Sebastian Redl577d4792010-07-22 22:43:28 +00003438PCHReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3439 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003440 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3441 case TemplateArgument::Null:
3442 return TemplateArgument();
3443 case TemplateArgument::Type:
3444 return TemplateArgument(GetType(Record[Idx++]));
3445 case TemplateArgument::Declaration:
3446 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00003447 case TemplateArgument::Integral: {
3448 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3449 QualType T = GetType(Record[Idx++]);
3450 return TemplateArgument(Value, T);
3451 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003452 case TemplateArgument::Template:
3453 return TemplateArgument(ReadTemplateName(Record, Idx));
3454 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00003455 return TemplateArgument(ReadExpr(DeclsCursor));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003456 case TemplateArgument::Pack: {
3457 unsigned NumArgs = Record[Idx++];
3458 llvm::SmallVector<TemplateArgument, 8> Args;
3459 Args.reserve(NumArgs);
3460 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003461 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003462 TemplateArgument TemplArg;
3463 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3464 return TemplArg;
3465 }
3466 }
3467
3468 assert(0 && "Unhandled template argument kind!");
3469 return TemplateArgument();
3470}
3471
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003472TemplateParameterList *
3473PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3474 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3475 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3476 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3477
3478 unsigned NumParams = Record[Idx++];
3479 llvm::SmallVector<NamedDecl *, 16> Params;
3480 Params.reserve(NumParams);
3481 while (NumParams--)
3482 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3483
3484 TemplateParameterList* TemplateParams =
3485 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3486 Params.data(), Params.size(), RAngleLoc);
3487 return TemplateParams;
3488}
3489
3490void
3491PCHReader::
3492ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
Sebastian Redl577d4792010-07-22 22:43:28 +00003493 llvm::BitstreamCursor &DeclsCursor,
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003494 const RecordData &Record, unsigned &Idx) {
3495 unsigned NumTemplateArgs = Record[Idx++];
3496 TemplArgs.reserve(NumTemplateArgs);
3497 while (NumTemplateArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003498 TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003499}
3500
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00003501/// \brief Read a UnresolvedSet structure.
3502void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3503 const RecordData &Record, unsigned &Idx) {
3504 unsigned NumDecls = Record[Idx++];
3505 while (NumDecls--) {
3506 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3507 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3508 Set.addDecl(D, AS);
3509 }
3510}
3511
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003512CXXBaseSpecifier
Nick Lewycky56062202010-07-26 16:56:01 +00003513PCHReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
3514 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003515 bool isVirtual = static_cast<bool>(Record[Idx++]);
3516 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3517 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Nick Lewycky56062202010-07-26 16:56:01 +00003518 TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003519 SourceRange Range = ReadSourceRange(Record, Idx);
Nick Lewycky56062202010-07-26 16:56:01 +00003520 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003521}
3522
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003523NestedNameSpecifier *
3524PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3525 unsigned N = Record[Idx++];
3526 NestedNameSpecifier *NNS = 0, *Prev = 0;
3527 for (unsigned I = 0; I != N; ++I) {
3528 NestedNameSpecifier::SpecifierKind Kind
3529 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3530 switch (Kind) {
3531 case NestedNameSpecifier::Identifier: {
3532 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3533 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3534 break;
3535 }
3536
3537 case NestedNameSpecifier::Namespace: {
3538 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3539 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3540 break;
3541 }
3542
3543 case NestedNameSpecifier::TypeSpec:
3544 case NestedNameSpecifier::TypeSpecWithTemplate: {
3545 Type *T = GetType(Record[Idx++]).getTypePtr();
3546 bool Template = Record[Idx++];
3547 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3548 break;
3549 }
3550
3551 case NestedNameSpecifier::Global: {
3552 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3553 // No associated value, and there can't be a prefix.
3554 break;
3555 }
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003556 }
Argyrios Kyrtzidisd2bb2c02010-07-07 15:46:30 +00003557 Prev = NNS;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003558 }
3559 return NNS;
3560}
3561
3562SourceRange
3563PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar8ee59392010-06-02 15:47:10 +00003564 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3565 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3566 return SourceRange(beg, end);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003567}
3568
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00003569/// \brief Read an integral value
3570llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3571 unsigned BitWidth = Record[Idx++];
3572 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3573 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3574 Idx += NumWords;
3575 return Result;
3576}
3577
3578/// \brief Read a signed integral value
3579llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3580 bool isUnsigned = Record[Idx++];
3581 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3582}
3583
Douglas Gregor17fc2232009-04-14 21:55:33 +00003584/// \brief Read a floating-point value
3585llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00003586 return llvm::APFloat(ReadAPInt(Record, Idx));
3587}
3588
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003589// \brief Read a string
3590std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3591 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00003592 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003593 Idx += Len;
3594 return Result;
3595}
3596
Chris Lattnerd2598362010-05-10 00:25:06 +00003597CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3598 unsigned &Idx) {
3599 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3600 return CXXTemporary::Create(*Context, Decl);
3601}
3602
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003603DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00003604 return Diag(SourceLocation(), DiagID);
3605}
3606
3607DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003608 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003609}
Douglas Gregor025452f2009-04-17 00:04:06 +00003610
Douglas Gregor668c1a42009-04-21 22:25:48 +00003611/// \brief Retrieve the identifier table associated with the
3612/// preprocessor.
3613IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003614 assert(PP && "Forgot to set Preprocessor ?");
3615 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00003616}
3617
Douglas Gregor025452f2009-04-17 00:04:06 +00003618/// \brief Record that the given ID maps to the given switch-case
3619/// statement.
3620void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3621 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3622 SwitchCaseStmts[ID] = SC;
3623}
3624
3625/// \brief Retrieve the switch-case statement with the given ID.
3626SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3627 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3628 return SwitchCaseStmts[ID];
3629}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003630
3631/// \brief Record that the given label statement has been
3632/// deserialized and has the given ID.
3633void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00003634 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003635 "Deserialized label twice");
3636 LabelStmts[ID] = S;
3637
3638 // If we've already seen any goto statements that point to this
3639 // label, resolve them now.
3640 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3641 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3642 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3643 Goto->second->setLabel(S);
3644 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003645
3646 // If we've already seen any address-label statements that point to
3647 // this label, resolve them now.
3648 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00003649 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003650 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00003651 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003652 AddrLabel != AddrLabels.second; ++AddrLabel)
3653 AddrLabel->second->setLabel(S);
3654 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003655}
3656
3657/// \brief Set the label of the given statement to the label
3658/// identified by ID.
3659///
3660/// Depending on the order in which the label and other statements
3661/// referencing that label occur, this operation may complete
3662/// immediately (updating the statement) or it may queue the
3663/// statement to be back-patched later.
3664void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3665 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3666 if (Label != LabelStmts.end()) {
3667 // We've already seen this label, so set the label of the goto and
3668 // we're done.
3669 S->setLabel(Label->second);
3670 } else {
3671 // We haven't seen this label yet, so add this goto to the set of
3672 // unresolved goto statements.
3673 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3674 }
3675}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003676
3677/// \brief Set the label of the given expression to the label
3678/// identified by ID.
3679///
3680/// Depending on the order in which the label and other statements
3681/// referencing that label occur, this operation may complete
3682/// immediately (updating the statement) or it may queue the
3683/// statement to be back-patched later.
3684void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3685 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3686 if (Label != LabelStmts.end()) {
3687 // We've already seen this label, so set the label of the
3688 // label-address expression and we're done.
3689 S->setLabel(Label->second);
3690 } else {
3691 // We haven't seen this label yet, so add this label-address
3692 // expression to the set of unresolved label-address expressions.
3693 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3694 }
3695}
Douglas Gregord89275b2009-07-06 18:54:52 +00003696
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003697void PCHReader::FinishedDeserializing() {
3698 assert(NumCurrentElementsDeserializing &&
3699 "FinishedDeserializing not paired with StartedDeserializing");
3700 if (NumCurrentElementsDeserializing == 1) {
Douglas Gregord89275b2009-07-06 18:54:52 +00003701 // If any identifiers with corresponding top-level declarations have
3702 // been loaded, load those declarations now.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003703 while (!PendingIdentifierInfos.empty()) {
3704 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
3705 PendingIdentifierInfos.front().DeclIDs, true);
3706 PendingIdentifierInfos.pop_front();
Douglas Gregord89275b2009-07-06 18:54:52 +00003707 }
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003708
3709 // We are not in recursive loading, so it's safe to pass the "interesting"
3710 // decls to the consumer.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003711 if (Consumer)
3712 PassInterestingDeclsToConsumer();
Douglas Gregord89275b2009-07-06 18:54:52 +00003713 }
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003714 --NumCurrentElementsDeserializing;
Douglas Gregord89275b2009-07-06 18:54:52 +00003715}