blob: ab8bd5957be8a22a7d5018669557a8f09c60a253 [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 Redl725cd962010-08-04 20:40:17 +0000421 Consumer(0), isysroot(isysroot), DisableValidation(DisableValidation),
422 NumStatHits(0), NumStatMisses(0), NumSLocEntriesRead(0),
423 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
Sebastian Redlfa78dec2010-08-04 21:22:45 +0000424 NumMacrosRead(0), TotalNumMacros(0), NumSelectorsRead(0),
425 NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0),
426 TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0),
Sebastian Redl725cd962010-08-04 20:40:17 +0000427 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
428 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000429 RelocatablePCH = false;
430}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000431
432PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000433 Diagnostic &Diags, const char *isysroot,
434 bool DisableValidation)
Sebastian Redl30c514c2010-07-14 23:45:08 +0000435 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
Sebastian Redl9137a522010-07-16 17:50:48 +0000436 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
Sebastian Redl725cd962010-08-04 20:40:17 +0000437 isysroot(isysroot), DisableValidation(DisableValidation), NumStatHits(0),
438 NumStatMisses(0), NumSLocEntriesRead(0), TotalNumSLocEntries(0),
439 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
Sebastian Redlfa78dec2010-08-04 21:22:45 +0000440 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
441 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
Sebastian Redl725cd962010-08-04 20:40:17 +0000442 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
443 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
444 NumCurrentElementsDeserializing(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000445 RelocatablePCH = false;
446}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000447
Sebastian Redl9137a522010-07-16 17:50:48 +0000448PCHReader::~PCHReader() {
449 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
450 delete Chain[e - i - 1];
451}
452
453PCHReader::PerFileData::PerFileData()
Sebastian Redl12d6da02010-07-19 22:06:55 +0000454 : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
Sebastian Redl2da08f92010-07-19 22:28:42 +0000455 LocalNumDecls(0), DeclOffsets(0), LocalNumIdentifiers(0),
Sebastian Redl04e6fd42010-07-21 20:07:32 +0000456 IdentifierOffsets(0), IdentifierTableData(0), IdentifierLookupTable(0),
457 LocalNumMacroDefinitions(0), MacroDefinitionOffsets(0),
Sebastian Redl725cd962010-08-04 20:40:17 +0000458 NumPreallocatedPreprocessingEntities(0), SelectorLookupTable(0),
459 SelectorLookupTableData(0), SelectorOffsets(0), LocalNumSelectors(0)
Sebastian Redl9137a522010-07-16 17:50:48 +0000460{}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000461
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000462void
463PCHReader::setDeserializationListener(PCHDeserializationListener *Listener) {
464 DeserializationListener = Listener;
465 if (DeserializationListener)
466 DeserializationListener->SetReader(this);
467}
468
Chris Lattner4c6f9522009-04-27 05:14:47 +0000469
Douglas Gregor668c1a42009-04-21 22:25:48 +0000470namespace {
Sebastian Redl725cd962010-08-04 20:40:17 +0000471class PCHSelectorLookupTrait {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000472 PCHReader &Reader;
473
474public:
Sebastian Redl5d050072010-08-04 17:20:04 +0000475 struct data_type {
476 pch::SelectorID ID;
477 ObjCMethodList Instance, Factory;
478 };
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000479
480 typedef Selector external_key_type;
481 typedef external_key_type internal_key_type;
482
Sebastian Redl725cd962010-08-04 20:40:17 +0000483 explicit PCHSelectorLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000485 static bool EqualKey(const internal_key_type& a,
486 const internal_key_type& b) {
487 return a == b;
488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000490 static unsigned ComputeHash(Selector Sel) {
491 unsigned N = Sel.getNumArgs();
492 if (N == 0)
493 ++N;
494 unsigned R = 5381;
495 for (unsigned I = 0; I != N; ++I)
496 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000497 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000498 return R;
499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000501 // This hopefully will just get inlined and removed by the optimizer.
502 static const internal_key_type&
503 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000505 static std::pair<unsigned, unsigned>
506 ReadKeyDataLength(const unsigned char*& d) {
507 using namespace clang::io;
508 unsigned KeyLen = ReadUnalignedLE16(d);
509 unsigned DataLen = ReadUnalignedLE16(d);
510 return std::make_pair(KeyLen, DataLen);
511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregor83941df2009-04-25 17:48:32 +0000513 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000514 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000515 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000516 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000517 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000518 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
519 if (N == 0)
520 return SelTable.getNullarySelector(FirstII);
521 else if (N == 1)
522 return SelTable.getUnarySelector(FirstII);
523
524 llvm::SmallVector<IdentifierInfo *, 16> Args;
525 Args.push_back(FirstII);
526 for (unsigned I = 1; I != N; ++I)
527 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
528
Douglas Gregor75fdb232009-05-22 22:45:36 +0000529 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000530 }
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000532 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
533 using namespace clang::io;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000534
535 data_type Result;
536
Sebastian Redl5d050072010-08-04 17:20:04 +0000537 Result.ID = ReadUnalignedLE32(d);
538 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
539 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
540
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000541 // Load instance methods
542 ObjCMethodList *Prev = 0;
543 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000544 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000545 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Sebastian Redl5d050072010-08-04 17:20:04 +0000546 if (!Result.Instance.Method) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000547 // This is the first method, which is the easy case.
Sebastian Redl5d050072010-08-04 17:20:04 +0000548 Result.Instance.Method = Method;
549 Prev = &Result.Instance;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000550 continue;
551 }
552
Ted Kremenek298ed872010-02-11 00:53:01 +0000553 ObjCMethodList *Mem =
554 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
555 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000556 Prev = Prev->Next;
557 }
558
559 // Load factory methods
560 Prev = 0;
561 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000562 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000563 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Sebastian Redl5d050072010-08-04 17:20:04 +0000564 if (!Result.Factory.Method) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000565 // This is the first method, which is the easy case.
Sebastian Redl5d050072010-08-04 17:20:04 +0000566 Result.Factory.Method = Method;
567 Prev = &Result.Factory;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000568 continue;
569 }
570
Ted Kremenek298ed872010-02-11 00:53:01 +0000571 ObjCMethodList *Mem =
572 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
573 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000574 Prev = Prev->Next;
575 }
576
577 return Result;
578 }
579};
Mike Stump1eb44332009-09-09 15:08:12 +0000580
581} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000582
583/// \brief The on-disk hash table used for the global method pool.
Sebastian Redl725cd962010-08-04 20:40:17 +0000584typedef OnDiskChainedHashTable<PCHSelectorLookupTrait>
585 PCHSelectorLookupTable;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000586
587namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000588class PCHIdentifierLookupTrait {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000589 PCHReader &Reader;
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000590 llvm::BitstreamCursor &Stream;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000591
592 // If we know the IdentifierInfo in advance, it is here and we will
593 // not build a new one. Used when deserializing information about an
594 // identifier that was constructed before the PCH file was read.
595 IdentifierInfo *KnownII;
596
597public:
598 typedef IdentifierInfo * data_type;
599
600 typedef const std::pair<const char*, unsigned> external_key_type;
601
602 typedef external_key_type internal_key_type;
603
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000604 PCHIdentifierLookupTrait(PCHReader &Reader, llvm::BitstreamCursor &Stream,
605 IdentifierInfo *II = 0)
606 : Reader(Reader), Stream(Stream), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Douglas Gregor668c1a42009-04-21 22:25:48 +0000608 static bool EqualKey(const internal_key_type& a,
609 const internal_key_type& b) {
610 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
611 : false;
612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Douglas Gregor668c1a42009-04-21 22:25:48 +0000614 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000615 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000616 }
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Douglas Gregor668c1a42009-04-21 22:25:48 +0000618 // This hopefully will just get inlined and removed by the optimizer.
619 static const internal_key_type&
620 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Douglas Gregor668c1a42009-04-21 22:25:48 +0000622 static std::pair<unsigned, unsigned>
623 ReadKeyDataLength(const unsigned char*& d) {
624 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000625 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000626 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000627 return std::make_pair(KeyLen, DataLen);
628 }
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Douglas Gregor668c1a42009-04-21 22:25:48 +0000630 static std::pair<const char*, unsigned>
631 ReadKey(const unsigned char* d, unsigned n) {
632 assert(n >= 2 && d[n-1] == '\0');
633 return std::make_pair((const char*) d, n-1);
634 }
Mike Stump1eb44332009-09-09 15:08:12 +0000635
636 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000637 const unsigned char* d,
638 unsigned DataLen) {
639 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000640 pch::IdentID ID = ReadUnalignedLE32(d);
641 bool IsInteresting = ID & 0x01;
642
643 // Wipe out the "is interesting" bit.
644 ID = ID >> 1;
645
646 if (!IsInteresting) {
Sebastian Redl083abdf2010-07-27 23:01:28 +0000647 // For uninteresting identifiers, just build the IdentifierInfo
Douglas Gregora92193e2009-04-28 21:18:29 +0000648 // and associate it with the persistent ID.
649 IdentifierInfo *II = KnownII;
650 if (!II)
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000651 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregora92193e2009-04-28 21:18:29 +0000652 Reader.SetIdentifierInfo(ID, II);
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000653 II->setIsFromPCH();
Douglas Gregora92193e2009-04-28 21:18:29 +0000654 return II;
655 }
656
Douglas Gregor5998da52009-04-28 21:32:13 +0000657 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000658 bool CPlusPlusOperatorKeyword = Bits & 0x01;
659 Bits >>= 1;
660 bool Poisoned = Bits & 0x01;
661 Bits >>= 1;
662 bool ExtensionToken = Bits & 0x01;
663 Bits >>= 1;
664 bool hasMacroDefinition = Bits & 0x01;
665 Bits >>= 1;
666 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
667 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Douglas Gregor2deaea32009-04-22 18:49:13 +0000669 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000670 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000671
672 // Build the IdentifierInfo itself and link the identifier ID with
673 // the new IdentifierInfo.
674 IdentifierInfo *II = KnownII;
675 if (!II)
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000676 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000677 Reader.SetIdentifierInfo(ID, II);
678
Douglas Gregor2deaea32009-04-22 18:49:13 +0000679 // Set or check the various bits in the IdentifierInfo structure.
680 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000681 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000682 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000683 "Incorrect extension token flag");
684 (void)ExtensionToken;
685 II->setIsPoisoned(Poisoned);
686 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
687 "Incorrect C++ operator keyword flag");
688 (void)CPlusPlusOperatorKeyword;
689
Douglas Gregor37e26842009-04-21 23:56:24 +0000690 // If this identifier is a macro, deserialize the macro
691 // definition.
692 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000693 uint32_t Offset = ReadUnalignedLE32(d);
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000694 Reader.ReadMacroRecord(Stream, Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000695 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000696 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000697
698 // Read all of the declarations visible at global scope with this
699 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000700 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000701 if (DataLen > 0) {
702 llvm::SmallVector<uint32_t, 4> DeclIDs;
703 for (; DataLen > 0; DataLen -= 4)
704 DeclIDs.push_back(ReadUnalignedLE32(d));
705 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000706 }
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000708 II->setIsFromPCH();
Douglas Gregor668c1a42009-04-21 22:25:48 +0000709 return II;
710 }
711};
Mike Stump1eb44332009-09-09 15:08:12 +0000712
713} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000714
715/// \brief The on-disk hash table used to contain information about
716/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000717typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000718 PCHIdentifierLookupTable;
719
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000720void PCHReader::Error(const char *Msg) {
721 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000722}
723
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000724/// \brief Check the contents of the concatenation of all predefines buffers in
725/// the PCH chain against the contents of the predefines buffer of the current
726/// compiler invocation.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000727///
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000728/// The contents should be the same. If not, then some command-line option
729/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000730///
731/// \returns true if there was a mismatch (in which case the PCH file
732/// should be ignored), or false otherwise.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000733bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000734 if (Listener)
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000735 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000736 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000737 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000738 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000739}
740
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000741//===----------------------------------------------------------------------===//
742// Source Manager Deserialization
743//===----------------------------------------------------------------------===//
744
Douglas Gregorbd945002009-04-13 16:31:14 +0000745/// \brief Read the line table in the source manager block.
746/// \returns true if ther was an error.
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000747bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000748 unsigned Idx = 0;
749 LineTableInfo &LineTable = SourceMgr.getLineTable();
750
751 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000752 std::map<int, int> FileIDs;
753 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000754 // Extract the file name
755 unsigned FilenameLen = Record[Idx++];
756 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
757 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000758 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000759 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000760 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000761 }
762
763 // Parse the line entries
764 std::vector<LineEntry> Entries;
765 while (Idx < Record.size()) {
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000766 int FID = Record[Idx++];
Douglas Gregorbd945002009-04-13 16:31:14 +0000767
768 // Extract the line entries
769 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000770 assert(NumEntries && "Numentries is 00000");
Douglas Gregorbd945002009-04-13 16:31:14 +0000771 Entries.clear();
772 Entries.reserve(NumEntries);
773 for (unsigned I = 0; I != NumEntries; ++I) {
774 unsigned FileOffset = Record[Idx++];
775 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000776 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump1eb44332009-09-09 15:08:12 +0000777 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000778 = (SrcMgr::CharacteristicKind)Record[Idx++];
779 unsigned IncludeOffset = Record[Idx++];
780 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
781 FileKind, IncludeOffset));
782 }
783 LineTable.AddEntry(FID, Entries);
784 }
785
786 return false;
787}
788
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000789namespace {
790
Benjamin Kramerbd218282009-11-28 10:07:24 +0000791class PCHStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000792public:
793 const bool hasStat;
794 const ino_t ino;
795 const dev_t dev;
796 const mode_t mode;
797 const time_t mtime;
798 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000800 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000801 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
802
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000803 PCHStatData()
804 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
805};
806
Benjamin Kramerbd218282009-11-28 10:07:24 +0000807class PCHStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000808 public:
809 typedef const char *external_key_type;
810 typedef const char *internal_key_type;
811
812 typedef PCHStatData data_type;
813
814 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000815 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000816 }
817
818 static internal_key_type GetInternalKey(const char *path) { return path; }
819
820 static bool EqualKey(internal_key_type a, internal_key_type b) {
821 return strcmp(a, b) == 0;
822 }
823
824 static std::pair<unsigned, unsigned>
825 ReadKeyDataLength(const unsigned char*& d) {
826 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
827 unsigned DataLen = (unsigned) *d++;
828 return std::make_pair(KeyLen + 1, DataLen);
829 }
830
831 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
832 return (const char *)d;
833 }
834
835 static data_type ReadData(const internal_key_type, const unsigned char *d,
836 unsigned /*DataLen*/) {
837 using namespace clang::io;
838
839 if (*d++ == 1)
840 return data_type();
841
842 ino_t ino = (ino_t) ReadUnalignedLE32(d);
843 dev_t dev = (dev_t) ReadUnalignedLE32(d);
844 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000845 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000846 off_t size = (off_t) ReadUnalignedLE64(d);
847 return data_type(ino, dev, mode, mtime, size);
848 }
849};
850
851/// \brief stat() cache for precompiled headers.
852///
853/// This cache is very similar to the stat cache used by pretokenized
854/// headers.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000855class PCHStatCache : public StatSysCallCache {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000856 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
857 CacheTy *Cache;
858
859 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000860public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000861 PCHStatCache(const unsigned char *Buckets,
862 const unsigned char *Base,
863 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000864 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000865 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
866 Cache = CacheTy::Create(Buckets, Base);
867 }
868
869 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000871 int stat(const char *path, struct stat *buf) {
872 // Do the lookup for the file's data in the PCH file.
873 CacheTy::iterator I = Cache->find(path);
874
875 // If we don't get a hit in the PCH file just forward to 'stat'.
876 if (I == Cache->end()) {
877 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000878 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000879 }
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000881 ++NumStatHits;
882 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000884 if (!Data.hasStat)
885 return 1;
886
887 buf->st_ino = Data.ino;
888 buf->st_dev = Data.dev;
889 buf->st_mtime = Data.mtime;
890 buf->st_mode = Data.mode;
891 buf->st_size = Data.size;
892 return 0;
893 }
894};
895} // end anonymous namespace
896
897
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000898/// \brief Read a source manager block
899PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000900 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000901
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000902 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +0000903
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000904 // Set the source-location entry cursor to the current position in
905 // the stream. This cursor will be used to read the contents of the
906 // source manager block initially, and then lazily read
907 // source-location entries as needed.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000908 SLocEntryCursor = F.Stream;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000909
910 // The stream itself is going to skip over the source manager block.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000911 if (F.Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000912 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000913 return Failure;
914 }
915
916 // Enter the source manager block.
917 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000918 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000919 return Failure;
920 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000921
Douglas Gregor14f79002009-04-10 03:52:48 +0000922 RecordData Record;
923 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000924 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000925 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000926 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000927 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000928 return Failure;
929 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000930 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000931 }
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Douglas Gregor14f79002009-04-10 03:52:48 +0000933 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
934 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000935 SLocEntryCursor.ReadSubBlockID();
936 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000937 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000938 return Failure;
939 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000940 continue;
941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Douglas Gregor14f79002009-04-10 03:52:48 +0000943 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000944 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000945 continue;
946 }
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Douglas Gregor14f79002009-04-10 03:52:48 +0000948 // Read a record.
949 const char *BlobStart;
950 unsigned BlobLen;
951 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000952 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000953 default: // Default behavior: ignore.
954 break;
955
Chris Lattner2c78b872009-04-14 23:22:57 +0000956 case pch::SM_LINE_TABLE:
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000957 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000958 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000959 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000960
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000961 case pch::SM_SLOC_FILE_ENTRY:
962 case pch::SM_SLOC_BUFFER_ENTRY:
963 case pch::SM_SLOC_INSTANTIATION_ENTRY:
964 // Once we hit one of the source location entries, we're done.
965 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000966 }
967 }
968}
969
Sebastian Redl190faf72010-07-20 21:50:20 +0000970/// \brief Get a cursor that's correctly positioned for reading the source
971/// location entry with the given ID.
972llvm::BitstreamCursor &PCHReader::SLocCursorForID(unsigned ID) {
973 assert(ID != 0 && ID <= TotalNumSLocEntries &&
974 "SLocCursorForID should only be called for real IDs.");
975
976 ID -= 1;
977 PerFileData *F = 0;
978 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
979 F = Chain[N - I - 1];
980 if (ID < F->LocalNumSLocEntries)
981 break;
982 ID -= F->LocalNumSLocEntries;
983 }
984 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
985
986 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
987 return F->SLocEntryCursor;
988}
989
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000990/// \brief Read in the source location entry with the given ID.
991PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
992 if (ID == 0)
993 return Success;
994
995 if (ID > TotalNumSLocEntries) {
996 Error("source location entry ID out-of-range for PCH file");
997 return Failure;
998 }
999
Sebastian Redl190faf72010-07-20 21:50:20 +00001000 llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
Sebastian Redl9137a522010-07-16 17:50:48 +00001001
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001002 ++NumSLocEntriesRead;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001003 unsigned Code = SLocEntryCursor.ReadCode();
1004 if (Code == llvm::bitc::END_BLOCK ||
1005 Code == llvm::bitc::ENTER_SUBBLOCK ||
1006 Code == llvm::bitc::DEFINE_ABBREV) {
1007 Error("incorrectly-formatted source location entry in PCH file");
1008 return Failure;
1009 }
1010
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001011 RecordData Record;
1012 const char *BlobStart;
1013 unsigned BlobLen;
1014 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1015 default:
1016 Error("incorrectly-formatted source location entry in PCH file");
1017 return Failure;
1018
1019 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001020 std::string Filename(BlobStart, BlobStart + BlobLen);
1021 MaybeAddSystemRootToFilename(Filename);
1022 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001023 if (File == 0) {
1024 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +00001025 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001026 ErrorStr += "' referenced by PCH file";
1027 Error(ErrorStr.c_str());
1028 return Failure;
1029 }
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Douglas Gregor2d52be52010-03-21 22:49:54 +00001031 if (Record.size() < 10) {
Ted Kremenek1857f622010-03-18 21:23:05 +00001032 Error("source location entry is incorrect");
1033 return Failure;
1034 }
1035
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001036 if (!DisableValidation &&
1037 ((off_t)Record[4] != File->getSize()
Douglas Gregor9f692a02010-04-09 15:54:22 +00001038#if !defined(LLVM_ON_WIN32)
1039 // In our regression testing, the Windows file system seems to
1040 // have inconsistent modification times that sometimes
1041 // erroneously trigger this error-handling path.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001042 || (time_t)Record[5] != File->getModificationTime()
Douglas Gregor9f692a02010-04-09 15:54:22 +00001043#endif
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001044 )) {
Douglas Gregor2d52be52010-03-21 22:49:54 +00001045 Diag(diag::err_fe_pch_file_modified)
1046 << Filename;
1047 return Failure;
1048 }
1049
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001050 FileID FID = SourceMgr.createFileID(File,
1051 SourceLocation::getFromRawEncoding(Record[1]),
1052 (SrcMgr::CharacteristicKind)Record[2],
1053 ID, Record[0]);
1054 if (Record[3])
1055 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1056 .setHasLineDirectives();
1057
Douglas Gregor12fab312010-03-16 16:35:32 +00001058 // Reconstruct header-search information for this file.
1059 HeaderFileInfo HFI;
Douglas Gregor2d52be52010-03-21 22:49:54 +00001060 HFI.isImport = Record[6];
1061 HFI.DirInfo = Record[7];
1062 HFI.NumIncludes = Record[8];
1063 HFI.ControllingMacroID = Record[9];
Douglas Gregor12fab312010-03-16 16:35:32 +00001064 if (Listener)
1065 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001066 break;
1067 }
1068
1069 case pch::SM_SLOC_BUFFER_ENTRY: {
1070 const char *Name = BlobStart;
1071 unsigned Offset = Record[0];
1072 unsigned Code = SLocEntryCursor.ReadCode();
1073 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001074 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001075 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001076
1077 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1078 Error("PCH record has invalid code");
1079 return Failure;
1080 }
1081
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001082 llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001083 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1084 Name);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001085 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Douglas Gregor92b059e2009-04-28 20:33:11 +00001087 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001088 PCHPredefinesBlock Block = {
1089 BufferID,
1090 llvm::StringRef(BlobStart, BlobLen - 1)
1091 };
1092 PCHPredefinesBuffers.push_back(Block);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001093 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001094
1095 break;
1096 }
1097
1098 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +00001099 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001100 = SourceLocation::getFromRawEncoding(Record[1]);
1101 SourceMgr.createInstantiationLoc(SpellingLoc,
1102 SourceLocation::getFromRawEncoding(Record[2]),
1103 SourceLocation::getFromRawEncoding(Record[3]),
1104 Record[4],
1105 ID,
1106 Record[0]);
1107 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001108 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001109 }
1110
1111 return Success;
1112}
1113
Chris Lattner6367f6d2009-04-27 01:05:14 +00001114/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1115/// specified cursor. Read the abbreviations that are at the top of the block
1116/// and then leave the cursor pointing into the block.
1117bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1118 unsigned BlockID) {
1119 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001120 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001121 return Failure;
1122 }
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattner6367f6d2009-04-27 01:05:14 +00001124 while (true) {
1125 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Chris Lattner6367f6d2009-04-27 01:05:14 +00001127 // We expect all abbrevs to be at the start of the block.
1128 if (Code != llvm::bitc::DEFINE_ABBREV)
1129 return false;
1130 Cursor.ReadAbbrevRecord();
1131 }
1132}
1133
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001134void PCHReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001135 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Douglas Gregor37e26842009-04-21 23:56:24 +00001137 // Keep track of where we are in the stream, then jump back there
1138 // after reading this macro.
1139 SavedStreamPosition SavedPosition(Stream);
1140
1141 Stream.JumpToBit(Offset);
1142 RecordData Record;
1143 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1144 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Douglas Gregor37e26842009-04-21 23:56:24 +00001146 while (true) {
1147 unsigned Code = Stream.ReadCode();
1148 switch (Code) {
1149 case llvm::bitc::END_BLOCK:
1150 return;
1151
1152 case llvm::bitc::ENTER_SUBBLOCK:
1153 // No known subblocks, always skip them.
1154 Stream.ReadSubBlockID();
1155 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001156 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001157 return;
1158 }
1159 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Douglas Gregor37e26842009-04-21 23:56:24 +00001161 case llvm::bitc::DEFINE_ABBREV:
1162 Stream.ReadAbbrevRecord();
1163 continue;
1164 default: break;
1165 }
1166
1167 // Read a record.
1168 Record.clear();
1169 pch::PreprocessorRecordTypes RecType =
1170 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1171 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001172 case pch::PP_MACRO_OBJECT_LIKE:
1173 case pch::PP_MACRO_FUNCTION_LIKE: {
1174 // If we already have a macro, that means that we've hit the end
1175 // of the definition of the macro we were looking for. We're
1176 // done.
1177 if (Macro)
1178 return;
1179
1180 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1181 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001182 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001183 return;
1184 }
1185 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1186 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001188 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001189 MI->setIsUsed(isUsed);
Sebastian Redl083abdf2010-07-27 23:01:28 +00001190 MI->setIsFromPCH();
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001192 unsigned NextIndex = 3;
Douglas Gregor37e26842009-04-21 23:56:24 +00001193 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1194 // Decode function-like macro info.
1195 bool isC99VarArgs = Record[3];
1196 bool isGNUVarArgs = Record[4];
1197 MacroArgs.clear();
1198 unsigned NumArgs = Record[5];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001199 NextIndex = 6 + NumArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001200 for (unsigned i = 0; i != NumArgs; ++i)
1201 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1202
1203 // Install function-like macro info.
1204 MI->setIsFunctionLike();
1205 if (isC99VarArgs) MI->setIsC99Varargs();
1206 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001207 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001208 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001209 }
1210
1211 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001212 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001213
1214 // Remember that we saw this macro last so that we add the tokens that
1215 // form its body to it.
1216 Macro = MI;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001217
1218 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1219 // We have a macro definition. Load it now.
1220 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1221 getMacroDefinition(Record[NextIndex]));
1222 }
1223
Douglas Gregor37e26842009-04-21 23:56:24 +00001224 ++NumMacrosRead;
1225 break;
1226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Douglas Gregor37e26842009-04-21 23:56:24 +00001228 case pch::PP_TOKEN: {
1229 // If we see a TOKEN before a PP_MACRO_*, then the file is
1230 // erroneous, just pretend we didn't see this.
1231 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Douglas Gregor37e26842009-04-21 23:56:24 +00001233 Token Tok;
1234 Tok.startToken();
1235 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1236 Tok.setLength(Record[1]);
1237 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1238 Tok.setIdentifierInfo(II);
1239 Tok.setKind((tok::TokenKind)Record[3]);
1240 Tok.setFlag((Token::TokenFlags)Record[4]);
1241 Macro->AddTokenToBody(Tok);
1242 break;
1243 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001244
1245 case pch::PP_MACRO_INSTANTIATION: {
1246 // If we already have a macro, that means that we've hit the end
1247 // of the definition of the macro we were looking for. We're
1248 // done.
1249 if (Macro)
1250 return;
1251
1252 if (!PP->getPreprocessingRecord()) {
1253 Error("missing preprocessing record in PCH file");
1254 return;
1255 }
1256
1257 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1258 if (PPRec.getPreprocessedEntity(Record[0]))
1259 return;
1260
1261 MacroInstantiation *MI
1262 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1263 SourceRange(
1264 SourceLocation::getFromRawEncoding(Record[1]),
1265 SourceLocation::getFromRawEncoding(Record[2])),
1266 getMacroDefinition(Record[4]));
1267 PPRec.SetPreallocatedEntity(Record[0], MI);
1268 return;
1269 }
1270
1271 case pch::PP_MACRO_DEFINITION: {
1272 // If we already have a macro, that means that we've hit the end
1273 // of the definition of the macro we were looking for. We're
1274 // done.
1275 if (Macro)
1276 return;
1277
1278 if (!PP->getPreprocessingRecord()) {
1279 Error("missing preprocessing record in PCH file");
1280 return;
1281 }
1282
1283 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1284 if (PPRec.getPreprocessedEntity(Record[0]))
1285 return;
1286
1287 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1288 Error("out-of-bounds macro definition record");
1289 return;
1290 }
1291
1292 MacroDefinition *MD
1293 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1294 SourceLocation::getFromRawEncoding(Record[5]),
1295 SourceRange(
1296 SourceLocation::getFromRawEncoding(Record[2]),
1297 SourceLocation::getFromRawEncoding(Record[3])));
1298 PPRec.SetPreallocatedEntity(Record[0], MD);
1299 MacroDefinitionsLoaded[Record[1]] = MD;
1300 return;
1301 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001302 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001303 }
1304}
1305
Douglas Gregor88a35862010-01-04 19:18:44 +00001306void PCHReader::ReadDefinedMacros() {
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001307 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1308 llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00001309
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001310 // If there was no preprocessor block, skip this file.
1311 if (!MacroCursor.getBitStreamReader())
1312 continue;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001313
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001314 llvm::BitstreamCursor Cursor = MacroCursor;
1315 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1316 Error("malformed preprocessor block record in PCH file");
Douglas Gregor88a35862010-01-04 19:18:44 +00001317 return;
1318 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001319
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001320 RecordData Record;
1321 while (true) {
1322 unsigned Code = Cursor.ReadCode();
1323 if (Code == llvm::bitc::END_BLOCK) {
1324 if (Cursor.ReadBlockEnd()) {
1325 Error("error at end of preprocessor block in PCH file");
1326 return;
1327 }
1328 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001329 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001330
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001331 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1332 // No known subblocks, always skip them.
1333 Cursor.ReadSubBlockID();
1334 if (Cursor.SkipBlock()) {
1335 Error("malformed block record in PCH file");
1336 return;
1337 }
1338 continue;
1339 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001340
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001341 if (Code == llvm::bitc::DEFINE_ABBREV) {
1342 Cursor.ReadAbbrevRecord();
1343 continue;
1344 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001345
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001346 // Read a record.
1347 const char *BlobStart;
1348 unsigned BlobLen;
1349 Record.clear();
1350 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1351 default: // Default behavior: ignore.
1352 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001353
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001354 case pch::PP_MACRO_OBJECT_LIKE:
1355 case pch::PP_MACRO_FUNCTION_LIKE:
1356 DecodeIdentifierInfo(Record[0]);
1357 break;
1358
1359 case pch::PP_TOKEN:
1360 // Ignore tokens.
1361 break;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001362
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001363 case pch::PP_MACRO_INSTANTIATION:
1364 case pch::PP_MACRO_DEFINITION:
1365 // Read the macro record.
1366 ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1367 break;
1368 }
Douglas Gregor88a35862010-01-04 19:18:44 +00001369 }
1370 }
1371}
1372
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001373MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1374 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1375 return 0;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001376
1377 if (!MacroDefinitionsLoaded[ID]) {
1378 unsigned Index = ID;
1379 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1380 PerFileData &F = *Chain[N - I - 1];
1381 if (Index < F.LocalNumMacroDefinitions) {
1382 ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1383 break;
1384 }
1385 Index -= F.LocalNumMacroDefinitions;
1386 }
1387 assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1388 }
1389
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001390 return MacroDefinitionsLoaded[ID];
1391}
1392
Douglas Gregore650c8c2009-07-07 00:12:59 +00001393/// \brief If we are loading a relocatable PCH file, and the filename is
1394/// not an absolute path, add the system root to the beginning of the file
1395/// name.
1396void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1397 // If this is not a relocatable PCH file, there's nothing to do.
1398 if (!RelocatablePCH)
1399 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Daniel Dunbard5b21972009-11-18 19:50:41 +00001401 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001402 return;
1403
Douglas Gregore650c8c2009-07-07 00:12:59 +00001404 if (isysroot == 0) {
1405 // If no system root was given, default to '/'
1406 Filename.insert(Filename.begin(), '/');
1407 return;
1408 }
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Douglas Gregore650c8c2009-07-07 00:12:59 +00001410 unsigned Length = strlen(isysroot);
1411 if (isysroot[Length - 1] != '/')
1412 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Douglas Gregore650c8c2009-07-07 00:12:59 +00001414 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1415}
1416
Mike Stump1eb44332009-09-09 15:08:12 +00001417PCHReader::PCHReadResult
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001418PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl9137a522010-07-16 17:50:48 +00001419 llvm::BitstreamCursor &Stream = F.Stream;
1420
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001421 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001422 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001423 return Failure;
1424 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001425
1426 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001427 RecordData Record;
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001428 bool First = true;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001429 while (!Stream.AtEndOfStream()) {
1430 unsigned Code = Stream.ReadCode();
1431 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001432 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001433 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001434 return Failure;
1435 }
Chris Lattner7356a312009-04-11 21:15:38 +00001436
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001437 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001438 }
1439
1440 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1441 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001442 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001443 // We lazily load the decls block, but we want to set up the
1444 // DeclsCursor cursor to point into it. Clone our current bitcode
1445 // cursor to it, enter the block and read the abbrevs in that block.
1446 // With the main cursor, we just skip over it.
Sebastian Redl9137a522010-07-16 17:50:48 +00001447 F.DeclsCursor = Stream;
Chris Lattner6367f6d2009-04-27 01:05:14 +00001448 if (Stream.SkipBlock() || // Skip with the main cursor.
1449 // Read the abbrevs.
Sebastian Redl9137a522010-07-16 17:50:48 +00001450 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001451 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001452 return Failure;
1453 }
1454 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Chris Lattner7356a312009-04-11 21:15:38 +00001456 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl9137a522010-07-16 17:50:48 +00001457 F.MacroCursor = Stream;
Douglas Gregor88a35862010-01-04 19:18:44 +00001458 if (PP)
1459 PP->setExternalSource(this);
1460
Chris Lattner7356a312009-04-11 21:15:38 +00001461 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001462 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001463 return Failure;
1464 }
1465 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001466
Douglas Gregor14f79002009-04-10 03:52:48 +00001467 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001468 switch (ReadSourceManagerBlock(F)) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001469 case Success:
1470 break;
1471
1472 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001473 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001474 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001475
1476 case IgnorePCH:
1477 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001478 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001479 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001480 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001481 First = false;
Douglas Gregor8038d512009-04-10 17:25:41 +00001482 continue;
1483 }
1484
1485 if (Code == llvm::bitc::DEFINE_ABBREV) {
1486 Stream.ReadAbbrevRecord();
1487 continue;
1488 }
1489
1490 // Read and process a record.
1491 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001492 const char *BlobStart = 0;
1493 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001494 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001495 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001496 default: // Default behavior: ignore.
1497 break;
1498
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001499 case pch::METADATA: {
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001500 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001501 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1502 : diag::warn_pch_version_too_new);
1503 return IgnorePCH;
1504 }
1505
1506 RelocatablePCH = Record[4];
1507 if (Listener) {
1508 std::string TargetTriple(BlobStart, BlobLen);
1509 if (Listener->ReadTargetTriple(TargetTriple))
1510 return IgnorePCH;
1511 }
1512 break;
1513 }
1514
1515 case pch::CHAINED_METADATA: {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001516 if (!First) {
1517 Error("CHAINED_METADATA is not first record in block");
1518 return Failure;
1519 }
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001520 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001521 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1522 : diag::warn_pch_version_too_new);
1523 return IgnorePCH;
1524 }
1525
1526 // Load the chained file.
1527 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1528 case Failure: return Failure;
1529 // If we have to ignore the dependency, we'll have to ignore this too.
1530 case IgnorePCH: return IgnorePCH;
1531 case Success: break;
1532 }
1533 break;
1534 }
1535
Douglas Gregor8038d512009-04-10 17:25:41 +00001536 case pch::TYPE_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001537 if (F.LocalNumTypes != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001538 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001539 return Failure;
1540 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001541 F.TypeOffsets = (const uint32_t *)BlobStart;
1542 F.LocalNumTypes = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001543 break;
1544
1545 case pch::DECL_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001546 if (F.LocalNumDecls != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001547 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001548 return Failure;
1549 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001550 F.DeclOffsets = (const uint32_t *)BlobStart;
1551 F.LocalNumDecls = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001552 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001553
Sebastian Redld692af72010-07-27 18:24:41 +00001554 case pch::TU_UPDATE_LEXICAL: {
1555 DeclContextInfo Info = {
1556 /* No visible information */ 0, 0,
1557 reinterpret_cast<const pch::DeclID *>(BlobStart),
1558 BlobLen / sizeof(pch::DeclID)
1559 };
1560 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1561 break;
1562 }
1563
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00001564 case pch::REDECLS_UPDATE_LATEST: {
1565 assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
1566 for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
1567 pch::DeclID First = Record[i], Latest = Record[i+1];
1568 assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
1569 Latest > FirstLatestDeclIDs[First]) &&
1570 "The new latest is supposed to come after the previous latest");
1571 FirstLatestDeclIDs[First] = Latest;
1572 }
1573 break;
1574 }
1575
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001576 case pch::LANGUAGE_OPTIONS:
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001577 if (ParseLanguageOptions(Record) && !DisableValidation)
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001578 return IgnorePCH;
1579 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001580
Douglas Gregorafaf3082009-04-11 00:14:32 +00001581 case pch::IDENTIFIER_TABLE:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001582 F.IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001583 if (Record[0]) {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001584 F.IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001585 = PCHIdentifierLookupTable::Create(
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001586 (const unsigned char *)F.IdentifierTableData + Record[0],
1587 (const unsigned char *)F.IdentifierTableData,
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001588 PCHIdentifierLookupTrait(*this, F.Stream));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001589 if (PP)
1590 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001591 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001592 break;
1593
1594 case pch::IDENTIFIER_OFFSET:
Sebastian Redl2da08f92010-07-19 22:28:42 +00001595 if (F.LocalNumIdentifiers != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001596 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001597 return Failure;
1598 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001599 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1600 F.LocalNumIdentifiers = Record[0];
Douglas Gregorafaf3082009-04-11 00:14:32 +00001601 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001602
1603 case pch::EXTERNAL_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001604 // Optimization for the first block.
1605 if (ExternalDefinitions.empty())
1606 ExternalDefinitions.swap(Record);
1607 else
1608 ExternalDefinitions.insert(ExternalDefinitions.end(),
1609 Record.begin(), Record.end());
Douglas Gregorfdd01722009-04-14 00:24:19 +00001610 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001611
Douglas Gregorad1de002009-04-18 05:55:16 +00001612 case pch::SPECIAL_TYPES:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001613 // Optimization for the first block
1614 if (SpecialTypes.empty())
1615 SpecialTypes.swap(Record);
1616 else
1617 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
Douglas Gregorad1de002009-04-18 05:55:16 +00001618 break;
1619
Douglas Gregor3e1af842009-04-17 22:13:46 +00001620 case pch::STATISTICS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001621 TotalNumStatements += Record[0];
1622 TotalNumMacros += Record[1];
1623 TotalLexicalDeclContexts += Record[2];
1624 TotalVisibleDeclContexts += Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001625 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001626
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001627 case pch::TENTATIVE_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001628 // Optimization for the first block.
1629 if (TentativeDefinitions.empty())
1630 TentativeDefinitions.swap(Record);
1631 else
1632 TentativeDefinitions.insert(TentativeDefinitions.end(),
1633 Record.begin(), Record.end());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001634 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001635
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001636 case pch::UNUSED_STATIC_FUNCS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001637 // Optimization for the first block.
1638 if (UnusedStaticFuncs.empty())
1639 UnusedStaticFuncs.swap(Record);
1640 else
1641 UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
1642 Record.begin(), Record.end());
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001643 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001644
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00001645 case pch::WEAK_UNDECLARED_IDENTIFIERS:
Sebastian Redl40566802010-08-05 18:21:25 +00001646 // Later blocks overwrite earlier ones.
1647 WeakUndeclaredIdentifiers.swap(Record);
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00001648 break;
1649
Douglas Gregor14c22f22009-04-22 22:18:58 +00001650 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001651 // Optimization for the first block.
1652 if (LocallyScopedExternalDecls.empty())
1653 LocallyScopedExternalDecls.swap(Record);
1654 else
1655 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1656 Record.begin(), Record.end());
Douglas Gregor14c22f22009-04-22 22:18:58 +00001657 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001658
Douglas Gregor83941df2009-04-25 17:48:32 +00001659 case pch::SELECTOR_OFFSETS:
Sebastian Redl059612d2010-08-03 21:58:15 +00001660 F.SelectorOffsets = (const uint32_t *)BlobStart;
Sebastian Redl725cd962010-08-04 20:40:17 +00001661 F.LocalNumSelectors = Record[0];
Douglas Gregor83941df2009-04-25 17:48:32 +00001662 break;
1663
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001664 case pch::METHOD_POOL:
Sebastian Redl725cd962010-08-04 20:40:17 +00001665 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
Douglas Gregor83941df2009-04-25 17:48:32 +00001666 if (Record[0])
Sebastian Redl725cd962010-08-04 20:40:17 +00001667 F.SelectorLookupTable
1668 = PCHSelectorLookupTable::Create(
1669 F.SelectorLookupTableData + Record[0],
1670 F.SelectorLookupTableData,
1671 PCHSelectorLookupTrait(*this));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00001672 TotalNumMethodPoolEntries += Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001673 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001674
Fariborz Jahanian32019832010-07-23 19:11:11 +00001675 case pch::REFERENCED_SELECTOR_POOL: {
Sebastian Redl725cd962010-08-04 20:40:17 +00001676 ReferencedSelectorsData.insert(ReferencedSelectorsData.end(),
1677 Record.begin(), Record.end());
Fariborz Jahanian32019832010-07-23 19:11:11 +00001678 break;
Sebastian Redl681d7232010-07-27 00:17:23 +00001679 }
Fariborz Jahanian32019832010-07-23 19:11:11 +00001680
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001681 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001682 if (!Record.empty() && Listener)
1683 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001684 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001685
1686 case pch::SOURCE_LOCATION_OFFSETS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001687 F.SLocOffsets = (const uint32_t *)BlobStart;
1688 F.LocalNumSLocEntries = Record[0];
1689 // We cannot delay this until all PCHs are loaded, because then source
1690 // location preloads would also have to be delayed.
1691 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001692 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001693 break;
1694
1695 case pch::SOURCE_LOCATION_PRELOADS:
1696 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1697 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1698 if (Result != Success)
1699 return Result;
1700 }
1701 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001702
Douglas Gregor52e71082009-10-16 18:18:30 +00001703 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001704 PCHStatCache *MyStatCache =
Douglas Gregor52e71082009-10-16 18:18:30 +00001705 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1706 (const unsigned char *)BlobStart,
1707 NumStatHits, NumStatMisses);
1708 FileMgr.addStatCache(MyStatCache);
Sebastian Redl9137a522010-07-16 17:50:48 +00001709 F.StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001710 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001711 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001712
Douglas Gregorb81c1702009-04-27 20:06:05 +00001713 case pch::EXT_VECTOR_DECLS:
Sebastian Redla9f23682010-07-28 21:38:49 +00001714 // Optimization for the first block.
1715 if (ExtVectorDecls.empty())
1716 ExtVectorDecls.swap(Record);
1717 else
1718 ExtVectorDecls.insert(ExtVectorDecls.end(),
1719 Record.begin(), Record.end());
Douglas Gregorb81c1702009-04-27 20:06:05 +00001720 break;
1721
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001722 case pch::VTABLE_USES:
Sebastian Redl40566802010-08-05 18:21:25 +00001723 // Later tables overwrite earlier ones.
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001724 VTableUses.swap(Record);
1725 break;
1726
1727 case pch::DYNAMIC_CLASSES:
Sebastian Redl40566802010-08-05 18:21:25 +00001728 // Optimization for the first block.
1729 if (DynamicClasses.empty())
1730 DynamicClasses.swap(Record);
1731 else
1732 DynamicClasses.insert(DynamicClasses.end(),
1733 Record.begin(), Record.end());
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001734 break;
1735
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +00001736 case pch::PENDING_IMPLICIT_INSTANTIATIONS:
1737 // Optimization for the first block.
1738 if (PendingImplicitInstantiations.empty())
1739 PendingImplicitInstantiations.swap(Record);
1740 else
1741 PendingImplicitInstantiations.insert(
1742 PendingImplicitInstantiations.end(), Record.begin(), Record.end());
1743 break;
1744
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001745 case pch::SEMA_DECL_REFS:
Sebastian Redl40566802010-08-05 18:21:25 +00001746 // Later tables overwrite earlier ones.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001747 SemaDeclRefs.swap(Record);
1748 break;
1749
Douglas Gregorb64c1932009-05-12 01:31:05 +00001750 case pch::ORIGINAL_FILE_NAME:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001751 // The primary PCH will be the last to get here, so it will be the one
1752 // that's used.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001753 ActualOriginalFileName.assign(BlobStart, BlobLen);
1754 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001755 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001756 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Ted Kremenek5b4ec632010-01-22 20:59:36 +00001758 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek974be4d2010-02-12 23:31:14 +00001759 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek517e6762010-01-22 20:55:35 +00001760 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001761 if (llvm::StringRef(CurBranch) != PCHBranch && !DisableValidation) {
Douglas Gregor445e23e2009-10-05 21:07:28 +00001762 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1763 return IgnorePCH;
1764 }
1765 break;
1766 }
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001767
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001768 case pch::MACRO_DEFINITION_OFFSETS:
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001769 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1770 F.NumPreallocatedPreprocessingEntities = Record[0];
1771 F.LocalNumMacroDefinitions = Record[1];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001772 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001773 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001774 First = false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001775 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001776 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001777 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001778}
1779
Douglas Gregore1d918e2009-04-10 23:10:45 +00001780PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001781 switch(ReadPCHCore(FileName)) {
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001782 case Failure: return Failure;
1783 case IgnorePCH: return IgnorePCH;
1784 case Success: break;
1785 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001786
1787 // Here comes stuff that we only do once the entire chain is loaded.
1788
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001789 // Allocate space for loaded identifiers, decls and types.
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001790 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
Sebastian Redl725cd962010-08-04 20:40:17 +00001791 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0,
1792 TotalNumSelectors = 0;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001793 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Sebastian Redl2da08f92010-07-19 22:28:42 +00001794 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001795 TotalNumTypes += Chain[I]->LocalNumTypes;
1796 TotalNumDecls += Chain[I]->LocalNumDecls;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001797 TotalNumPreallocatedPreprocessingEntities +=
1798 Chain[I]->NumPreallocatedPreprocessingEntities;
1799 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
Sebastian Redl725cd962010-08-04 20:40:17 +00001800 TotalNumSelectors += Chain[I]->LocalNumSelectors;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001801 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001802 IdentifiersLoaded.resize(TotalNumIdentifiers);
Sebastian Redl12d6da02010-07-19 22:06:55 +00001803 TypesLoaded.resize(TotalNumTypes);
1804 DeclsLoaded.resize(TotalNumDecls);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001805 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
1806 if (PP) {
1807 if (TotalNumIdentifiers > 0)
1808 PP->getHeaderSearchInfo().SetExternalLookup(this);
1809 if (TotalNumPreallocatedPreprocessingEntities > 0) {
1810 if (!PP->getPreprocessingRecord())
1811 PP->createPreprocessingRecord();
1812 PP->getPreprocessingRecord()->SetExternalSource(*this,
1813 TotalNumPreallocatedPreprocessingEntities);
1814 }
1815 }
Sebastian Redl725cd962010-08-04 20:40:17 +00001816 SelectorsLoaded.resize(TotalNumSelectors);
Sebastian Redl12d6da02010-07-19 22:06:55 +00001817
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001818 // Check the predefines buffers.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001819 if (!DisableValidation && CheckPredefinesBuffers())
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001820 return IgnorePCH;
1821
1822 if (PP) {
1823 // Initialization of keywords and pragmas occurs before the
1824 // PCH file is read, so there may be some identifiers that were
1825 // loaded into the IdentifierTable before we intercepted the
1826 // creation of identifiers. Iterate through the list of known
1827 // identifiers and determine whether we have to establish
1828 // preprocessor definitions or top-level identifier declaration
1829 // chains for those identifiers.
1830 //
1831 // We copy the IdentifierInfo pointers to a small vector first,
1832 // since de-serializing declarations or macro definitions can add
1833 // new entries into the identifier table, invalidating the
1834 // iterators.
1835 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1836 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1837 IdEnd = PP->getIdentifierTable().end();
1838 Id != IdEnd; ++Id)
1839 Identifiers.push_back(Id->second);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001840 // We need to search the tables in all files.
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001841 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1842 PCHIdentifierLookupTable *IdTable
1843 = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00001844 // Not all PCH files necessarily have identifier tables, only the useful
1845 // ones.
1846 if (!IdTable)
1847 continue;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001848 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1849 IdentifierInfo *II = Identifiers[I];
1850 // Look in the on-disk hash tables for an entry for this identifier
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001851 PCHIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001852 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001853 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1854 if (Pos == IdTable->end())
1855 continue;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001856
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001857 // Dereferencing the iterator has the effect of populating the
1858 // IdentifierInfo node with the various declarations it needs.
1859 (void)*Pos;
1860 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001861 }
1862 }
1863
1864 if (Context)
1865 InitializeContext(*Context);
1866
1867 return Success;
1868}
1869
1870PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1871 Chain.push_back(new PerFileData());
Sebastian Redl9137a522010-07-16 17:50:48 +00001872 PerFileData &F = *Chain.back();
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001873
1874 // Set the PCH file name.
1875 F.FileName = FileName;
1876
1877 // Open the PCH file.
1878 //
1879 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1880 std::string ErrStr;
1881 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1882 if (!F.Buffer) {
1883 Error(ErrStr.c_str());
1884 return IgnorePCH;
1885 }
1886
1887 // Initialize the stream
1888 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1889 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl9137a522010-07-16 17:50:48 +00001890 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001891 Stream.init(F.StreamFile);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001892 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001893
1894 // Sniff for the signature.
1895 if (Stream.Read(8) != 'C' ||
1896 Stream.Read(8) != 'P' ||
1897 Stream.Read(8) != 'C' ||
1898 Stream.Read(8) != 'H') {
1899 Diag(diag::err_not_a_pch_file) << FileName;
1900 return Failure;
1901 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001902
Douglas Gregor2cf26342009-04-09 22:27:44 +00001903 while (!Stream.AtEndOfStream()) {
1904 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Douglas Gregore1d918e2009-04-10 23:10:45 +00001906 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001907 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001908 return Failure;
1909 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001910
1911 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001912
Douglas Gregor2cf26342009-04-09 22:27:44 +00001913 // We only know the PCH subblock ID.
1914 switch (BlockID) {
1915 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001916 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001917 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001918 return Failure;
1919 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001920 break;
1921 case pch::PCH_BLOCK_ID:
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001922 switch (ReadPCHBlock(F)) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001923 case Success:
1924 break;
1925
1926 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001927 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001928
1929 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001930 // FIXME: We could consider reading through to the end of this
1931 // PCH block, skipping subblocks, to see if there are other
1932 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001933
1934 // Clear out any preallocated source location entries, so that
1935 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001936 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001937
1938 // Remove the stat cache.
Sebastian Redl9137a522010-07-16 17:50:48 +00001939 if (F.StatCache)
1940 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001941
Douglas Gregore1d918e2009-04-10 23:10:45 +00001942 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001943 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001944 break;
1945 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001946 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001947 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001948 return Failure;
1949 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001950 break;
1951 }
Mike Stump1eb44332009-09-09 15:08:12 +00001952 }
1953
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001954 return Success;
1955}
1956
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001957void PCHReader::setPreprocessor(Preprocessor &pp) {
1958 PP = &pp;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001959
1960 unsigned TotalNum = 0;
1961 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
1962 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
1963 if (TotalNum) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001964 if (!PP->getPreprocessingRecord())
1965 PP->createPreprocessingRecord();
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001966 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001967 }
1968}
1969
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001970void PCHReader::InitializeContext(ASTContext &Ctx) {
1971 Context = &Ctx;
1972 assert(Context && "Passed null context!");
1973
1974 assert(PP && "Forgot to set Preprocessor ?");
1975 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1976 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00001977 PP->setExternalSource(this);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001978
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001979 // Load the translation unit declaration
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00001980 GetTranslationUnitDecl();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001981
1982 // Load the special types.
1983 Context->setBuiltinVaListType(
1984 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1985 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1986 Context->setObjCIdType(GetType(Id));
1987 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1988 Context->setObjCSelType(GetType(Sel));
1989 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1990 Context->setObjCProtoType(GetType(Proto));
1991 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1992 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001993
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001994 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1995 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001996 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001997 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1998 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001999 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
2000 QualType FileType = GetType(File);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002001 if (FileType.isNull()) {
2002 Error("FILE type is NULL");
2003 return;
2004 }
John McCall183700f2009-09-21 23:43:11 +00002005 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002006 Context->setFILEDecl(Typedef->getDecl());
2007 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002008 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002009 if (!Tag) {
2010 Error("Invalid FILE type in PCH file");
2011 return;
2012 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002013 Context->setFILEDecl(Tag->getDecl());
2014 }
2015 }
Mike Stump782fa302009-07-28 02:25:19 +00002016 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
2017 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002018 if (Jmp_bufType.isNull()) {
2019 Error("jmp_bug type is NULL");
2020 return;
2021 }
John McCall183700f2009-09-21 23:43:11 +00002022 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00002023 Context->setjmp_bufDecl(Typedef->getDecl());
2024 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002025 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002026 if (!Tag) {
2027 Error("Invalid jmp_bug type in PCH file");
2028 return;
2029 }
Mike Stump782fa302009-07-28 02:25:19 +00002030 Context->setjmp_bufDecl(Tag->getDecl());
2031 }
2032 }
2033 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
2034 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002035 if (Sigjmp_bufType.isNull()) {
2036 Error("sigjmp_buf type is NULL");
2037 return;
2038 }
John McCall183700f2009-09-21 23:43:11 +00002039 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00002040 Context->setsigjmp_bufDecl(Typedef->getDecl());
2041 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002042 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00002043 assert(Tag && "Invalid sigjmp_buf type in PCH file");
2044 Context->setsigjmp_bufDecl(Tag->getDecl());
2045 }
2046 }
Mike Stump1eb44332009-09-09 15:08:12 +00002047 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00002048 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2049 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00002050 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00002051 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2052 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00002053 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2054 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00002055 if (unsigned String
2056 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2057 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002058 if (unsigned ObjCSelRedef
2059 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2060 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2061 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
2062 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +00002063
2064 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
2065 Context->setInt128Installed();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002066}
2067
Douglas Gregorb64c1932009-05-12 01:31:05 +00002068/// \brief Retrieve the name of the original source file name
2069/// directly from the PCH file, without actually loading the PCH
2070/// file.
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002071std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
2072 Diagnostic &Diags) {
Douglas Gregorb64c1932009-05-12 01:31:05 +00002073 // Open the PCH file.
2074 std::string ErrStr;
2075 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2076 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
2077 if (!Buffer) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002078 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002079 return std::string();
2080 }
2081
2082 // Initialize the stream
2083 llvm::BitstreamReader StreamFile;
2084 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00002085 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00002086 (const unsigned char *)Buffer->getBufferEnd());
2087 Stream.init(StreamFile);
2088
2089 // Sniff for the signature.
2090 if (Stream.Read(8) != 'C' ||
2091 Stream.Read(8) != 'P' ||
2092 Stream.Read(8) != 'C' ||
2093 Stream.Read(8) != 'H') {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002094 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002095 return std::string();
2096 }
2097
2098 RecordData Record;
2099 while (!Stream.AtEndOfStream()) {
2100 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Douglas Gregorb64c1932009-05-12 01:31:05 +00002102 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2103 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Douglas Gregorb64c1932009-05-12 01:31:05 +00002105 // We only know the PCH subblock ID.
2106 switch (BlockID) {
2107 case pch::PCH_BLOCK_ID:
2108 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002109 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002110 return std::string();
2111 }
2112 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Douglas Gregorb64c1932009-05-12 01:31:05 +00002114 default:
2115 if (Stream.SkipBlock()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002116 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002117 return std::string();
2118 }
2119 break;
2120 }
2121 continue;
2122 }
2123
2124 if (Code == llvm::bitc::END_BLOCK) {
2125 if (Stream.ReadBlockEnd()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002126 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002127 return std::string();
2128 }
2129 continue;
2130 }
2131
2132 if (Code == llvm::bitc::DEFINE_ABBREV) {
2133 Stream.ReadAbbrevRecord();
2134 continue;
2135 }
2136
2137 Record.clear();
2138 const char *BlobStart = 0;
2139 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002140 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00002141 == pch::ORIGINAL_FILE_NAME)
2142 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00002143 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00002144
2145 return std::string();
2146}
2147
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002148/// \brief Parse the record that corresponds to a LangOptions data
2149/// structure.
2150///
2151/// This routine compares the language options used to generate the
2152/// PCH file against the language options set for the current
2153/// compilation. For each option, we classify differences between the
2154/// two compiler states as either "benign" or "important". Benign
2155/// differences don't matter, and we accept them without complaint
2156/// (and without modifying the language options). Differences between
2157/// the states for important options cause the PCH file to be
2158/// unusable, so we emit a warning and return true to indicate that
2159/// there was an error.
2160///
2161/// \returns true if the PCH file is unacceptable, false otherwise.
2162bool PCHReader::ParseLanguageOptions(
2163 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002164 if (Listener) {
2165 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002167 #define PARSE_LANGOPT(Option) \
2168 LangOpts.Option = Record[Idx]; \
2169 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002171 unsigned Idx = 0;
2172 PARSE_LANGOPT(Trigraphs);
2173 PARSE_LANGOPT(BCPLComment);
2174 PARSE_LANGOPT(DollarIdents);
2175 PARSE_LANGOPT(AsmPreprocessor);
2176 PARSE_LANGOPT(GNUMode);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +00002177 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002178 PARSE_LANGOPT(ImplicitInt);
2179 PARSE_LANGOPT(Digraphs);
2180 PARSE_LANGOPT(HexFloats);
2181 PARSE_LANGOPT(C99);
2182 PARSE_LANGOPT(Microsoft);
2183 PARSE_LANGOPT(CPlusPlus);
2184 PARSE_LANGOPT(CPlusPlus0x);
2185 PARSE_LANGOPT(CXXOperatorNames);
2186 PARSE_LANGOPT(ObjC1);
2187 PARSE_LANGOPT(ObjC2);
2188 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002189 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +00002190 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002191 PARSE_LANGOPT(PascalStrings);
2192 PARSE_LANGOPT(WritableStrings);
2193 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002194 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002195 PARSE_LANGOPT(Exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +00002196 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002197 PARSE_LANGOPT(NeXTRuntime);
2198 PARSE_LANGOPT(Freestanding);
2199 PARSE_LANGOPT(NoBuiltin);
2200 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00002201 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002202 PARSE_LANGOPT(Blocks);
2203 PARSE_LANGOPT(EmitAllDecls);
2204 PARSE_LANGOPT(MathErrno);
Chris Lattnera4d71452010-06-26 21:25:03 +00002205 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2206 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002207 PARSE_LANGOPT(HeinousExtensions);
2208 PARSE_LANGOPT(Optimize);
2209 PARSE_LANGOPT(OptimizeSize);
2210 PARSE_LANGOPT(Static);
2211 PARSE_LANGOPT(PICLevel);
2212 PARSE_LANGOPT(GNUInline);
2213 PARSE_LANGOPT(NoInline);
2214 PARSE_LANGOPT(AccessControl);
2215 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00002216 PARSE_LANGOPT(ShortWChar);
Chris Lattnera4d71452010-06-26 21:25:03 +00002217 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2218 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbarab8e2812009-09-21 04:16:19 +00002219 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattnera4d71452010-06-26 21:25:03 +00002220 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002221 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002222 PARSE_LANGOPT(OpenCL);
Mike Stump9c276ae2009-12-12 01:27:46 +00002223 PARSE_LANGOPT(CatchUndefined);
2224 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002225 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002226
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002227 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002228 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002229
2230 return false;
2231}
2232
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002233void PCHReader::ReadPreprocessedEntities() {
2234 ReadDefinedMacros();
2235}
2236
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002237/// \brief Get the correct cursor and offset for loading a type.
2238PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
2239 PerFileData *F = 0;
2240 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2241 F = Chain[N - I - 1];
2242 if (Index < F->LocalNumTypes)
2243 break;
2244 Index -= F->LocalNumTypes;
2245 }
2246 assert(F && F->LocalNumTypes > Index && "Broken chain");
Sebastian Redl971dd442010-07-20 22:55:31 +00002247 return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002248}
2249
2250/// \brief Read and return the type with the given index..
Douglas Gregor2cf26342009-04-09 22:27:44 +00002251///
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002252/// The index is the type ID, shifted and minus the number of predefs. This
2253/// routine actually reads the record corresponding to the type at the given
2254/// location. It is a helper routine for GetType, which deals with reading type
2255/// IDs.
2256QualType PCHReader::ReadTypeRecord(unsigned Index) {
2257 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redl971dd442010-07-20 22:55:31 +00002258 llvm::BitstreamCursor &DeclsCursor = *Loc.first;
Sebastian Redl9137a522010-07-16 17:50:48 +00002259
Douglas Gregor0b748912009-04-14 21:18:50 +00002260 // Keep track of where we are in the stream, then jump back there
2261 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002262 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002263
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002264 ReadingKindTracker ReadingKind(Read_Type, *this);
2265
Douglas Gregord89275b2009-07-06 18:54:52 +00002266 // Note that we are loading a type record.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00002267 Deserializing AType(this);
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002269 DeclsCursor.JumpToBit(Loc.second);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002270 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002271 unsigned Code = DeclsCursor.ReadCode();
2272 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00002273 case pch::TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002274 if (Record.size() != 2) {
2275 Error("Incorrect encoding of extended qualifier type");
2276 return QualType();
2277 }
Douglas Gregor6d473962009-04-15 22:00:08 +00002278 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00002279 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2280 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00002281 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002282
Douglas Gregor2cf26342009-04-09 22:27:44 +00002283 case pch::TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002284 if (Record.size() != 1) {
2285 Error("Incorrect encoding of complex type");
2286 return QualType();
2287 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002288 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002289 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002290 }
2291
2292 case pch::TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002293 if (Record.size() != 1) {
2294 Error("Incorrect encoding of pointer type");
2295 return QualType();
2296 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002297 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002298 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002299 }
2300
2301 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002302 if (Record.size() != 1) {
2303 Error("Incorrect encoding of block pointer type");
2304 return QualType();
2305 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002306 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002307 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002308 }
2309
2310 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002311 if (Record.size() != 1) {
2312 Error("Incorrect encoding of lvalue reference type");
2313 return QualType();
2314 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002315 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002316 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002317 }
2318
2319 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002320 if (Record.size() != 1) {
2321 Error("Incorrect encoding of rvalue reference type");
2322 return QualType();
2323 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002324 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002325 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002326 }
2327
2328 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidis240437b2010-07-02 11:55:15 +00002329 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002330 Error("Incorrect encoding of member pointer type");
2331 return QualType();
2332 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002333 QualType PointeeType = GetType(Record[0]);
2334 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002335 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00002336 }
2337
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002338 case pch::TYPE_CONSTANT_ARRAY: {
2339 QualType ElementType = GetType(Record[0]);
2340 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2341 unsigned IndexTypeQuals = Record[2];
2342 unsigned Idx = 3;
2343 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002344 return Context->getConstantArrayType(ElementType, Size,
2345 ASM, IndexTypeQuals);
2346 }
2347
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002348 case pch::TYPE_INCOMPLETE_ARRAY: {
2349 QualType ElementType = GetType(Record[0]);
2350 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2351 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002352 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002353 }
2354
2355 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00002356 QualType ElementType = GetType(Record[0]);
2357 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2358 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002359 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2360 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Sebastian Redl577d4792010-07-22 22:43:28 +00002361 return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002362 ASM, IndexTypeQuals,
2363 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002364 }
2365
2366 case pch::TYPE_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002367 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002368 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002369 return QualType();
2370 }
2371
2372 QualType ElementType = GetType(Record[0]);
2373 unsigned NumElements = Record[1];
Chris Lattner788b0fd2010-06-23 06:00:24 +00002374 unsigned AltiVecSpec = Record[2];
2375 return Context->getVectorType(ElementType, NumElements,
2376 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002377 }
2378
2379 case pch::TYPE_EXT_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002380 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002381 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002382 return QualType();
2383 }
2384
2385 QualType ElementType = GetType(Record[0]);
2386 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002387 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002388 }
2389
2390 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola425ef722010-03-30 22:15:11 +00002391 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002392 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002393 return QualType();
2394 }
2395 QualType ResultType = GetType(Record[0]);
Rafael Espindola425ef722010-03-30 22:15:11 +00002396 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindola264ba482010-03-30 20:24:48 +00002397 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002398 }
2399
2400 case pch::TYPE_FUNCTION_PROTO: {
2401 QualType ResultType = GetType(Record[0]);
Douglas Gregor91236662009-12-22 18:11:50 +00002402 bool NoReturn = Record[1];
Rafael Espindola425ef722010-03-30 22:15:11 +00002403 unsigned RegParm = Record[2];
2404 CallingConv CallConv = (CallingConv)Record[3];
2405 unsigned Idx = 4;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002406 unsigned NumParams = Record[Idx++];
2407 llvm::SmallVector<QualType, 16> ParamTypes;
2408 for (unsigned I = 0; I != NumParams; ++I)
2409 ParamTypes.push_back(GetType(Record[Idx++]));
2410 bool isVariadic = Record[Idx++];
2411 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00002412 bool hasExceptionSpec = Record[Idx++];
2413 bool hasAnyExceptionSpec = Record[Idx++];
2414 unsigned NumExceptions = Record[Idx++];
2415 llvm::SmallVector<QualType, 2> Exceptions;
2416 for (unsigned I = 0; I != NumExceptions; ++I)
2417 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00002418 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00002419 isVariadic, Quals, hasExceptionSpec,
2420 hasAnyExceptionSpec, NumExceptions,
Rafael Espindola264ba482010-03-30 20:24:48 +00002421 Exceptions.data(),
Rafael Espindola425ef722010-03-30 22:15:11 +00002422 FunctionType::ExtInfo(NoReturn, RegParm,
2423 CallConv));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002424 }
2425
John McCalled976492009-12-04 22:46:56 +00002426 case pch::TYPE_UNRESOLVED_USING:
2427 return Context->getTypeDeclType(
2428 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2429
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002430 case pch::TYPE_TYPEDEF: {
2431 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002432 Error("incorrect encoding of typedef type");
2433 return QualType();
2434 }
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002435 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2436 QualType Canonical = GetType(Record[1]);
2437 return Context->getTypedefType(Decl, Canonical);
2438 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002439
2440 case pch::TYPE_TYPEOF_EXPR:
Sebastian Redl577d4792010-07-22 22:43:28 +00002441 return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002442
2443 case pch::TYPE_TYPEOF: {
2444 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002445 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002446 return QualType();
2447 }
2448 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002449 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002450 }
Mike Stump1eb44332009-09-09 15:08:12 +00002451
Anders Carlsson395b4752009-06-24 19:06:50 +00002452 case pch::TYPE_DECLTYPE:
Sebastian Redl577d4792010-07-22 22:43:28 +00002453 return Context->getDecltypeType(ReadExpr(DeclsCursor));
Anders Carlsson395b4752009-06-24 19:06:50 +00002454
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002455 case pch::TYPE_RECORD: {
2456 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002457 Error("incorrect encoding of record type");
2458 return QualType();
2459 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002460 bool IsDependent = Record[0];
2461 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2462 T->Dependent = IsDependent;
2463 return T;
2464 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002465
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002466 case pch::TYPE_ENUM: {
2467 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002468 Error("incorrect encoding of enum type");
2469 return QualType();
2470 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002471 bool IsDependent = Record[0];
2472 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2473 T->Dependent = IsDependent;
2474 return T;
2475 }
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002476
John McCall7da24312009-09-05 00:15:47 +00002477 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002478 unsigned Idx = 0;
2479 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2480 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2481 QualType NamedType = GetType(Record[Idx++]);
2482 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCall7da24312009-09-05 00:15:47 +00002483 }
2484
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002485 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002486 unsigned Idx = 0;
2487 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002488 return Context->getObjCInterfaceType(ItfD);
2489 }
2490
2491 case pch::TYPE_OBJC_OBJECT: {
2492 unsigned Idx = 0;
2493 QualType Base = GetType(Record[Idx++]);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002494 unsigned NumProtos = Record[Idx++];
2495 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2496 for (unsigned I = 0; I != NumProtos; ++I)
2497 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCallc12c5bb2010-05-15 11:32:37 +00002498 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002499 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002500
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002501 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002502 unsigned Idx = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002503 QualType Pointee = GetType(Record[Idx++]);
2504 return Context->getObjCObjectPointerType(Pointee);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002505 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00002506
John McCall49a832b2009-10-18 09:09:24 +00002507 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2508 unsigned Idx = 0;
2509 QualType Parm = GetType(Record[Idx++]);
2510 QualType Replacement = GetType(Record[Idx++]);
2511 return
2512 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2513 Replacement);
2514 }
John McCall3cb0ebd2010-03-10 03:28:59 +00002515
2516 case pch::TYPE_INJECTED_CLASS_NAME: {
2517 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2518 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00002519 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2520 // for PCH reading, too much interdependencies.
2521 return
2522 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCall3cb0ebd2010-03-10 03:28:59 +00002523 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002524
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002525 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2526 unsigned Idx = 0;
2527 unsigned Depth = Record[Idx++];
2528 unsigned Index = Record[Idx++];
2529 bool Pack = Record[Idx++];
2530 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2531 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2532 }
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002533
2534 case pch::TYPE_DEPENDENT_NAME: {
2535 unsigned Idx = 0;
2536 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2537 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2538 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidisf48d45e2010-07-02 11:55:24 +00002539 QualType Canon = GetType(Record[Idx++]);
2540 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002541 }
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002542
2543 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2544 unsigned Idx = 0;
2545 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2546 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2547 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2548 unsigned NumArgs = Record[Idx++];
2549 llvm::SmallVector<TemplateArgument, 8> Args;
2550 Args.reserve(NumArgs);
2551 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00002552 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002553 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2554 Args.size(), Args.data());
2555 }
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002556
2557 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2558 unsigned Idx = 0;
2559
2560 // ArrayType
2561 QualType ElementType = GetType(Record[Idx++]);
2562 ArrayType::ArraySizeModifier ASM
2563 = (ArrayType::ArraySizeModifier)Record[Idx++];
2564 unsigned IndexTypeQuals = Record[Idx++];
2565
2566 // DependentSizedArrayType
Sebastian Redl577d4792010-07-22 22:43:28 +00002567 Expr *NumElts = ReadExpr(DeclsCursor);
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002568 SourceRange Brackets = ReadSourceRange(Record, Idx);
2569
2570 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2571 IndexTypeQuals, Brackets);
2572 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002573
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002574 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2575 unsigned Idx = 0;
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002576 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002577 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002578 llvm::SmallVector<TemplateArgument, 8> Args;
Sebastian Redl577d4792010-07-22 22:43:28 +00002579 ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00002580 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002581 QualType T;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002582 if (Canon.isNull())
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002583 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2584 Args.size());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002585 else
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002586 T = Context->getTemplateSpecializationType(Name, Args.data(),
2587 Args.size(), Canon);
2588 T->Dependent = IsDependent;
2589 return T;
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002590 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002591 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002592 // Suppress a GCC warning
2593 return QualType();
2594}
2595
John McCalla1ee0c52009-10-16 21:56:05 +00002596namespace {
2597
2598class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2599 PCHReader &Reader;
Sebastian Redl577d4792010-07-22 22:43:28 +00002600 llvm::BitstreamCursor &DeclsCursor;
John McCalla1ee0c52009-10-16 21:56:05 +00002601 const PCHReader::RecordData &Record;
2602 unsigned &Idx;
2603
2604public:
Sebastian Redl577d4792010-07-22 22:43:28 +00002605 TypeLocReader(PCHReader &Reader, llvm::BitstreamCursor &Cursor,
2606 const PCHReader::RecordData &Record, unsigned &Idx)
2607 : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
John McCalla1ee0c52009-10-16 21:56:05 +00002608
John McCall51bd8032009-10-18 01:05:36 +00002609 // We want compile-time assurance that we've enumerated all of
2610 // these, so unfortunately we have to declare them first, then
2611 // define them out-of-line.
2612#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00002613#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002614 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002615#include "clang/AST/TypeLocNodes.def"
2616
John McCall51bd8032009-10-18 01:05:36 +00002617 void VisitFunctionTypeLoc(FunctionTypeLoc);
2618 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002619};
2620
2621}
2622
John McCall51bd8032009-10-18 01:05:36 +00002623void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002624 // nothing to do
2625}
John McCall51bd8032009-10-18 01:05:36 +00002626void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorddf889a2010-01-18 18:04:31 +00002627 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2628 if (TL.needsExtraLocalData()) {
2629 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2630 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2631 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2632 TL.setModeAttr(Record[Idx++]);
2633 }
John McCalla1ee0c52009-10-16 21:56:05 +00002634}
John McCall51bd8032009-10-18 01:05:36 +00002635void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2636 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002637}
John McCall51bd8032009-10-18 01:05:36 +00002638void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2639 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002640}
John McCall51bd8032009-10-18 01:05:36 +00002641void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2642 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002643}
John McCall51bd8032009-10-18 01:05:36 +00002644void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2645 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002646}
John McCall51bd8032009-10-18 01:05:36 +00002647void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2648 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002649}
John McCall51bd8032009-10-18 01:05:36 +00002650void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2651 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002652}
John McCall51bd8032009-10-18 01:05:36 +00002653void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2654 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2655 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002656 if (Record[Idx++])
Sebastian Redl577d4792010-07-22 22:43:28 +00002657 TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002658 else
John McCall51bd8032009-10-18 01:05:36 +00002659 TL.setSizeExpr(0);
2660}
2661void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2662 VisitArrayTypeLoc(TL);
2663}
2664void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2665 VisitArrayTypeLoc(TL);
2666}
2667void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2668 VisitArrayTypeLoc(TL);
2669}
2670void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2671 DependentSizedArrayTypeLoc TL) {
2672 VisitArrayTypeLoc(TL);
2673}
2674void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2675 DependentSizedExtVectorTypeLoc TL) {
2676 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2677}
2678void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2679 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2680}
2681void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2682 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2683}
2684void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2685 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2686 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2687 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002688 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002689 }
2690}
2691void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2692 VisitFunctionTypeLoc(TL);
2693}
2694void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2695 VisitFunctionTypeLoc(TL);
2696}
John McCalled976492009-12-04 22:46:56 +00002697void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2698 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2699}
John McCall51bd8032009-10-18 01:05:36 +00002700void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2701 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2702}
2703void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002704 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2705 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2706 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002707}
2708void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002709 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2710 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2711 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Sebastian Redl577d4792010-07-22 22:43:28 +00002712 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002713}
2714void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2715 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2716}
2717void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2718 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2719}
2720void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2721 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2722}
John McCall51bd8032009-10-18 01:05:36 +00002723void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2724 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2725}
John McCall49a832b2009-10-18 09:09:24 +00002726void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2727 SubstTemplateTypeParmTypeLoc TL) {
2728 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2729}
John McCall51bd8032009-10-18 01:05:36 +00002730void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2731 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002732 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2733 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2734 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2735 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2736 TL.setArgLocInfo(i,
2737 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002738 DeclsCursor, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002739}
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002740void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002741 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2742 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002743}
John McCall3cb0ebd2010-03-10 03:28:59 +00002744void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2745 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2746}
Douglas Gregor4714c122010-03-31 17:34:00 +00002747void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002748 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2749 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002750 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2751}
John McCall33500952010-06-11 00:33:02 +00002752void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2753 DependentTemplateSpecializationTypeLoc TL) {
2754 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2755 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2756 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2757 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2758 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2759 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2760 TL.setArgLocInfo(I,
2761 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002762 DeclsCursor, Record, Idx));
John McCall33500952010-06-11 00:33:02 +00002763}
John McCall51bd8032009-10-18 01:05:36 +00002764void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2765 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002766}
2767void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2768 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall51bd8032009-10-18 01:05:36 +00002769 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2770 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2771 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2772 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002773}
John McCall54e14c42009-10-22 22:37:11 +00002774void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2775 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall54e14c42009-10-22 22:37:11 +00002776}
John McCalla1ee0c52009-10-16 21:56:05 +00002777
Sebastian Redl577d4792010-07-22 22:43:28 +00002778TypeSourceInfo *PCHReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2779 const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00002780 unsigned &Idx) {
2781 QualType InfoTy = GetType(Record[Idx++]);
2782 if (InfoTy.isNull())
2783 return 0;
2784
John McCalla93c9342009-12-07 02:54:59 +00002785 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
Sebastian Redl577d4792010-07-22 22:43:28 +00002786 TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00002787 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00002788 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00002789 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00002790}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002791
Douglas Gregor8038d512009-04-10 17:25:41 +00002792QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002793 unsigned FastQuals = ID & Qualifiers::FastMask;
2794 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002795
2796 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2797 QualType T;
2798 switch ((pch::PredefinedTypeIDs)Index) {
2799 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002800 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2801 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002802
2803 case pch::PREDEF_TYPE_CHAR_U_ID:
2804 case pch::PREDEF_TYPE_CHAR_S_ID:
2805 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002806 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002807 break;
2808
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002809 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2810 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2811 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2812 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2813 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002814 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002815 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2816 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2817 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2818 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2819 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2820 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002821 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002822 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2823 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2824 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2825 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2826 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002827 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002828 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2829 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002830 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2831 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002832 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002833 }
2834
2835 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002836 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002837 }
2838
2839 Index -= pch::NUM_PREDEF_TYPE_IDS;
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002840 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl07a353c2010-07-14 20:26:45 +00002841 if (TypesLoaded[Index].isNull()) {
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002842 TypesLoaded[Index] = ReadTypeRecord(Index);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002843 TypesLoaded[Index]->setFromPCH();
Sebastian Redl30c514c2010-07-14 23:45:08 +00002844 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002845 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2846 TypesLoaded[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002847 }
Mike Stump1eb44332009-09-09 15:08:12 +00002848
John McCall0953e762009-09-24 19:53:00 +00002849 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002850}
2851
John McCall833ca992009-10-29 08:12:44 +00002852TemplateArgumentLocInfo
2853PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Sebastian Redl577d4792010-07-22 22:43:28 +00002854 llvm::BitstreamCursor &DeclsCursor,
John McCall833ca992009-10-29 08:12:44 +00002855 const RecordData &Record,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002856 unsigned &Index) {
John McCall833ca992009-10-29 08:12:44 +00002857 switch (Kind) {
2858 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00002859 return ReadExpr(DeclsCursor);
John McCall833ca992009-10-29 08:12:44 +00002860 case TemplateArgument::Type:
Sebastian Redl577d4792010-07-22 22:43:28 +00002861 return GetTypeSourceInfo(DeclsCursor, Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002862 case TemplateArgument::Template: {
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002863 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2864 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2865 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor788cd062009-11-11 01:00:40 +00002866 }
John McCall833ca992009-10-29 08:12:44 +00002867 case TemplateArgument::Null:
2868 case TemplateArgument::Integral:
2869 case TemplateArgument::Declaration:
2870 case TemplateArgument::Pack:
2871 return TemplateArgumentLocInfo();
2872 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002873 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00002874 return TemplateArgumentLocInfo();
2875}
2876
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002877TemplateArgumentLoc
Sebastian Redl577d4792010-07-22 22:43:28 +00002878PCHReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
2879 const RecordData &Record, unsigned &Index) {
2880 TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002881
2882 if (Arg.getKind() == TemplateArgument::Expression) {
2883 if (Record[Index++]) // bool InfoHasSameExpr.
2884 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2885 }
2886 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002887 DeclsCursor,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002888 Record, Index));
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00002889}
2890
John McCall76bd1f32010-06-01 09:23:16 +00002891Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2892 return GetDecl(ID);
2893}
2894
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002895TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl30c514c2010-07-14 23:45:08 +00002896 if (!DeclsLoaded[0]) {
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00002897 ReadDeclRecord(0, 0);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002898 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002899 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002900 }
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002901
2902 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2903}
2904
Douglas Gregor8038d512009-04-10 17:25:41 +00002905Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002906 if (ID == 0)
2907 return 0;
2908
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002909 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002910 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002911 return 0;
2912 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002913
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002914 unsigned Index = ID - 1;
Sebastian Redl30c514c2010-07-14 23:45:08 +00002915 if (!DeclsLoaded[Index]) {
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00002916 ReadDeclRecord(Index, ID);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002917 if (DeserializationListener)
2918 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2919 }
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002920
2921 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002922}
2923
Chris Lattner887e2b32009-04-27 05:46:25 +00002924/// \brief Resolve the offset of a statement into a statement.
2925///
2926/// This operation will read a new statement from the external
2927/// source each time it is called, and is meant to be used via a
2928/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall76bd1f32010-06-01 09:23:16 +00002929Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002930 // Offset here is a global offset across the entire chain.
2931 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2932 PerFileData &F = *Chain[N - I - 1];
2933 if (Offset < F.SizeInBits) {
2934 // Since we know that this statement is part of a decl, make sure to use
2935 // the decl cursor to read it.
2936 F.DeclsCursor.JumpToBit(Offset);
2937 return ReadStmtFromStream(F.DeclsCursor);
2938 }
2939 Offset -= F.SizeInBits;
2940 }
2941 llvm_unreachable("Broken chain");
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002942}
2943
John McCall76bd1f32010-06-01 09:23:16 +00002944bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2945 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002946 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002947 "DeclContext has no lexical decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002948
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002949 // There might be lexical decls in multiple parts of the chain, for the TU
2950 // at least.
2951 DeclContextInfos &Infos = DeclContextOffsets[DC];
2952 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2953 I != E; ++I) {
Sebastian Redl681d7232010-07-27 00:17:23 +00002954 // IDs can be 0 if this context doesn't contain declarations.
2955 if (!I->LexicalDecls)
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002956 continue;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002957
2958 // Load all of the declaration IDs
Sebastian Redl681d7232010-07-27 00:17:23 +00002959 for (const pch::DeclID *ID = I->LexicalDecls,
2960 *IDE = ID + I->NumLexicalDecls;
2961 ID != IDE; ++ID)
2962 Decls.push_back(GetDecl(*ID));
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002963 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002964
Douglas Gregor25123082009-04-22 22:34:57 +00002965 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002966 return false;
2967}
2968
John McCall76bd1f32010-06-01 09:23:16 +00002969DeclContext::lookup_result
2970PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2971 DeclarationName Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00002972 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002973 "DeclContext has no visible decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002974
John McCall76bd1f32010-06-01 09:23:16 +00002975 llvm::SmallVector<VisibleDeclaration, 64> Decls;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002976 // There might be lexical decls in multiple parts of the chain, for the TU
2977 // and namespaces.
2978 DeclContextInfos &Infos = DeclContextOffsets[DC];
2979 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2980 I != E; ++I) {
2981 uint64_t Offset = I->OffsetToVisibleDecls;
2982 if (Offset == 0)
2983 continue;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002984
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002985 llvm::BitstreamCursor &DeclsCursor = *I->Stream;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002986
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002987 // Keep track of where we are in the stream, then jump back there
2988 // after reading this context.
2989 SavedStreamPosition SavedPosition(DeclsCursor);
2990
2991 // Load the record containing all of the declarations visible in
2992 // this context.
2993 DeclsCursor.JumpToBit(Offset);
2994 RecordData Record;
2995 unsigned Code = DeclsCursor.ReadCode();
2996 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2997 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2998 Error("Expected visible block");
2999 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
3000 DeclContext::lookup_iterator());
3001 }
3002
3003 if (Record.empty())
3004 continue;
3005
3006 unsigned Idx = 0;
3007 while (Idx < Record.size()) {
3008 Decls.push_back(VisibleDeclaration());
3009 Decls.back().Name = ReadDeclarationName(Record, Idx);
3010
3011 unsigned Size = Record[Idx++];
3012 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
3013 LoadedDecls.reserve(Size);
3014 for (unsigned J = 0; J < Size; ++J)
3015 LoadedDecls.push_back(Record[Idx++]);
3016 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003017 }
3018
Douglas Gregor25123082009-04-22 22:34:57 +00003019 ++NumVisibleDeclContextsRead;
John McCall76bd1f32010-06-01 09:23:16 +00003020
3021 SetExternalVisibleDecls(DC, Decls);
3022 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregor2cf26342009-04-09 22:27:44 +00003023}
3024
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003025void PCHReader::PassInterestingDeclsToConsumer() {
3026 assert(Consumer);
3027 while (!InterestingDecls.empty()) {
3028 DeclGroupRef DG(InterestingDecls.front());
3029 InterestingDecls.pop_front();
3030 Consumer->HandleTopLevelDecl(DG);
3031 }
3032}
3033
Douglas Gregorfdd01722009-04-14 00:24:19 +00003034void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00003035 this->Consumer = Consumer;
3036
Douglas Gregorfdd01722009-04-14 00:24:19 +00003037 if (!Consumer)
3038 return;
3039
3040 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003041 // Force deserialization of this decl, which will cause it to be queued for
3042 // passing to the consumer.
Daniel Dunbar04a0b502009-09-17 03:06:44 +00003043 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00003044 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00003045
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003046 PassInterestingDeclsToConsumer();
Douglas Gregorfdd01722009-04-14 00:24:19 +00003047}
3048
Douglas Gregor2cf26342009-04-09 22:27:44 +00003049void PCHReader::PrintStats() {
3050 std::fprintf(stderr, "*** PCH Statistics:\n");
3051
Mike Stump1eb44332009-09-09 15:08:12 +00003052 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003053 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00003054 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003055 unsigned NumDeclsLoaded
3056 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3057 (Decl *)0);
3058 unsigned NumIdentifiersLoaded
3059 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3060 IdentifiersLoaded.end(),
3061 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00003062 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003063 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3064 SelectorsLoaded.end(),
3065 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00003066
Douglas Gregor4fed3f42009-04-27 18:38:38 +00003067 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
3068 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003069 if (TotalNumSLocEntries)
3070 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
3071 NumSLocEntriesRead, TotalNumSLocEntries,
3072 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003073 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003074 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003075 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3076 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3077 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003078 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003079 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3080 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003081 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003082 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003083 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3084 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Sebastian Redl725cd962010-08-04 20:40:17 +00003085 if (!SelectorsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003086 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
Sebastian Redl725cd962010-08-04 20:40:17 +00003087 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
3088 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00003089 if (TotalNumStatements)
3090 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3091 NumStatementsRead, TotalNumStatements,
3092 ((float)NumStatementsRead/TotalNumStatements * 100));
3093 if (TotalNumMacros)
3094 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3095 NumMacrosRead, TotalNumMacros,
3096 ((float)NumMacrosRead/TotalNumMacros * 100));
3097 if (TotalLexicalDeclContexts)
3098 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3099 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3100 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3101 * 100));
3102 if (TotalVisibleDeclContexts)
3103 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3104 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3105 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3106 * 100));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003107 if (TotalNumMethodPoolEntries) {
Douglas Gregor83941df2009-04-25 17:48:32 +00003108 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003109 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
3110 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
Douglas Gregor83941df2009-04-25 17:48:32 +00003111 * 100));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003112 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
Douglas Gregor83941df2009-04-25 17:48:32 +00003113 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003114 std::fprintf(stderr, "\n");
3115}
3116
Douglas Gregor668c1a42009-04-21 22:25:48 +00003117void PCHReader::InitializeSema(Sema &S) {
3118 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003119 S.ExternalSource = this;
3120
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003121 // Makes sure any declarations that were deserialized "too early"
3122 // still get added to the identifier's declaration chains.
3123 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3124 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3125 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003126 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003127 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003128
3129 // If there were any tentative definitions, deserialize them and add
Sebastian Redle9d12b62010-01-31 22:27:38 +00003130 // them to Sema's list of tentative definitions.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003131 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3132 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redle9d12b62010-01-31 22:27:38 +00003133 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003134 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00003135
Tanya Lattnere6bbc012010-02-12 00:07:30 +00003136 // If there were any unused static functions, deserialize them and add to
3137 // Sema's list of unused static functions.
3138 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
3139 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3140 SemaObj->UnusedStaticFuncs.push_back(FD);
3141 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00003142
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00003143 // If there were any weak undeclared identifiers, deserialize them and add to
3144 // Sema's list of weak undeclared identifiers.
3145 if (!WeakUndeclaredIdentifiers.empty()) {
3146 unsigned Idx = 0;
3147 for (unsigned I = 0, N = WeakUndeclaredIdentifiers[Idx++]; I != N; ++I) {
3148 IdentifierInfo *WeakId = GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
3149 IdentifierInfo *AliasId=GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
3150 SourceLocation Loc = ReadSourceLocation(WeakUndeclaredIdentifiers, Idx);
3151 bool Used = WeakUndeclaredIdentifiers[Idx++];
3152 Sema::WeakInfo WI(AliasId, Loc);
3153 WI.setUsed(Used);
3154 SemaObj->WeakUndeclaredIdentifiers.insert(std::make_pair(WeakId, WI));
3155 }
3156 }
3157
Douglas Gregor14c22f22009-04-22 22:18:58 +00003158 // If there were any locally-scoped external declarations,
3159 // deserialize them and add them to Sema's table of locally-scoped
3160 // external declarations.
3161 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3162 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3163 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3164 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00003165
3166 // If there were any ext_vector type declarations, deserialize them
3167 // and add them to Sema's vector of such declarations.
3168 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3169 SemaObj->ExtVectorDecls.push_back(
3170 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003171
3172 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3173 // Can we cut them down before writing them ?
3174
3175 // If there were any VTable uses, deserialize the information and add it
3176 // to Sema's vector and map of VTable uses.
Argyrios Kyrtzidisbe4ebcd2010-08-03 17:29:52 +00003177 if (!VTableUses.empty()) {
3178 unsigned Idx = 0;
3179 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3180 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3181 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3182 bool DefinitionRequired = VTableUses[Idx++];
3183 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3184 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3185 }
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003186 }
3187
3188 // If there were any dynamic classes declarations, deserialize them
3189 // and add them to Sema's vector of such declarations.
3190 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3191 SemaObj->DynamicClasses.push_back(
3192 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Fariborz Jahanian32019832010-07-23 19:11:11 +00003193
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +00003194 // If there were any pending implicit instantiations, deserialize them
3195 // and add them to Sema's queue of such instantiations.
3196 assert(PendingImplicitInstantiations.size() % 2 == 0 &&
3197 "Expected pairs of entries");
3198 for (unsigned Idx = 0, N = PendingImplicitInstantiations.size(); Idx < N;) {
3199 ValueDecl *D=cast<ValueDecl>(GetDecl(PendingImplicitInstantiations[Idx++]));
3200 SourceLocation Loc = ReadSourceLocation(PendingImplicitInstantiations, Idx);
3201 SemaObj->PendingImplicitInstantiations.push_back(std::make_pair(D, Loc));
3202 }
3203
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003204 // Load the offsets of the declarations that Sema references.
3205 // They will be lazily deserialized when needed.
3206 if (!SemaDeclRefs.empty()) {
3207 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
3208 SemaObj->StdNamespace = SemaDeclRefs[0];
3209 SemaObj->StdBadAlloc = SemaDeclRefs[1];
3210 }
3211
Fariborz Jahanian32019832010-07-23 19:11:11 +00003212 // If there are @selector references added them to its pool. This is for
3213 // implementation of -Wselector.
Sebastian Redl725cd962010-08-04 20:40:17 +00003214 if (!ReferencedSelectorsData.empty()) {
3215 unsigned int DataSize = ReferencedSelectorsData.size()-1;
Fariborz Jahanian32019832010-07-23 19:11:11 +00003216 unsigned I = 0;
3217 while (I < DataSize) {
Sebastian Redl725cd962010-08-04 20:40:17 +00003218 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
Fariborz Jahanian32019832010-07-23 19:11:11 +00003219 SourceLocation SelLoc =
Sebastian Redl725cd962010-08-04 20:40:17 +00003220 SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
Fariborz Jahanian32019832010-07-23 19:11:11 +00003221 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3222 }
3223 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00003224}
3225
3226IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003227 // Try to find this name within our on-disk hash tables. We start with the
3228 // most recent one, since that one contains the most up-to-date info.
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003229 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3230 PCHIdentifierLookupTable *IdTable
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003231 = (PCHIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00003232 if (!IdTable)
3233 continue;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003234 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3235 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3236 if (Pos == IdTable->end())
3237 continue;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003238
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003239 // Dereferencing the iterator has the effect of building the
3240 // IdentifierInfo node and populating it with the various
3241 // declarations it needs.
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003242 return *Pos;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003243 }
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003244 return 0;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003245}
3246
Mike Stump1eb44332009-09-09 15:08:12 +00003247std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003248PCHReader::ReadMethodPool(Selector Sel) {
Sebastian Redl725cd962010-08-04 20:40:17 +00003249 // Find this selector in a hash table. We want to find the most recent entry.
3250 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3251 PerFileData &F = *Chain[I];
3252 if (!F.SelectorLookupTable)
3253 continue;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003254
Sebastian Redl725cd962010-08-04 20:40:17 +00003255 PCHSelectorLookupTable *PoolTable
3256 = (PCHSelectorLookupTable*)F.SelectorLookupTable;
3257 PCHSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
3258 if (Pos != PoolTable->end()) {
3259 ++NumSelectorsRead;
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003260 // FIXME: Not quite happy with the statistics here. We probably should
3261 // disable this tracking when called via LoadSelector.
3262 // Also, should entries without methods count as misses?
3263 ++NumMethodPoolEntriesRead;
Sebastian Redl725cd962010-08-04 20:40:17 +00003264 PCHSelectorLookupTrait::data_type Data = *Pos;
3265 if (DeserializationListener)
3266 DeserializationListener->SelectorRead(Data.ID, Sel);
3267 return std::make_pair(Data.Instance, Data.Factory);
3268 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003269 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003270
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003271 ++NumMethodPoolMisses;
Sebastian Redl725cd962010-08-04 20:40:17 +00003272 return std::pair<ObjCMethodList, ObjCMethodList>();
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003273}
3274
Sebastian Redle58aa892010-08-04 18:21:41 +00003275void PCHReader::LoadSelector(Selector Sel) {
3276 // It would be complicated to avoid reading the methods anyway. So don't.
3277 ReadMethodPool(Sel);
3278}
3279
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003280void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00003281 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00003282 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003283 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003284 if (DeserializationListener)
3285 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003286}
3287
Douglas Gregord89275b2009-07-06 18:54:52 +00003288/// \brief Set the globally-visible declarations associated with the given
3289/// identifier.
3290///
3291/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00003292/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00003293/// them.
3294///
3295/// \param II an IdentifierInfo that refers to one or more globally-visible
3296/// declarations.
3297///
3298/// \param DeclIDs the set of declaration IDs with the name @p II that are
3299/// visible at global scope.
3300///
3301/// \param Nonrecursive should be true to indicate that the caller knows that
3302/// this call is non-recursive, and therefore the globally-visible declarations
3303/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00003304void
3305PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00003306 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3307 bool Nonrecursive) {
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003308 if (NumCurrentElementsDeserializing && !Nonrecursive) {
Douglas Gregord89275b2009-07-06 18:54:52 +00003309 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3310 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3311 PII.II = II;
3312 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3313 PII.DeclIDs.push_back(DeclIDs[I]);
3314 return;
3315 }
Mike Stump1eb44332009-09-09 15:08:12 +00003316
Douglas Gregord89275b2009-07-06 18:54:52 +00003317 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3318 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3319 if (SemaObj) {
3320 // Introduce this declaration into the translation-unit scope
3321 // and add it to the declaration chain for this identifier, so
3322 // that (unqualified) name lookup will find it.
3323 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3324 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3325 } else {
3326 // Queue this declaration so that it will be added to the
3327 // translation unit scope and identifier's declaration chain
3328 // once a Sema object is known.
3329 PreloadedDecls.push_back(D);
3330 }
3331 }
3332}
3333
Chris Lattner7356a312009-04-11 21:15:38 +00003334IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00003335 if (ID == 0)
3336 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003337
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003338 if (IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003339 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00003340 return 0;
3341 }
Mike Stump1eb44332009-09-09 15:08:12 +00003342
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003343 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003344 ID -= 1;
3345 if (!IdentifiersLoaded[ID]) {
3346 unsigned Index = ID;
3347 const char *Str = 0;
3348 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3349 PerFileData *F = Chain[N - I - 1];
3350 if (Index < F->LocalNumIdentifiers) {
3351 uint32_t Offset = F->IdentifierOffsets[Index];
3352 Str = F->IdentifierTableData + Offset;
3353 break;
3354 }
3355 Index -= F->LocalNumIdentifiers;
3356 }
3357 assert(Str && "Broken Chain");
Douglas Gregord6595a42009-04-25 21:04:17 +00003358
Douglas Gregor02fc7512009-04-28 20:01:51 +00003359 // All of the strings in the PCH file are preceded by a 16-bit
3360 // length. Extract that 16-bit length to avoid having to execute
3361 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00003362 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3363 // unsigned integers. This is important to avoid integer overflow when
3364 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00003365 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00003366 unsigned StrLen = (((unsigned) StrLenPtr[0])
3367 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003368 IdentifiersLoaded[ID]
Kovarththanan Rajaratnam811f4262010-03-12 10:32:27 +00003369 = &PP->getIdentifierTable().get(Str, StrLen);
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003370 if (DeserializationListener)
3371 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregorafaf3082009-04-11 00:14:32 +00003372 }
Mike Stump1eb44332009-09-09 15:08:12 +00003373
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003374 return IdentifiersLoaded[ID];
Douglas Gregor2cf26342009-04-09 22:27:44 +00003375}
3376
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003377void PCHReader::ReadSLocEntry(unsigned ID) {
3378 ReadSLocEntryRecord(ID);
3379}
3380
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003381Selector PCHReader::DecodeSelector(unsigned ID) {
3382 if (ID == 0)
3383 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00003384
Sebastian Redl725cd962010-08-04 20:40:17 +00003385 if (ID > SelectorsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003386 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003387 return Selector();
3388 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003389
Sebastian Redl725cd962010-08-04 20:40:17 +00003390 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
Douglas Gregor83941df2009-04-25 17:48:32 +00003391 // Load this selector from the selector table.
Sebastian Redl725cd962010-08-04 20:40:17 +00003392 unsigned Idx = ID - 1;
3393 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3394 PerFileData &F = *Chain[N - I - 1];
3395 if (Idx < F.LocalNumSelectors) {
3396 PCHSelectorLookupTrait Trait(*this);
3397 SelectorsLoaded[ID - 1] =
3398 Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0);
3399 if (DeserializationListener)
3400 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
3401 break;
3402 }
3403 Idx -= F.LocalNumSelectors;
3404 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003405 }
3406
Sebastian Redl725cd962010-08-04 20:40:17 +00003407 return SelectorsLoaded[ID - 1];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003408}
3409
John McCall76bd1f32010-06-01 09:23:16 +00003410Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003411 return DecodeSelector(ID);
3412}
3413
John McCall76bd1f32010-06-01 09:23:16 +00003414uint32_t PCHReader::GetNumExternalSelectors() {
Sebastian Redl725cd962010-08-04 20:40:17 +00003415 // ID 0 (the null selector) is considered an external selector.
3416 return getTotalNumSelectors() + 1;
Douglas Gregor719770d2010-04-06 17:30:22 +00003417}
3418
Mike Stump1eb44332009-09-09 15:08:12 +00003419DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00003420PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3421 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3422 switch (Kind) {
3423 case DeclarationName::Identifier:
3424 return DeclarationName(GetIdentifierInfo(Record, Idx));
3425
3426 case DeclarationName::ObjCZeroArgSelector:
3427 case DeclarationName::ObjCOneArgSelector:
3428 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00003429 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003430
3431 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003432 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003433 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003434
3435 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003436 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003437 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003438
3439 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003440 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003441 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003442
3443 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003444 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00003445 (OverloadedOperatorKind)Record[Idx++]);
3446
Sean Hunt3e518bd2009-11-29 07:34:05 +00003447 case DeclarationName::CXXLiteralOperatorName:
3448 return Context->DeclarationNames.getCXXLiteralOperatorName(
3449 GetIdentifierInfo(Record, Idx));
3450
Douglas Gregor2cf26342009-04-09 22:27:44 +00003451 case DeclarationName::CXXUsingDirective:
3452 return DeclarationName::getUsingDirectiveName();
3453 }
3454
3455 // Required to silence GCC warning
3456 return DeclarationName();
3457}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003458
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003459TemplateName
3460PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3461 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3462 switch (Kind) {
3463 case TemplateName::Template:
3464 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3465
3466 case TemplateName::OverloadedTemplate: {
3467 unsigned size = Record[Idx++];
3468 UnresolvedSet<8> Decls;
3469 while (size--)
3470 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3471
3472 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3473 }
3474
3475 case TemplateName::QualifiedTemplate: {
3476 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3477 bool hasTemplKeyword = Record[Idx++];
3478 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3479 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3480 }
3481
3482 case TemplateName::DependentTemplate: {
3483 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3484 if (Record[Idx++]) // isIdentifier
3485 return Context->getDependentTemplateName(NNS,
3486 GetIdentifierInfo(Record, Idx));
3487 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00003488 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003489 }
3490 }
3491
3492 assert(0 && "Unhandled template name kind!");
3493 return TemplateName();
3494}
3495
3496TemplateArgument
Sebastian Redl577d4792010-07-22 22:43:28 +00003497PCHReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3498 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003499 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3500 case TemplateArgument::Null:
3501 return TemplateArgument();
3502 case TemplateArgument::Type:
3503 return TemplateArgument(GetType(Record[Idx++]));
3504 case TemplateArgument::Declaration:
3505 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00003506 case TemplateArgument::Integral: {
3507 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3508 QualType T = GetType(Record[Idx++]);
3509 return TemplateArgument(Value, T);
3510 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003511 case TemplateArgument::Template:
3512 return TemplateArgument(ReadTemplateName(Record, Idx));
3513 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00003514 return TemplateArgument(ReadExpr(DeclsCursor));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003515 case TemplateArgument::Pack: {
3516 unsigned NumArgs = Record[Idx++];
3517 llvm::SmallVector<TemplateArgument, 8> Args;
3518 Args.reserve(NumArgs);
3519 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003520 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003521 TemplateArgument TemplArg;
3522 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3523 return TemplArg;
3524 }
3525 }
3526
3527 assert(0 && "Unhandled template argument kind!");
3528 return TemplateArgument();
3529}
3530
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003531TemplateParameterList *
3532PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3533 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3534 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3535 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3536
3537 unsigned NumParams = Record[Idx++];
3538 llvm::SmallVector<NamedDecl *, 16> Params;
3539 Params.reserve(NumParams);
3540 while (NumParams--)
3541 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3542
3543 TemplateParameterList* TemplateParams =
3544 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3545 Params.data(), Params.size(), RAngleLoc);
3546 return TemplateParams;
3547}
3548
3549void
3550PCHReader::
3551ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
Sebastian Redl577d4792010-07-22 22:43:28 +00003552 llvm::BitstreamCursor &DeclsCursor,
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003553 const RecordData &Record, unsigned &Idx) {
3554 unsigned NumTemplateArgs = Record[Idx++];
3555 TemplArgs.reserve(NumTemplateArgs);
3556 while (NumTemplateArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003557 TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003558}
3559
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00003560/// \brief Read a UnresolvedSet structure.
3561void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3562 const RecordData &Record, unsigned &Idx) {
3563 unsigned NumDecls = Record[Idx++];
3564 while (NumDecls--) {
3565 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3566 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3567 Set.addDecl(D, AS);
3568 }
3569}
3570
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003571CXXBaseSpecifier
Nick Lewycky56062202010-07-26 16:56:01 +00003572PCHReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
3573 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003574 bool isVirtual = static_cast<bool>(Record[Idx++]);
3575 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3576 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Nick Lewycky56062202010-07-26 16:56:01 +00003577 TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003578 SourceRange Range = ReadSourceRange(Record, Idx);
Nick Lewycky56062202010-07-26 16:56:01 +00003579 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003580}
3581
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003582NestedNameSpecifier *
3583PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3584 unsigned N = Record[Idx++];
3585 NestedNameSpecifier *NNS = 0, *Prev = 0;
3586 for (unsigned I = 0; I != N; ++I) {
3587 NestedNameSpecifier::SpecifierKind Kind
3588 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3589 switch (Kind) {
3590 case NestedNameSpecifier::Identifier: {
3591 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3592 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3593 break;
3594 }
3595
3596 case NestedNameSpecifier::Namespace: {
3597 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3598 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3599 break;
3600 }
3601
3602 case NestedNameSpecifier::TypeSpec:
3603 case NestedNameSpecifier::TypeSpecWithTemplate: {
3604 Type *T = GetType(Record[Idx++]).getTypePtr();
3605 bool Template = Record[Idx++];
3606 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3607 break;
3608 }
3609
3610 case NestedNameSpecifier::Global: {
3611 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3612 // No associated value, and there can't be a prefix.
3613 break;
3614 }
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003615 }
Argyrios Kyrtzidisd2bb2c02010-07-07 15:46:30 +00003616 Prev = NNS;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003617 }
3618 return NNS;
3619}
3620
3621SourceRange
3622PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar8ee59392010-06-02 15:47:10 +00003623 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3624 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3625 return SourceRange(beg, end);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003626}
3627
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00003628/// \brief Read an integral value
3629llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3630 unsigned BitWidth = Record[Idx++];
3631 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3632 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3633 Idx += NumWords;
3634 return Result;
3635}
3636
3637/// \brief Read a signed integral value
3638llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3639 bool isUnsigned = Record[Idx++];
3640 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3641}
3642
Douglas Gregor17fc2232009-04-14 21:55:33 +00003643/// \brief Read a floating-point value
3644llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00003645 return llvm::APFloat(ReadAPInt(Record, Idx));
3646}
3647
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003648// \brief Read a string
3649std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3650 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00003651 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003652 Idx += Len;
3653 return Result;
3654}
3655
Chris Lattnerd2598362010-05-10 00:25:06 +00003656CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3657 unsigned &Idx) {
3658 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3659 return CXXTemporary::Create(*Context, Decl);
3660}
3661
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003662DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00003663 return Diag(SourceLocation(), DiagID);
3664}
3665
3666DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003667 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003668}
Douglas Gregor025452f2009-04-17 00:04:06 +00003669
Douglas Gregor668c1a42009-04-21 22:25:48 +00003670/// \brief Retrieve the identifier table associated with the
3671/// preprocessor.
3672IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003673 assert(PP && "Forgot to set Preprocessor ?");
3674 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00003675}
3676
Douglas Gregor025452f2009-04-17 00:04:06 +00003677/// \brief Record that the given ID maps to the given switch-case
3678/// statement.
3679void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3680 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3681 SwitchCaseStmts[ID] = SC;
3682}
3683
3684/// \brief Retrieve the switch-case statement with the given ID.
3685SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3686 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3687 return SwitchCaseStmts[ID];
3688}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003689
3690/// \brief Record that the given label statement has been
3691/// deserialized and has the given ID.
3692void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00003693 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003694 "Deserialized label twice");
3695 LabelStmts[ID] = S;
3696
3697 // If we've already seen any goto statements that point to this
3698 // label, resolve them now.
3699 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3700 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3701 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3702 Goto->second->setLabel(S);
3703 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003704
3705 // If we've already seen any address-label statements that point to
3706 // this label, resolve them now.
3707 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00003708 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003709 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00003710 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003711 AddrLabel != AddrLabels.second; ++AddrLabel)
3712 AddrLabel->second->setLabel(S);
3713 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003714}
3715
3716/// \brief Set the label of the given statement to the label
3717/// identified by ID.
3718///
3719/// Depending on the order in which the label and other statements
3720/// referencing that label occur, this operation may complete
3721/// immediately (updating the statement) or it may queue the
3722/// statement to be back-patched later.
3723void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3724 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3725 if (Label != LabelStmts.end()) {
3726 // We've already seen this label, so set the label of the goto and
3727 // we're done.
3728 S->setLabel(Label->second);
3729 } else {
3730 // We haven't seen this label yet, so add this goto to the set of
3731 // unresolved goto statements.
3732 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3733 }
3734}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003735
3736/// \brief Set the label of the given expression to the label
3737/// identified by ID.
3738///
3739/// Depending on the order in which the label and other statements
3740/// referencing that label occur, this operation may complete
3741/// immediately (updating the statement) or it may queue the
3742/// statement to be back-patched later.
3743void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3744 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3745 if (Label != LabelStmts.end()) {
3746 // We've already seen this label, so set the label of the
3747 // label-address expression and we're done.
3748 S->setLabel(Label->second);
3749 } else {
3750 // We haven't seen this label yet, so add this label-address
3751 // expression to the set of unresolved label-address expressions.
3752 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3753 }
3754}
Douglas Gregord89275b2009-07-06 18:54:52 +00003755
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003756void PCHReader::FinishedDeserializing() {
3757 assert(NumCurrentElementsDeserializing &&
3758 "FinishedDeserializing not paired with StartedDeserializing");
3759 if (NumCurrentElementsDeserializing == 1) {
Douglas Gregord89275b2009-07-06 18:54:52 +00003760 // If any identifiers with corresponding top-level declarations have
3761 // been loaded, load those declarations now.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003762 while (!PendingIdentifierInfos.empty()) {
3763 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
3764 PendingIdentifierInfos.front().DeclIDs, true);
3765 PendingIdentifierInfos.pop_front();
Douglas Gregord89275b2009-07-06 18:54:52 +00003766 }
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003767
3768 // We are not in recursive loading, so it's safe to pass the "interesting"
3769 // decls to the consumer.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003770 if (Consumer)
3771 PassInterestingDeclsToConsumer();
Douglas Gregord89275b2009-07-06 18:54:52 +00003772 }
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003773 --NumCurrentElementsDeserializing;
Douglas Gregord89275b2009-07-06 18:54:52 +00003774}