blob: 9c132f40ebcfaca8f959c58a5ad4da604fa99c83 [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,
417 const char *isysroot)
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),
421 StatCache(0), Consumer(0), IdentifierTableData(0), IdentifierLookupTable(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000422 IdentifierOffsets(0),
423 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
424 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000425 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +0000426 NumPreallocatedPreprocessingEntities(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000427 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000428 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000429 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000430 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000431 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000432 RelocatablePCH = false;
433}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000434
435PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000436 Diagnostic &Diags, const char *isysroot)
Sebastian Redl30c514c2010-07-14 23:45:08 +0000437 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
438 Diags(Diags), SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000439 IdentifierTableData(0), IdentifierLookupTable(0),
440 IdentifierOffsets(0),
441 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
442 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000443 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +0000444 NumPreallocatedPreprocessingEntities(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000445 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000446 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000447 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000448 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000449 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000450 RelocatablePCH = false;
451}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000452
453PCHReader::~PCHReader() {}
454
Chris Lattner4c6f9522009-04-27 05:14:47 +0000455
Douglas Gregor668c1a42009-04-21 22:25:48 +0000456namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000457class PCHMethodPoolLookupTrait {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000458 PCHReader &Reader;
459
460public:
461 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
462
463 typedef Selector external_key_type;
464 typedef external_key_type internal_key_type;
465
466 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000468 static bool EqualKey(const internal_key_type& a,
469 const internal_key_type& b) {
470 return a == b;
471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000473 static unsigned ComputeHash(Selector Sel) {
474 unsigned N = Sel.getNumArgs();
475 if (N == 0)
476 ++N;
477 unsigned R = 5381;
478 for (unsigned I = 0; I != N; ++I)
479 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000480 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000481 return R;
482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000484 // This hopefully will just get inlined and removed by the optimizer.
485 static const internal_key_type&
486 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000488 static std::pair<unsigned, unsigned>
489 ReadKeyDataLength(const unsigned char*& d) {
490 using namespace clang::io;
491 unsigned KeyLen = ReadUnalignedLE16(d);
492 unsigned DataLen = ReadUnalignedLE16(d);
493 return std::make_pair(KeyLen, DataLen);
494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Douglas Gregor83941df2009-04-25 17:48:32 +0000496 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000497 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000498 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000499 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000500 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000501 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
502 if (N == 0)
503 return SelTable.getNullarySelector(FirstII);
504 else if (N == 1)
505 return SelTable.getUnarySelector(FirstII);
506
507 llvm::SmallVector<IdentifierInfo *, 16> Args;
508 Args.push_back(FirstII);
509 for (unsigned I = 1; I != N; ++I)
510 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
511
Douglas Gregor75fdb232009-05-22 22:45:36 +0000512 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000513 }
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000515 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
516 using namespace clang::io;
517 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
518 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
519
520 data_type Result;
521
522 // Load instance methods
523 ObjCMethodList *Prev = 0;
524 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000525 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000526 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
527 if (!Result.first.Method) {
528 // This is the first method, which is the easy case.
529 Result.first.Method = Method;
530 Prev = &Result.first;
531 continue;
532 }
533
Ted Kremenek298ed872010-02-11 00:53:01 +0000534 ObjCMethodList *Mem =
535 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
536 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000537 Prev = Prev->Next;
538 }
539
540 // Load factory methods
541 Prev = 0;
542 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000543 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000544 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
545 if (!Result.second.Method) {
546 // This is the first method, which is the easy case.
547 Result.second.Method = Method;
548 Prev = &Result.second;
549 continue;
550 }
551
Ted Kremenek298ed872010-02-11 00:53:01 +0000552 ObjCMethodList *Mem =
553 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
554 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000555 Prev = Prev->Next;
556 }
557
558 return Result;
559 }
560};
Mike Stump1eb44332009-09-09 15:08:12 +0000561
562} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000563
564/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000565typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000566 PCHMethodPoolLookupTable;
567
568namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000569class PCHIdentifierLookupTrait {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000570 PCHReader &Reader;
571
572 // If we know the IdentifierInfo in advance, it is here and we will
573 // not build a new one. Used when deserializing information about an
574 // identifier that was constructed before the PCH file was read.
575 IdentifierInfo *KnownII;
576
577public:
578 typedef IdentifierInfo * data_type;
579
580 typedef const std::pair<const char*, unsigned> external_key_type;
581
582 typedef external_key_type internal_key_type;
583
Mike Stump1eb44332009-09-09 15:08:12 +0000584 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000585 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Douglas Gregor668c1a42009-04-21 22:25:48 +0000587 static bool EqualKey(const internal_key_type& a,
588 const internal_key_type& b) {
589 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
590 : false;
591 }
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Douglas Gregor668c1a42009-04-21 22:25:48 +0000593 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000594 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000595 }
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Douglas Gregor668c1a42009-04-21 22:25:48 +0000597 // This hopefully will just get inlined and removed by the optimizer.
598 static const internal_key_type&
599 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Douglas Gregor668c1a42009-04-21 22:25:48 +0000601 static std::pair<unsigned, unsigned>
602 ReadKeyDataLength(const unsigned char*& d) {
603 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000604 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000605 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000606 return std::make_pair(KeyLen, DataLen);
607 }
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Douglas Gregor668c1a42009-04-21 22:25:48 +0000609 static std::pair<const char*, unsigned>
610 ReadKey(const unsigned char* d, unsigned n) {
611 assert(n >= 2 && d[n-1] == '\0');
612 return std::make_pair((const char*) d, n-1);
613 }
Mike Stump1eb44332009-09-09 15:08:12 +0000614
615 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000616 const unsigned char* d,
617 unsigned DataLen) {
618 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000619 pch::IdentID ID = ReadUnalignedLE32(d);
620 bool IsInteresting = ID & 0x01;
621
622 // Wipe out the "is interesting" bit.
623 ID = ID >> 1;
624
625 if (!IsInteresting) {
626 // For unintersting identifiers, just build the IdentifierInfo
627 // and associate it with the persistent ID.
628 IdentifierInfo *II = KnownII;
629 if (!II)
630 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
631 k.first, k.first + k.second);
632 Reader.SetIdentifierInfo(ID, II);
633 return II;
634 }
635
Douglas Gregor5998da52009-04-28 21:32:13 +0000636 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000637 bool CPlusPlusOperatorKeyword = Bits & 0x01;
638 Bits >>= 1;
639 bool Poisoned = Bits & 0x01;
640 Bits >>= 1;
641 bool ExtensionToken = Bits & 0x01;
642 Bits >>= 1;
643 bool hasMacroDefinition = Bits & 0x01;
644 Bits >>= 1;
645 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
646 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Douglas Gregor2deaea32009-04-22 18:49:13 +0000648 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000649 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000650
651 // Build the IdentifierInfo itself and link the identifier ID with
652 // the new IdentifierInfo.
653 IdentifierInfo *II = KnownII;
654 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000655 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
656 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000657 Reader.SetIdentifierInfo(ID, II);
658
Douglas Gregor2deaea32009-04-22 18:49:13 +0000659 // Set or check the various bits in the IdentifierInfo structure.
660 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000661 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000662 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000663 "Incorrect extension token flag");
664 (void)ExtensionToken;
665 II->setIsPoisoned(Poisoned);
666 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
667 "Incorrect C++ operator keyword flag");
668 (void)CPlusPlusOperatorKeyword;
669
Douglas Gregor37e26842009-04-21 23:56:24 +0000670 // If this identifier is a macro, deserialize the macro
671 // definition.
672 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000673 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000674 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000675 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000676 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000677
678 // Read all of the declarations visible at global scope with this
679 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000680 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000681 if (DataLen > 0) {
682 llvm::SmallVector<uint32_t, 4> DeclIDs;
683 for (; DataLen > 0; DataLen -= 4)
684 DeclIDs.push_back(ReadUnalignedLE32(d));
685 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000686 }
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Douglas Gregor668c1a42009-04-21 22:25:48 +0000688 return II;
689 }
690};
Mike Stump1eb44332009-09-09 15:08:12 +0000691
692} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000693
694/// \brief The on-disk hash table used to contain information about
695/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000696typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000697 PCHIdentifierLookupTable;
698
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000699void PCHReader::Error(const char *Msg) {
700 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000701}
702
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000703/// \brief Check the contents of the concatenation of all predefines buffers in
704/// the PCH chain against the contents of the predefines buffer of the current
705/// compiler invocation.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000706///
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000707/// The contents should be the same. If not, then some command-line option
708/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000709///
710/// \returns true if there was a mismatch (in which case the PCH file
711/// should be ignored), or false otherwise.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000712bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000713 if (Listener)
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000714 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000715 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000716 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000717 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000718}
719
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000720//===----------------------------------------------------------------------===//
721// Source Manager Deserialization
722//===----------------------------------------------------------------------===//
723
Douglas Gregorbd945002009-04-13 16:31:14 +0000724/// \brief Read the line table in the source manager block.
725/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000726bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000727 unsigned Idx = 0;
728 LineTableInfo &LineTable = SourceMgr.getLineTable();
729
730 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000731 std::map<int, int> FileIDs;
732 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000733 // Extract the file name
734 unsigned FilenameLen = Record[Idx++];
735 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
736 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000737 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000738 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000739 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000740 }
741
742 // Parse the line entries
743 std::vector<LineEntry> Entries;
744 while (Idx < Record.size()) {
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000745 int FID = Record[Idx++];
Douglas Gregorbd945002009-04-13 16:31:14 +0000746
747 // Extract the line entries
748 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000749 assert(NumEntries && "Numentries is 00000");
Douglas Gregorbd945002009-04-13 16:31:14 +0000750 Entries.clear();
751 Entries.reserve(NumEntries);
752 for (unsigned I = 0; I != NumEntries; ++I) {
753 unsigned FileOffset = Record[Idx++];
754 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000755 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump1eb44332009-09-09 15:08:12 +0000756 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000757 = (SrcMgr::CharacteristicKind)Record[Idx++];
758 unsigned IncludeOffset = Record[Idx++];
759 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
760 FileKind, IncludeOffset));
761 }
762 LineTable.AddEntry(FID, Entries);
763 }
764
765 return false;
766}
767
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000768namespace {
769
Benjamin Kramerbd218282009-11-28 10:07:24 +0000770class PCHStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000771public:
772 const bool hasStat;
773 const ino_t ino;
774 const dev_t dev;
775 const mode_t mode;
776 const time_t mtime;
777 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000779 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000780 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
781
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000782 PCHStatData()
783 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
784};
785
Benjamin Kramerbd218282009-11-28 10:07:24 +0000786class PCHStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000787 public:
788 typedef const char *external_key_type;
789 typedef const char *internal_key_type;
790
791 typedef PCHStatData data_type;
792
793 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000794 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000795 }
796
797 static internal_key_type GetInternalKey(const char *path) { return path; }
798
799 static bool EqualKey(internal_key_type a, internal_key_type b) {
800 return strcmp(a, b) == 0;
801 }
802
803 static std::pair<unsigned, unsigned>
804 ReadKeyDataLength(const unsigned char*& d) {
805 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
806 unsigned DataLen = (unsigned) *d++;
807 return std::make_pair(KeyLen + 1, DataLen);
808 }
809
810 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
811 return (const char *)d;
812 }
813
814 static data_type ReadData(const internal_key_type, const unsigned char *d,
815 unsigned /*DataLen*/) {
816 using namespace clang::io;
817
818 if (*d++ == 1)
819 return data_type();
820
821 ino_t ino = (ino_t) ReadUnalignedLE32(d);
822 dev_t dev = (dev_t) ReadUnalignedLE32(d);
823 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000824 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000825 off_t size = (off_t) ReadUnalignedLE64(d);
826 return data_type(ino, dev, mode, mtime, size);
827 }
828};
829
830/// \brief stat() cache for precompiled headers.
831///
832/// This cache is very similar to the stat cache used by pretokenized
833/// headers.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000834class PCHStatCache : public StatSysCallCache {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000835 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
836 CacheTy *Cache;
837
838 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000839public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000840 PCHStatCache(const unsigned char *Buckets,
841 const unsigned char *Base,
842 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000843 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000844 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
845 Cache = CacheTy::Create(Buckets, Base);
846 }
847
848 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000850 int stat(const char *path, struct stat *buf) {
851 // Do the lookup for the file's data in the PCH file.
852 CacheTy::iterator I = Cache->find(path);
853
854 // If we don't get a hit in the PCH file just forward to 'stat'.
855 if (I == Cache->end()) {
856 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000857 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000860 ++NumStatHits;
861 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000863 if (!Data.hasStat)
864 return 1;
865
866 buf->st_ino = Data.ino;
867 buf->st_dev = Data.dev;
868 buf->st_mtime = Data.mtime;
869 buf->st_mode = Data.mode;
870 buf->st_size = Data.size;
871 return 0;
872 }
873};
874} // end anonymous namespace
875
876
Douglas Gregor14f79002009-04-10 03:52:48 +0000877/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000878PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000879 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000880
881 // Set the source-location entry cursor to the current position in
882 // the stream. This cursor will be used to read the contents of the
883 // source manager block initially, and then lazily read
884 // source-location entries as needed.
885 SLocEntryCursor = Stream;
886
887 // The stream itself is going to skip over the source manager block.
888 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000889 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000890 return Failure;
891 }
892
893 // Enter the source manager block.
894 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000895 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000896 return Failure;
897 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000898
Douglas Gregor14f79002009-04-10 03:52:48 +0000899 RecordData Record;
900 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000901 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000902 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000903 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000904 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000905 return Failure;
906 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000907 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000908 }
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Douglas Gregor14f79002009-04-10 03:52:48 +0000910 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
911 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000912 SLocEntryCursor.ReadSubBlockID();
913 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000914 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000915 return Failure;
916 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000917 continue;
918 }
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Douglas Gregor14f79002009-04-10 03:52:48 +0000920 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000921 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000922 continue;
923 }
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Douglas Gregor14f79002009-04-10 03:52:48 +0000925 // Read a record.
926 const char *BlobStart;
927 unsigned BlobLen;
928 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000929 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000930 default: // Default behavior: ignore.
931 break;
932
Chris Lattner2c78b872009-04-14 23:22:57 +0000933 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000934 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000935 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000936 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000937
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000938 case pch::SM_SLOC_FILE_ENTRY:
939 case pch::SM_SLOC_BUFFER_ENTRY:
940 case pch::SM_SLOC_INSTANTIATION_ENTRY:
941 // Once we hit one of the source location entries, we're done.
942 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000943 }
944 }
945}
946
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000947/// \brief Read in the source location entry with the given ID.
948PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
949 if (ID == 0)
950 return Success;
951
952 if (ID > TotalNumSLocEntries) {
953 Error("source location entry ID out-of-range for PCH file");
954 return Failure;
955 }
956
957 ++NumSLocEntriesRead;
958 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
959 unsigned Code = SLocEntryCursor.ReadCode();
960 if (Code == llvm::bitc::END_BLOCK ||
961 Code == llvm::bitc::ENTER_SUBBLOCK ||
962 Code == llvm::bitc::DEFINE_ABBREV) {
963 Error("incorrectly-formatted source location entry in PCH file");
964 return Failure;
965 }
966
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000967 RecordData Record;
968 const char *BlobStart;
969 unsigned BlobLen;
970 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
971 default:
972 Error("incorrectly-formatted source location entry in PCH file");
973 return Failure;
974
975 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000976 std::string Filename(BlobStart, BlobStart + BlobLen);
977 MaybeAddSystemRootToFilename(Filename);
978 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000979 if (File == 0) {
980 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000981 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000982 ErrorStr += "' referenced by PCH file";
983 Error(ErrorStr.c_str());
984 return Failure;
985 }
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Douglas Gregor2d52be52010-03-21 22:49:54 +0000987 if (Record.size() < 10) {
Ted Kremenek1857f622010-03-18 21:23:05 +0000988 Error("source location entry is incorrect");
989 return Failure;
990 }
991
Douglas Gregor9f692a02010-04-09 15:54:22 +0000992 if ((off_t)Record[4] != File->getSize()
993#if !defined(LLVM_ON_WIN32)
994 // In our regression testing, the Windows file system seems to
995 // have inconsistent modification times that sometimes
996 // erroneously trigger this error-handling path.
997 || (time_t)Record[5] != File->getModificationTime()
998#endif
999 ) {
Douglas Gregor2d52be52010-03-21 22:49:54 +00001000 Diag(diag::err_fe_pch_file_modified)
1001 << Filename;
1002 return Failure;
1003 }
1004
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001005 FileID FID = SourceMgr.createFileID(File,
1006 SourceLocation::getFromRawEncoding(Record[1]),
1007 (SrcMgr::CharacteristicKind)Record[2],
1008 ID, Record[0]);
1009 if (Record[3])
1010 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1011 .setHasLineDirectives();
1012
Douglas Gregor12fab312010-03-16 16:35:32 +00001013 // Reconstruct header-search information for this file.
1014 HeaderFileInfo HFI;
Douglas Gregor2d52be52010-03-21 22:49:54 +00001015 HFI.isImport = Record[6];
1016 HFI.DirInfo = Record[7];
1017 HFI.NumIncludes = Record[8];
1018 HFI.ControllingMacroID = Record[9];
Douglas Gregor12fab312010-03-16 16:35:32 +00001019 if (Listener)
1020 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001021 break;
1022 }
1023
1024 case pch::SM_SLOC_BUFFER_ENTRY: {
1025 const char *Name = BlobStart;
1026 unsigned Offset = Record[0];
1027 unsigned Code = SLocEntryCursor.ReadCode();
1028 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001029 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001030 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001031
1032 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1033 Error("PCH record has invalid code");
1034 return Failure;
1035 }
1036
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001037 llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001038 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1039 Name);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001040 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Douglas Gregor92b059e2009-04-28 20:33:11 +00001042 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001043 PCHPredefinesBlock Block = {
1044 BufferID,
1045 llvm::StringRef(BlobStart, BlobLen - 1)
1046 };
1047 PCHPredefinesBuffers.push_back(Block);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001048 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001049
1050 break;
1051 }
1052
1053 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +00001054 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001055 = SourceLocation::getFromRawEncoding(Record[1]);
1056 SourceMgr.createInstantiationLoc(SpellingLoc,
1057 SourceLocation::getFromRawEncoding(Record[2]),
1058 SourceLocation::getFromRawEncoding(Record[3]),
1059 Record[4],
1060 ID,
1061 Record[0]);
1062 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001063 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001064 }
1065
1066 return Success;
1067}
1068
Chris Lattner6367f6d2009-04-27 01:05:14 +00001069/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1070/// specified cursor. Read the abbreviations that are at the top of the block
1071/// and then leave the cursor pointing into the block.
1072bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1073 unsigned BlockID) {
1074 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001075 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001076 return Failure;
1077 }
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Chris Lattner6367f6d2009-04-27 01:05:14 +00001079 while (true) {
1080 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Chris Lattner6367f6d2009-04-27 01:05:14 +00001082 // We expect all abbrevs to be at the start of the block.
1083 if (Code != llvm::bitc::DEFINE_ABBREV)
1084 return false;
1085 Cursor.ReadAbbrevRecord();
1086 }
1087}
1088
Douglas Gregor37e26842009-04-21 23:56:24 +00001089void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001090 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Douglas Gregor37e26842009-04-21 23:56:24 +00001092 // Keep track of where we are in the stream, then jump back there
1093 // after reading this macro.
1094 SavedStreamPosition SavedPosition(Stream);
1095
1096 Stream.JumpToBit(Offset);
1097 RecordData Record;
1098 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1099 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Douglas Gregor37e26842009-04-21 23:56:24 +00001101 while (true) {
1102 unsigned Code = Stream.ReadCode();
1103 switch (Code) {
1104 case llvm::bitc::END_BLOCK:
1105 return;
1106
1107 case llvm::bitc::ENTER_SUBBLOCK:
1108 // No known subblocks, always skip them.
1109 Stream.ReadSubBlockID();
1110 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001111 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001112 return;
1113 }
1114 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Douglas Gregor37e26842009-04-21 23:56:24 +00001116 case llvm::bitc::DEFINE_ABBREV:
1117 Stream.ReadAbbrevRecord();
1118 continue;
1119 default: break;
1120 }
1121
1122 // Read a record.
1123 Record.clear();
1124 pch::PreprocessorRecordTypes RecType =
1125 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1126 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001127 case pch::PP_MACRO_OBJECT_LIKE:
1128 case pch::PP_MACRO_FUNCTION_LIKE: {
1129 // If we already have a macro, that means that we've hit the end
1130 // of the definition of the macro we were looking for. We're
1131 // done.
1132 if (Macro)
1133 return;
1134
1135 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1136 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001137 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001138 return;
1139 }
1140 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1141 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001143 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001144 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001146 unsigned NextIndex = 3;
Douglas Gregor37e26842009-04-21 23:56:24 +00001147 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1148 // Decode function-like macro info.
1149 bool isC99VarArgs = Record[3];
1150 bool isGNUVarArgs = Record[4];
1151 MacroArgs.clear();
1152 unsigned NumArgs = Record[5];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001153 NextIndex = 6 + NumArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001154 for (unsigned i = 0; i != NumArgs; ++i)
1155 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1156
1157 // Install function-like macro info.
1158 MI->setIsFunctionLike();
1159 if (isC99VarArgs) MI->setIsC99Varargs();
1160 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001161 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001162 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001163 }
1164
1165 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001166 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001167
1168 // Remember that we saw this macro last so that we add the tokens that
1169 // form its body to it.
1170 Macro = MI;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001171
1172 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1173 // We have a macro definition. Load it now.
1174 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1175 getMacroDefinition(Record[NextIndex]));
1176 }
1177
Douglas Gregor37e26842009-04-21 23:56:24 +00001178 ++NumMacrosRead;
1179 break;
1180 }
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Douglas Gregor37e26842009-04-21 23:56:24 +00001182 case pch::PP_TOKEN: {
1183 // If we see a TOKEN before a PP_MACRO_*, then the file is
1184 // erroneous, just pretend we didn't see this.
1185 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Douglas Gregor37e26842009-04-21 23:56:24 +00001187 Token Tok;
1188 Tok.startToken();
1189 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1190 Tok.setLength(Record[1]);
1191 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1192 Tok.setIdentifierInfo(II);
1193 Tok.setKind((tok::TokenKind)Record[3]);
1194 Tok.setFlag((Token::TokenFlags)Record[4]);
1195 Macro->AddTokenToBody(Tok);
1196 break;
1197 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001198
1199 case pch::PP_MACRO_INSTANTIATION: {
1200 // If we already have a macro, that means that we've hit the end
1201 // of the definition of the macro we were looking for. We're
1202 // done.
1203 if (Macro)
1204 return;
1205
1206 if (!PP->getPreprocessingRecord()) {
1207 Error("missing preprocessing record in PCH file");
1208 return;
1209 }
1210
1211 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1212 if (PPRec.getPreprocessedEntity(Record[0]))
1213 return;
1214
1215 MacroInstantiation *MI
1216 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1217 SourceRange(
1218 SourceLocation::getFromRawEncoding(Record[1]),
1219 SourceLocation::getFromRawEncoding(Record[2])),
1220 getMacroDefinition(Record[4]));
1221 PPRec.SetPreallocatedEntity(Record[0], MI);
1222 return;
1223 }
1224
1225 case pch::PP_MACRO_DEFINITION: {
1226 // If we already have a macro, that means that we've hit the end
1227 // of the definition of the macro we were looking for. We're
1228 // done.
1229 if (Macro)
1230 return;
1231
1232 if (!PP->getPreprocessingRecord()) {
1233 Error("missing preprocessing record in PCH file");
1234 return;
1235 }
1236
1237 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1238 if (PPRec.getPreprocessedEntity(Record[0]))
1239 return;
1240
1241 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1242 Error("out-of-bounds macro definition record");
1243 return;
1244 }
1245
1246 MacroDefinition *MD
1247 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1248 SourceLocation::getFromRawEncoding(Record[5]),
1249 SourceRange(
1250 SourceLocation::getFromRawEncoding(Record[2]),
1251 SourceLocation::getFromRawEncoding(Record[3])));
1252 PPRec.SetPreallocatedEntity(Record[0], MD);
1253 MacroDefinitionsLoaded[Record[1]] = MD;
1254 return;
1255 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001256 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001257 }
1258}
1259
Douglas Gregor88a35862010-01-04 19:18:44 +00001260void PCHReader::ReadDefinedMacros() {
1261 // If there was no preprocessor block, do nothing.
1262 if (!MacroCursor.getBitStreamReader())
1263 return;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001264
Douglas Gregor88a35862010-01-04 19:18:44 +00001265 llvm::BitstreamCursor Cursor = MacroCursor;
1266 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1267 Error("malformed preprocessor block record in PCH file");
1268 return;
1269 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001270
Douglas Gregor88a35862010-01-04 19:18:44 +00001271 RecordData Record;
1272 while (true) {
1273 unsigned Code = Cursor.ReadCode();
1274 if (Code == llvm::bitc::END_BLOCK) {
1275 if (Cursor.ReadBlockEnd())
1276 Error("error at end of preprocessor block in PCH file");
1277 return;
1278 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001279
Douglas Gregor88a35862010-01-04 19:18:44 +00001280 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1281 // No known subblocks, always skip them.
1282 Cursor.ReadSubBlockID();
1283 if (Cursor.SkipBlock()) {
1284 Error("malformed block record in PCH file");
1285 return;
1286 }
1287 continue;
1288 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001289
Douglas Gregor88a35862010-01-04 19:18:44 +00001290 if (Code == llvm::bitc::DEFINE_ABBREV) {
1291 Cursor.ReadAbbrevRecord();
1292 continue;
1293 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001294
Douglas Gregor88a35862010-01-04 19:18:44 +00001295 // Read a record.
1296 const char *BlobStart;
1297 unsigned BlobLen;
1298 Record.clear();
1299 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1300 default: // Default behavior: ignore.
1301 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001302
Douglas Gregor88a35862010-01-04 19:18:44 +00001303 case pch::PP_MACRO_OBJECT_LIKE:
1304 case pch::PP_MACRO_FUNCTION_LIKE:
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001305 DecodeIdentifierInfo(Record[0]);
Douglas Gregor88a35862010-01-04 19:18:44 +00001306 break;
1307
1308 case pch::PP_TOKEN:
1309 // Ignore tokens.
1310 break;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001311
1312 case pch::PP_MACRO_INSTANTIATION:
1313 case pch::PP_MACRO_DEFINITION:
1314 // Read the macro record.
1315 ReadMacroRecord(Cursor.GetCurrentBitNo());
1316 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001317 }
1318 }
1319}
1320
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001321MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1322 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1323 return 0;
1324
1325 if (!MacroDefinitionsLoaded[ID])
1326 ReadMacroRecord(MacroDefinitionOffsets[ID]);
1327
1328 return MacroDefinitionsLoaded[ID];
1329}
1330
Douglas Gregore650c8c2009-07-07 00:12:59 +00001331/// \brief If we are loading a relocatable PCH file, and the filename is
1332/// not an absolute path, add the system root to the beginning of the file
1333/// name.
1334void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1335 // If this is not a relocatable PCH file, there's nothing to do.
1336 if (!RelocatablePCH)
1337 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Daniel Dunbard5b21972009-11-18 19:50:41 +00001339 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001340 return;
1341
Douglas Gregore650c8c2009-07-07 00:12:59 +00001342 if (isysroot == 0) {
1343 // If no system root was given, default to '/'
1344 Filename.insert(Filename.begin(), '/');
1345 return;
1346 }
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Douglas Gregore650c8c2009-07-07 00:12:59 +00001348 unsigned Length = strlen(isysroot);
1349 if (isysroot[Length - 1] != '/')
1350 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Douglas Gregore650c8c2009-07-07 00:12:59 +00001352 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1353}
1354
Mike Stump1eb44332009-09-09 15:08:12 +00001355PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001356PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001357 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001358 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001359 return Failure;
1360 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001361
1362 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001363 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001364 while (!Stream.AtEndOfStream()) {
1365 unsigned Code = Stream.ReadCode();
1366 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001367 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001368 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001369 return Failure;
1370 }
Chris Lattner7356a312009-04-11 21:15:38 +00001371
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001372 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001373 }
1374
1375 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1376 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001377 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001378 // We lazily load the decls block, but we want to set up the
1379 // DeclsCursor cursor to point into it. Clone our current bitcode
1380 // cursor to it, enter the block and read the abbrevs in that block.
1381 // With the main cursor, we just skip over it.
1382 DeclsCursor = Stream;
1383 if (Stream.SkipBlock() || // Skip with the main cursor.
1384 // Read the abbrevs.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001385 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001386 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001387 return Failure;
1388 }
1389 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Chris Lattner7356a312009-04-11 21:15:38 +00001391 case pch::PREPROCESSOR_BLOCK_ID:
Douglas Gregor88a35862010-01-04 19:18:44 +00001392 MacroCursor = Stream;
1393 if (PP)
1394 PP->setExternalSource(this);
1395
Chris Lattner7356a312009-04-11 21:15:38 +00001396 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001397 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001398 return Failure;
1399 }
1400 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001401
Douglas Gregor14f79002009-04-10 03:52:48 +00001402 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001403 switch (ReadSourceManagerBlock()) {
1404 case Success:
1405 break;
1406
1407 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001408 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001409 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001410
1411 case IgnorePCH:
1412 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001413 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001414 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001415 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001416 continue;
1417 }
1418
1419 if (Code == llvm::bitc::DEFINE_ABBREV) {
1420 Stream.ReadAbbrevRecord();
1421 continue;
1422 }
1423
1424 // Read and process a record.
1425 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001426 const char *BlobStart = 0;
1427 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001428 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001429 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001430 default: // Default behavior: ignore.
1431 break;
1432
1433 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001434 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001435 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001436 return Failure;
1437 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001438 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001439 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001440 break;
1441
1442 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001443 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001444 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001445 return Failure;
1446 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001447 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001448 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001449 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001450
1451 case pch::LANGUAGE_OPTIONS:
1452 if (ParseLanguageOptions(Record))
1453 return IgnorePCH;
1454 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001455
Douglas Gregorab41e632009-04-27 22:23:34 +00001456 case pch::METADATA: {
1457 if (Record[0] != pch::VERSION_MAJOR) {
1458 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1459 : diag::warn_pch_version_too_new);
1460 return IgnorePCH;
1461 }
1462
Douglas Gregore650c8c2009-07-07 00:12:59 +00001463 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001464 if (Listener) {
1465 std::string TargetTriple(BlobStart, BlobLen);
1466 if (Listener->ReadTargetTriple(TargetTriple))
1467 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001468 }
1469 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001470 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001471
1472 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001473 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001474 if (Record[0]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001475 IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001476 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001477 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001478 (const unsigned char *)IdentifierTableData,
Douglas Gregor668c1a42009-04-21 22:25:48 +00001479 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001480 if (PP)
1481 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001482 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001483 break;
1484
1485 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001486 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001487 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001488 return Failure;
1489 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001490 IdentifierOffsets = (const uint32_t *)BlobStart;
1491 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001492 if (PP)
1493 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001494 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001495
1496 case pch::EXTERNAL_DEFINITIONS:
1497 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001498 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001499 return Failure;
1500 }
1501 ExternalDefinitions.swap(Record);
1502 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001503
Douglas Gregorad1de002009-04-18 05:55:16 +00001504 case pch::SPECIAL_TYPES:
1505 SpecialTypes.swap(Record);
1506 break;
1507
Douglas Gregor3e1af842009-04-17 22:13:46 +00001508 case pch::STATISTICS:
1509 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001510 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001511 TotalLexicalDeclContexts = Record[2];
1512 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001513 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001514
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001515 case pch::TENTATIVE_DEFINITIONS:
1516 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001517 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001518 return Failure;
1519 }
1520 TentativeDefinitions.swap(Record);
1521 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001522
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001523 case pch::UNUSED_STATIC_FUNCS:
1524 if (!UnusedStaticFuncs.empty()) {
1525 Error("duplicate UNUSED_STATIC_FUNCS record in PCH file");
1526 return Failure;
1527 }
1528 UnusedStaticFuncs.swap(Record);
1529 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001530
Douglas Gregor14c22f22009-04-22 22:18:58 +00001531 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1532 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001533 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001534 return Failure;
1535 }
1536 LocallyScopedExternalDecls.swap(Record);
1537 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001538
Douglas Gregor83941df2009-04-25 17:48:32 +00001539 case pch::SELECTOR_OFFSETS:
1540 SelectorOffsets = (const uint32_t *)BlobStart;
1541 TotalNumSelectors = Record[0];
1542 SelectorsLoaded.resize(TotalNumSelectors);
1543 break;
1544
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001545 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001546 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1547 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001548 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001549 = PCHMethodPoolLookupTable::Create(
1550 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001551 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001552 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001553 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001554 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001555
1556 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001557 if (!Record.empty() && Listener)
1558 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001559 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001560
1561 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001562 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001563 TotalNumSLocEntries = Record[0];
Douglas Gregor445e23e2009-10-05 21:07:28 +00001564 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001565 break;
1566
1567 case pch::SOURCE_LOCATION_PRELOADS:
1568 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1569 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1570 if (Result != Success)
1571 return Result;
1572 }
1573 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001574
Douglas Gregor52e71082009-10-16 18:18:30 +00001575 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001576 PCHStatCache *MyStatCache =
Douglas Gregor52e71082009-10-16 18:18:30 +00001577 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1578 (const unsigned char *)BlobStart,
1579 NumStatHits, NumStatMisses);
1580 FileMgr.addStatCache(MyStatCache);
1581 StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001582 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001583 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001584
Douglas Gregorb81c1702009-04-27 20:06:05 +00001585 case pch::EXT_VECTOR_DECLS:
1586 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001587 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001588 return Failure;
1589 }
1590 ExtVectorDecls.swap(Record);
1591 break;
1592
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001593 case pch::VTABLE_USES:
1594 if (!VTableUses.empty()) {
1595 Error("duplicate VTABLE_USES record in PCH file");
1596 return Failure;
1597 }
1598 VTableUses.swap(Record);
1599 break;
1600
1601 case pch::DYNAMIC_CLASSES:
1602 if (!DynamicClasses.empty()) {
1603 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1604 return Failure;
1605 }
1606 DynamicClasses.swap(Record);
1607 break;
1608
Douglas Gregorb64c1932009-05-12 01:31:05 +00001609 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001610 ActualOriginalFileName.assign(BlobStart, BlobLen);
1611 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001612 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001613 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Ted Kremenek5b4ec632010-01-22 20:59:36 +00001615 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek974be4d2010-02-12 23:31:14 +00001616 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek517e6762010-01-22 20:55:35 +00001617 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Ted Kremenek974be4d2010-02-12 23:31:14 +00001618 if (llvm::StringRef(CurBranch) != PCHBranch) {
Douglas Gregor445e23e2009-10-05 21:07:28 +00001619 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1620 return IgnorePCH;
1621 }
1622 break;
1623 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001624
1625 case pch::MACRO_DEFINITION_OFFSETS:
1626 MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1627 if (PP) {
1628 if (!PP->getPreprocessingRecord())
1629 PP->createPreprocessingRecord();
1630 PP->getPreprocessingRecord()->SetExternalSource(*this, Record[0]);
1631 } else {
1632 NumPreallocatedPreprocessingEntities = Record[0];
1633 }
1634
1635 MacroDefinitionsLoaded.resize(Record[1]);
1636 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001637 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001638 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001639 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001640 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001641}
1642
Douglas Gregore1d918e2009-04-10 23:10:45 +00001643PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001644 // Set the PCH file name.
1645 this->FileName = FileName;
1646
Douglas Gregor2cf26342009-04-09 22:27:44 +00001647 // Open the PCH file.
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001648 //
1649 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001650 std::string ErrStr;
Daniel Dunbar731ad8f2009-11-10 00:46:19 +00001651 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001652 if (!Buffer) {
1653 Error(ErrStr.c_str());
1654 return IgnorePCH;
1655 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001656
1657 // Initialize the stream
Mike Stump1eb44332009-09-09 15:08:12 +00001658 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001659 (const unsigned char *)Buffer->getBufferEnd());
1660 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001661
1662 // Sniff for the signature.
1663 if (Stream.Read(8) != 'C' ||
1664 Stream.Read(8) != 'P' ||
1665 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001666 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001667 Diag(diag::err_not_a_pch_file) << FileName;
1668 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001669 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001670
Douglas Gregor2cf26342009-04-09 22:27:44 +00001671 while (!Stream.AtEndOfStream()) {
1672 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Douglas Gregore1d918e2009-04-10 23:10:45 +00001674 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001675 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001676 return Failure;
1677 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001678
1679 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001680
Douglas Gregor2cf26342009-04-09 22:27:44 +00001681 // We only know the PCH subblock ID.
1682 switch (BlockID) {
1683 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001684 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001685 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001686 return Failure;
1687 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001688 break;
1689 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001690 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001691 case Success:
1692 break;
1693
1694 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001695 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001696
1697 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001698 // FIXME: We could consider reading through to the end of this
1699 // PCH block, skipping subblocks, to see if there are other
1700 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001701
1702 // Clear out any preallocated source location entries, so that
1703 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001704 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001705
1706 // Remove the stat cache.
Douglas Gregor52e71082009-10-16 18:18:30 +00001707 if (StatCache)
1708 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001709
Douglas Gregore1d918e2009-04-10 23:10:45 +00001710 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001711 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001712 break;
1713 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001714 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001715 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001716 return Failure;
1717 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001718 break;
1719 }
Mike Stump1eb44332009-09-09 15:08:12 +00001720 }
1721
Douglas Gregor92b059e2009-04-28 20:33:11 +00001722 // Check the predefines buffer.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001723 if (CheckPredefinesBuffers())
Douglas Gregor92b059e2009-04-28 20:33:11 +00001724 return IgnorePCH;
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001726 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001727 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001728 // PCH file is read, so there may be some identifiers that were
1729 // loaded into the IdentifierTable before we intercepted the
1730 // creation of identifiers. Iterate through the list of known
1731 // identifiers and determine whether we have to establish
1732 // preprocessor definitions or top-level identifier declaration
1733 // chains for those identifiers.
1734 //
1735 // We copy the IdentifierInfo pointers to a small vector first,
1736 // since de-serializing declarations or macro definitions can add
1737 // new entries into the identifier table, invalidating the
1738 // iterators.
1739 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1740 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1741 IdEnd = PP->getIdentifierTable().end();
1742 Id != IdEnd; ++Id)
1743 Identifiers.push_back(Id->second);
Mike Stump1eb44332009-09-09 15:08:12 +00001744 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001745 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1746 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1747 IdentifierInfo *II = Identifiers[I];
1748 // Look in the on-disk hash table for an entry for
1749 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbare013d682009-10-18 20:26:12 +00001750 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001751 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1752 if (Pos == IdTable->end())
1753 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001755 // Dereferencing the iterator has the effect of populating the
1756 // IdentifierInfo node with the various declarations it needs.
1757 (void)*Pos;
1758 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001759 }
1760
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001761 if (Context)
1762 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001763
Douglas Gregor668c1a42009-04-21 22:25:48 +00001764 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001765}
1766
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001767void PCHReader::setPreprocessor(Preprocessor &pp) {
1768 PP = &pp;
1769
1770 if (NumPreallocatedPreprocessingEntities) {
1771 if (!PP->getPreprocessingRecord())
1772 PP->createPreprocessingRecord();
1773 PP->getPreprocessingRecord()->SetExternalSource(*this,
1774 NumPreallocatedPreprocessingEntities);
1775 NumPreallocatedPreprocessingEntities = 0;
1776 }
1777}
1778
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001779void PCHReader::InitializeContext(ASTContext &Ctx) {
1780 Context = &Ctx;
1781 assert(Context && "Passed null context!");
1782
1783 assert(PP && "Forgot to set Preprocessor ?");
1784 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1785 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00001786 PP->setExternalSource(this);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001787
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001788 // Load the translation unit declaration
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00001789 GetTranslationUnitDecl();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001790
1791 // Load the special types.
1792 Context->setBuiltinVaListType(
1793 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1794 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1795 Context->setObjCIdType(GetType(Id));
1796 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1797 Context->setObjCSelType(GetType(Sel));
1798 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1799 Context->setObjCProtoType(GetType(Proto));
1800 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1801 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001802
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001803 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1804 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001805 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001806 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1807 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001808 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1809 QualType FileType = GetType(File);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001810 if (FileType.isNull()) {
1811 Error("FILE type is NULL");
1812 return;
1813 }
John McCall183700f2009-09-21 23:43:11 +00001814 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001815 Context->setFILEDecl(Typedef->getDecl());
1816 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001817 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001818 if (!Tag) {
1819 Error("Invalid FILE type in PCH file");
1820 return;
1821 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001822 Context->setFILEDecl(Tag->getDecl());
1823 }
1824 }
Mike Stump782fa302009-07-28 02:25:19 +00001825 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1826 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001827 if (Jmp_bufType.isNull()) {
1828 Error("jmp_bug type is NULL");
1829 return;
1830 }
John McCall183700f2009-09-21 23:43:11 +00001831 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001832 Context->setjmp_bufDecl(Typedef->getDecl());
1833 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001834 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001835 if (!Tag) {
1836 Error("Invalid jmp_bug type in PCH file");
1837 return;
1838 }
Mike Stump782fa302009-07-28 02:25:19 +00001839 Context->setjmp_bufDecl(Tag->getDecl());
1840 }
1841 }
1842 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1843 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001844 if (Sigjmp_bufType.isNull()) {
1845 Error("sigjmp_buf type is NULL");
1846 return;
1847 }
John McCall183700f2009-09-21 23:43:11 +00001848 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001849 Context->setsigjmp_bufDecl(Typedef->getDecl());
1850 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001851 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001852 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1853 Context->setsigjmp_bufDecl(Tag->getDecl());
1854 }
1855 }
Mike Stump1eb44332009-09-09 15:08:12 +00001856 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001857 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1858 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001859 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001860 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1861 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00001862 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1863 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00001864 if (unsigned String
1865 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1866 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001867 if (unsigned ObjCSelRedef
1868 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
1869 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
1870 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
1871 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +00001872
1873 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
1874 Context->setInt128Installed();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001875}
1876
Douglas Gregorb64c1932009-05-12 01:31:05 +00001877/// \brief Retrieve the name of the original source file name
1878/// directly from the PCH file, without actually loading the PCH
1879/// file.
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001880std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1881 Diagnostic &Diags) {
Douglas Gregorb64c1932009-05-12 01:31:05 +00001882 // Open the PCH file.
1883 std::string ErrStr;
1884 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1885 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1886 if (!Buffer) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001887 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001888 return std::string();
1889 }
1890
1891 // Initialize the stream
1892 llvm::BitstreamReader StreamFile;
1893 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00001894 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00001895 (const unsigned char *)Buffer->getBufferEnd());
1896 Stream.init(StreamFile);
1897
1898 // Sniff for the signature.
1899 if (Stream.Read(8) != 'C' ||
1900 Stream.Read(8) != 'P' ||
1901 Stream.Read(8) != 'C' ||
1902 Stream.Read(8) != 'H') {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001903 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001904 return std::string();
1905 }
1906
1907 RecordData Record;
1908 while (!Stream.AtEndOfStream()) {
1909 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Douglas Gregorb64c1932009-05-12 01:31:05 +00001911 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1912 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Douglas Gregorb64c1932009-05-12 01:31:05 +00001914 // We only know the PCH subblock ID.
1915 switch (BlockID) {
1916 case pch::PCH_BLOCK_ID:
1917 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001918 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001919 return std::string();
1920 }
1921 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Douglas Gregorb64c1932009-05-12 01:31:05 +00001923 default:
1924 if (Stream.SkipBlock()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001925 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001926 return std::string();
1927 }
1928 break;
1929 }
1930 continue;
1931 }
1932
1933 if (Code == llvm::bitc::END_BLOCK) {
1934 if (Stream.ReadBlockEnd()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001935 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001936 return std::string();
1937 }
1938 continue;
1939 }
1940
1941 if (Code == llvm::bitc::DEFINE_ABBREV) {
1942 Stream.ReadAbbrevRecord();
1943 continue;
1944 }
1945
1946 Record.clear();
1947 const char *BlobStart = 0;
1948 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001949 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00001950 == pch::ORIGINAL_FILE_NAME)
1951 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001952 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00001953
1954 return std::string();
1955}
1956
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001957/// \brief Parse the record that corresponds to a LangOptions data
1958/// structure.
1959///
1960/// This routine compares the language options used to generate the
1961/// PCH file against the language options set for the current
1962/// compilation. For each option, we classify differences between the
1963/// two compiler states as either "benign" or "important". Benign
1964/// differences don't matter, and we accept them without complaint
1965/// (and without modifying the language options). Differences between
1966/// the states for important options cause the PCH file to be
1967/// unusable, so we emit a warning and return true to indicate that
1968/// there was an error.
1969///
1970/// \returns true if the PCH file is unacceptable, false otherwise.
1971bool PCHReader::ParseLanguageOptions(
1972 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001973 if (Listener) {
1974 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001976 #define PARSE_LANGOPT(Option) \
1977 LangOpts.Option = Record[Idx]; \
1978 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001980 unsigned Idx = 0;
1981 PARSE_LANGOPT(Trigraphs);
1982 PARSE_LANGOPT(BCPLComment);
1983 PARSE_LANGOPT(DollarIdents);
1984 PARSE_LANGOPT(AsmPreprocessor);
1985 PARSE_LANGOPT(GNUMode);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +00001986 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001987 PARSE_LANGOPT(ImplicitInt);
1988 PARSE_LANGOPT(Digraphs);
1989 PARSE_LANGOPT(HexFloats);
1990 PARSE_LANGOPT(C99);
1991 PARSE_LANGOPT(Microsoft);
1992 PARSE_LANGOPT(CPlusPlus);
1993 PARSE_LANGOPT(CPlusPlus0x);
1994 PARSE_LANGOPT(CXXOperatorNames);
1995 PARSE_LANGOPT(ObjC1);
1996 PARSE_LANGOPT(ObjC2);
1997 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001998 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +00001999 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002000 PARSE_LANGOPT(PascalStrings);
2001 PARSE_LANGOPT(WritableStrings);
2002 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002003 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002004 PARSE_LANGOPT(Exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +00002005 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002006 PARSE_LANGOPT(NeXTRuntime);
2007 PARSE_LANGOPT(Freestanding);
2008 PARSE_LANGOPT(NoBuiltin);
2009 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00002010 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002011 PARSE_LANGOPT(Blocks);
2012 PARSE_LANGOPT(EmitAllDecls);
2013 PARSE_LANGOPT(MathErrno);
Chris Lattnera4d71452010-06-26 21:25:03 +00002014 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2015 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002016 PARSE_LANGOPT(HeinousExtensions);
2017 PARSE_LANGOPT(Optimize);
2018 PARSE_LANGOPT(OptimizeSize);
2019 PARSE_LANGOPT(Static);
2020 PARSE_LANGOPT(PICLevel);
2021 PARSE_LANGOPT(GNUInline);
2022 PARSE_LANGOPT(NoInline);
2023 PARSE_LANGOPT(AccessControl);
2024 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00002025 PARSE_LANGOPT(ShortWChar);
Chris Lattnera4d71452010-06-26 21:25:03 +00002026 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2027 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbarab8e2812009-09-21 04:16:19 +00002028 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattnera4d71452010-06-26 21:25:03 +00002029 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002030 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002031 PARSE_LANGOPT(OpenCL);
Mike Stump9c276ae2009-12-12 01:27:46 +00002032 PARSE_LANGOPT(CatchUndefined);
2033 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002034 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002035
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002036 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002037 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002038
2039 return false;
2040}
2041
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002042void PCHReader::ReadPreprocessedEntities() {
2043 ReadDefinedMacros();
2044}
2045
Douglas Gregor2cf26342009-04-09 22:27:44 +00002046/// \brief Read and return the type at the given offset.
2047///
2048/// This routine actually reads the record corresponding to the type
2049/// at the given offset in the bitstream. It is a helper routine for
2050/// GetType, which deals with reading type IDs.
2051QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00002052 // Keep track of where we are in the stream, then jump back there
2053 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002054 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002055
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002056 ReadingKindTracker ReadingKind(Read_Type, *this);
2057
Douglas Gregord89275b2009-07-06 18:54:52 +00002058 // Note that we are loading a type record.
2059 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002061 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002062 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002063 unsigned Code = DeclsCursor.ReadCode();
2064 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00002065 case pch::TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002066 if (Record.size() != 2) {
2067 Error("Incorrect encoding of extended qualifier type");
2068 return QualType();
2069 }
Douglas Gregor6d473962009-04-15 22:00:08 +00002070 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00002071 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2072 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00002073 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002074
Douglas Gregor2cf26342009-04-09 22:27:44 +00002075 case pch::TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002076 if (Record.size() != 1) {
2077 Error("Incorrect encoding of complex type");
2078 return QualType();
2079 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002080 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002081 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002082 }
2083
2084 case pch::TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002085 if (Record.size() != 1) {
2086 Error("Incorrect encoding of pointer type");
2087 return QualType();
2088 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002089 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002090 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002091 }
2092
2093 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002094 if (Record.size() != 1) {
2095 Error("Incorrect encoding of block pointer type");
2096 return QualType();
2097 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002098 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002099 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002100 }
2101
2102 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002103 if (Record.size() != 1) {
2104 Error("Incorrect encoding of lvalue reference type");
2105 return QualType();
2106 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002107 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002108 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002109 }
2110
2111 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002112 if (Record.size() != 1) {
2113 Error("Incorrect encoding of rvalue reference type");
2114 return QualType();
2115 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002116 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002117 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002118 }
2119
2120 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidis240437b2010-07-02 11:55:15 +00002121 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002122 Error("Incorrect encoding of member pointer type");
2123 return QualType();
2124 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002125 QualType PointeeType = GetType(Record[0]);
2126 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002127 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00002128 }
2129
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002130 case pch::TYPE_CONSTANT_ARRAY: {
2131 QualType ElementType = GetType(Record[0]);
2132 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2133 unsigned IndexTypeQuals = Record[2];
2134 unsigned Idx = 3;
2135 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002136 return Context->getConstantArrayType(ElementType, Size,
2137 ASM, IndexTypeQuals);
2138 }
2139
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002140 case pch::TYPE_INCOMPLETE_ARRAY: {
2141 QualType ElementType = GetType(Record[0]);
2142 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2143 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002144 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002145 }
2146
2147 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00002148 QualType ElementType = GetType(Record[0]);
2149 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2150 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002151 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2152 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002153 return Context->getVariableArrayType(ElementType, ReadExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002154 ASM, IndexTypeQuals,
2155 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002156 }
2157
2158 case pch::TYPE_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002159 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002160 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002161 return QualType();
2162 }
2163
2164 QualType ElementType = GetType(Record[0]);
2165 unsigned NumElements = Record[1];
Chris Lattner788b0fd2010-06-23 06:00:24 +00002166 unsigned AltiVecSpec = Record[2];
2167 return Context->getVectorType(ElementType, NumElements,
2168 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002169 }
2170
2171 case pch::TYPE_EXT_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002172 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002173 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002174 return QualType();
2175 }
2176
2177 QualType ElementType = GetType(Record[0]);
2178 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002179 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002180 }
2181
2182 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola425ef722010-03-30 22:15:11 +00002183 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002184 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002185 return QualType();
2186 }
2187 QualType ResultType = GetType(Record[0]);
Rafael Espindola425ef722010-03-30 22:15:11 +00002188 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindola264ba482010-03-30 20:24:48 +00002189 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002190 }
2191
2192 case pch::TYPE_FUNCTION_PROTO: {
2193 QualType ResultType = GetType(Record[0]);
Douglas Gregor91236662009-12-22 18:11:50 +00002194 bool NoReturn = Record[1];
Rafael Espindola425ef722010-03-30 22:15:11 +00002195 unsigned RegParm = Record[2];
2196 CallingConv CallConv = (CallingConv)Record[3];
2197 unsigned Idx = 4;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002198 unsigned NumParams = Record[Idx++];
2199 llvm::SmallVector<QualType, 16> ParamTypes;
2200 for (unsigned I = 0; I != NumParams; ++I)
2201 ParamTypes.push_back(GetType(Record[Idx++]));
2202 bool isVariadic = Record[Idx++];
2203 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00002204 bool hasExceptionSpec = Record[Idx++];
2205 bool hasAnyExceptionSpec = Record[Idx++];
2206 unsigned NumExceptions = Record[Idx++];
2207 llvm::SmallVector<QualType, 2> Exceptions;
2208 for (unsigned I = 0; I != NumExceptions; ++I)
2209 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00002210 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00002211 isVariadic, Quals, hasExceptionSpec,
2212 hasAnyExceptionSpec, NumExceptions,
Rafael Espindola264ba482010-03-30 20:24:48 +00002213 Exceptions.data(),
Rafael Espindola425ef722010-03-30 22:15:11 +00002214 FunctionType::ExtInfo(NoReturn, RegParm,
2215 CallConv));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002216 }
2217
John McCalled976492009-12-04 22:46:56 +00002218 case pch::TYPE_UNRESOLVED_USING:
2219 return Context->getTypeDeclType(
2220 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2221
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002222 case pch::TYPE_TYPEDEF: {
2223 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002224 Error("incorrect encoding of typedef type");
2225 return QualType();
2226 }
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002227 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2228 QualType Canonical = GetType(Record[1]);
2229 return Context->getTypedefType(Decl, Canonical);
2230 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002231
2232 case pch::TYPE_TYPEOF_EXPR:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002233 return Context->getTypeOfExprType(ReadExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002234
2235 case pch::TYPE_TYPEOF: {
2236 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002237 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002238 return QualType();
2239 }
2240 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002241 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002242 }
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Anders Carlsson395b4752009-06-24 19:06:50 +00002244 case pch::TYPE_DECLTYPE:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002245 return Context->getDecltypeType(ReadExpr());
Anders Carlsson395b4752009-06-24 19:06:50 +00002246
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002247 case pch::TYPE_RECORD: {
2248 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002249 Error("incorrect encoding of record type");
2250 return QualType();
2251 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002252 bool IsDependent = Record[0];
2253 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2254 T->Dependent = IsDependent;
2255 return T;
2256 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002257
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002258 case pch::TYPE_ENUM: {
2259 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002260 Error("incorrect encoding of enum type");
2261 return QualType();
2262 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002263 bool IsDependent = Record[0];
2264 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2265 T->Dependent = IsDependent;
2266 return T;
2267 }
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002268
John McCall7da24312009-09-05 00:15:47 +00002269 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002270 unsigned Idx = 0;
2271 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2272 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2273 QualType NamedType = GetType(Record[Idx++]);
2274 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCall7da24312009-09-05 00:15:47 +00002275 }
2276
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002277 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002278 unsigned Idx = 0;
2279 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002280 return Context->getObjCInterfaceType(ItfD);
2281 }
2282
2283 case pch::TYPE_OBJC_OBJECT: {
2284 unsigned Idx = 0;
2285 QualType Base = GetType(Record[Idx++]);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002286 unsigned NumProtos = Record[Idx++];
2287 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2288 for (unsigned I = 0; I != NumProtos; ++I)
2289 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCallc12c5bb2010-05-15 11:32:37 +00002290 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002291 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002292
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002293 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002294 unsigned Idx = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002295 QualType Pointee = GetType(Record[Idx++]);
2296 return Context->getObjCObjectPointerType(Pointee);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002297 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00002298
John McCall49a832b2009-10-18 09:09:24 +00002299 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2300 unsigned Idx = 0;
2301 QualType Parm = GetType(Record[Idx++]);
2302 QualType Replacement = GetType(Record[Idx++]);
2303 return
2304 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2305 Replacement);
2306 }
John McCall3cb0ebd2010-03-10 03:28:59 +00002307
2308 case pch::TYPE_INJECTED_CLASS_NAME: {
2309 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2310 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00002311 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2312 // for PCH reading, too much interdependencies.
2313 return
2314 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCall3cb0ebd2010-03-10 03:28:59 +00002315 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002316
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002317 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2318 unsigned Idx = 0;
2319 unsigned Depth = Record[Idx++];
2320 unsigned Index = Record[Idx++];
2321 bool Pack = Record[Idx++];
2322 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2323 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2324 }
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002325
2326 case pch::TYPE_DEPENDENT_NAME: {
2327 unsigned Idx = 0;
2328 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2329 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2330 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidisf48d45e2010-07-02 11:55:24 +00002331 QualType Canon = GetType(Record[Idx++]);
2332 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002333 }
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002334
2335 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2336 unsigned Idx = 0;
2337 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2338 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2339 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2340 unsigned NumArgs = Record[Idx++];
2341 llvm::SmallVector<TemplateArgument, 8> Args;
2342 Args.reserve(NumArgs);
2343 while (NumArgs--)
2344 Args.push_back(ReadTemplateArgument(Record, Idx));
2345 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2346 Args.size(), Args.data());
2347 }
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002348
2349 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2350 unsigned Idx = 0;
2351
2352 // ArrayType
2353 QualType ElementType = GetType(Record[Idx++]);
2354 ArrayType::ArraySizeModifier ASM
2355 = (ArrayType::ArraySizeModifier)Record[Idx++];
2356 unsigned IndexTypeQuals = Record[Idx++];
2357
2358 // DependentSizedArrayType
2359 Expr *NumElts = ReadExpr();
2360 SourceRange Brackets = ReadSourceRange(Record, Idx);
2361
2362 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2363 IndexTypeQuals, Brackets);
2364 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002365
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002366 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2367 unsigned Idx = 0;
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002368 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002369 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002370 llvm::SmallVector<TemplateArgument, 8> Args;
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00002371 ReadTemplateArgumentList(Args, Record, Idx);
2372 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002373 QualType T;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002374 if (Canon.isNull())
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002375 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2376 Args.size());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002377 else
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002378 T = Context->getTemplateSpecializationType(Name, Args.data(),
2379 Args.size(), Canon);
2380 T->Dependent = IsDependent;
2381 return T;
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002382 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002383 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002384 // Suppress a GCC warning
2385 return QualType();
2386}
2387
John McCalla1ee0c52009-10-16 21:56:05 +00002388namespace {
2389
2390class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2391 PCHReader &Reader;
2392 const PCHReader::RecordData &Record;
2393 unsigned &Idx;
2394
2395public:
2396 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2397 unsigned &Idx)
2398 : Reader(Reader), Record(Record), Idx(Idx) { }
2399
John McCall51bd8032009-10-18 01:05:36 +00002400 // We want compile-time assurance that we've enumerated all of
2401 // these, so unfortunately we have to declare them first, then
2402 // define them out-of-line.
2403#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00002404#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002405 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002406#include "clang/AST/TypeLocNodes.def"
2407
John McCall51bd8032009-10-18 01:05:36 +00002408 void VisitFunctionTypeLoc(FunctionTypeLoc);
2409 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002410};
2411
2412}
2413
John McCall51bd8032009-10-18 01:05:36 +00002414void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002415 // nothing to do
2416}
John McCall51bd8032009-10-18 01:05:36 +00002417void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorddf889a2010-01-18 18:04:31 +00002418 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2419 if (TL.needsExtraLocalData()) {
2420 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2421 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2422 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2423 TL.setModeAttr(Record[Idx++]);
2424 }
John McCalla1ee0c52009-10-16 21:56:05 +00002425}
John McCall51bd8032009-10-18 01:05:36 +00002426void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2427 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002428}
John McCall51bd8032009-10-18 01:05:36 +00002429void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2430 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002431}
John McCall51bd8032009-10-18 01:05:36 +00002432void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2433 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002434}
John McCall51bd8032009-10-18 01:05:36 +00002435void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2436 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002437}
John McCall51bd8032009-10-18 01:05:36 +00002438void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2439 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002440}
John McCall51bd8032009-10-18 01:05:36 +00002441void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2442 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002443}
John McCall51bd8032009-10-18 01:05:36 +00002444void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2445 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2446 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002447 if (Record[Idx++])
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002448 TL.setSizeExpr(Reader.ReadExpr());
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002449 else
John McCall51bd8032009-10-18 01:05:36 +00002450 TL.setSizeExpr(0);
2451}
2452void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2453 VisitArrayTypeLoc(TL);
2454}
2455void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2456 VisitArrayTypeLoc(TL);
2457}
2458void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2459 VisitArrayTypeLoc(TL);
2460}
2461void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2462 DependentSizedArrayTypeLoc TL) {
2463 VisitArrayTypeLoc(TL);
2464}
2465void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2466 DependentSizedExtVectorTypeLoc TL) {
2467 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2468}
2469void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2470 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2471}
2472void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2473 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2474}
2475void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2476 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2477 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2478 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002479 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002480 }
2481}
2482void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2483 VisitFunctionTypeLoc(TL);
2484}
2485void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2486 VisitFunctionTypeLoc(TL);
2487}
John McCalled976492009-12-04 22:46:56 +00002488void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2489 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2490}
John McCall51bd8032009-10-18 01:05:36 +00002491void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2492 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2493}
2494void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002495 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2496 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2497 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002498}
2499void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002500 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2501 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2502 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2503 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002504}
2505void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2506 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2507}
2508void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2509 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2510}
2511void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2512 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2513}
John McCall51bd8032009-10-18 01:05:36 +00002514void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2515 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2516}
John McCall49a832b2009-10-18 09:09:24 +00002517void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2518 SubstTemplateTypeParmTypeLoc TL) {
2519 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2520}
John McCall51bd8032009-10-18 01:05:36 +00002521void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2522 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002523 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2524 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2525 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2526 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2527 TL.setArgLocInfo(i,
2528 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2529 Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002530}
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002531void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002532 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2533 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002534}
John McCall3cb0ebd2010-03-10 03:28:59 +00002535void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2536 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2537}
Douglas Gregor4714c122010-03-31 17:34:00 +00002538void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002539 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2540 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002541 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2542}
John McCall33500952010-06-11 00:33:02 +00002543void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2544 DependentTemplateSpecializationTypeLoc TL) {
2545 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2546 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2547 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2548 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2549 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2550 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2551 TL.setArgLocInfo(I,
2552 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
2553 Record, Idx));
2554}
John McCall51bd8032009-10-18 01:05:36 +00002555void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2556 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002557}
2558void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2559 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall51bd8032009-10-18 01:05:36 +00002560 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2561 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2562 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2563 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002564}
John McCall54e14c42009-10-22 22:37:11 +00002565void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2566 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall54e14c42009-10-22 22:37:11 +00002567}
John McCalla1ee0c52009-10-16 21:56:05 +00002568
John McCalla93c9342009-12-07 02:54:59 +00002569TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00002570 unsigned &Idx) {
2571 QualType InfoTy = GetType(Record[Idx++]);
2572 if (InfoTy.isNull())
2573 return 0;
2574
John McCalla93c9342009-12-07 02:54:59 +00002575 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCalla1ee0c52009-10-16 21:56:05 +00002576 TypeLocReader TLR(*this, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00002577 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00002578 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00002579 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00002580}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002581
Douglas Gregor8038d512009-04-10 17:25:41 +00002582QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002583 unsigned FastQuals = ID & Qualifiers::FastMask;
2584 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002585
2586 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2587 QualType T;
2588 switch ((pch::PredefinedTypeIDs)Index) {
2589 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002590 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2591 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002592
2593 case pch::PREDEF_TYPE_CHAR_U_ID:
2594 case pch::PREDEF_TYPE_CHAR_S_ID:
2595 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002596 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002597 break;
2598
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002599 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2600 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2601 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2602 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2603 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002604 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002605 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2606 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2607 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2608 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2609 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2610 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002611 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002612 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2613 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2614 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2615 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2616 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002617 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002618 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2619 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002620 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2621 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002622 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002623 }
2624
2625 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002626 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002627 }
2628
2629 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002630 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl07a353c2010-07-14 20:26:45 +00002631 if (TypesLoaded[Index].isNull()) {
John McCall0953e762009-09-24 19:53:00 +00002632 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002633 TypesLoaded[Index]->setFromPCH();
Sebastian Redl30c514c2010-07-14 23:45:08 +00002634 if (DeserializationListener)
2635 DeserializationListener->TypeRead(ID, TypesLoaded[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002636 }
Mike Stump1eb44332009-09-09 15:08:12 +00002637
John McCall0953e762009-09-24 19:53:00 +00002638 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002639}
2640
John McCall833ca992009-10-29 08:12:44 +00002641TemplateArgumentLocInfo
2642PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2643 const RecordData &Record,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002644 unsigned &Index) {
John McCall833ca992009-10-29 08:12:44 +00002645 switch (Kind) {
2646 case TemplateArgument::Expression:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002647 return ReadExpr();
John McCall833ca992009-10-29 08:12:44 +00002648 case TemplateArgument::Type:
John McCalla93c9342009-12-07 02:54:59 +00002649 return GetTypeSourceInfo(Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002650 case TemplateArgument::Template: {
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002651 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2652 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2653 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor788cd062009-11-11 01:00:40 +00002654 }
John McCall833ca992009-10-29 08:12:44 +00002655 case TemplateArgument::Null:
2656 case TemplateArgument::Integral:
2657 case TemplateArgument::Declaration:
2658 case TemplateArgument::Pack:
2659 return TemplateArgumentLocInfo();
2660 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002661 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00002662 return TemplateArgumentLocInfo();
2663}
2664
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002665TemplateArgumentLoc
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002666PCHReader::ReadTemplateArgumentLoc(const RecordData &Record, unsigned &Index) {
2667 TemplateArgument Arg = ReadTemplateArgument(Record, Index);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002668
2669 if (Arg.getKind() == TemplateArgument::Expression) {
2670 if (Record[Index++]) // bool InfoHasSameExpr.
2671 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2672 }
2673 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002674 Record, Index));
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00002675}
2676
John McCall76bd1f32010-06-01 09:23:16 +00002677Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2678 return GetDecl(ID);
2679}
2680
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002681TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl30c514c2010-07-14 23:45:08 +00002682 if (!DeclsLoaded[0]) {
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002683 ReadDeclRecord(DeclOffsets[0], 0);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002684 if (DeserializationListener)
2685 DeserializationListener->DeclRead(0, DeclsLoaded[0]);
2686 }
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002687
2688 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2689}
2690
Douglas Gregor8038d512009-04-10 17:25:41 +00002691Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002692 if (ID == 0)
2693 return 0;
2694
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002695 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002696 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002697 return 0;
2698 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002699
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002700 unsigned Index = ID - 1;
Sebastian Redl30c514c2010-07-14 23:45:08 +00002701 if (!DeclsLoaded[Index]) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002702 ReadDeclRecord(DeclOffsets[Index], Index);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002703 if (DeserializationListener)
2704 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2705 }
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002706
2707 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002708}
2709
Chris Lattner887e2b32009-04-27 05:46:25 +00002710/// \brief Resolve the offset of a statement into a statement.
2711///
2712/// This operation will read a new statement from the external
2713/// source each time it is called, and is meant to be used via a
2714/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall76bd1f32010-06-01 09:23:16 +00002715Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002716 // Since we know tha this statement is part of a decl, make sure to use the
2717 // decl cursor to read it.
2718 DeclsCursor.JumpToBit(Offset);
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002719 return ReadStmtFromStream(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002720}
2721
John McCall76bd1f32010-06-01 09:23:16 +00002722bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2723 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002724 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002725 "DeclContext has no lexical decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002726
Douglas Gregor2cf26342009-04-09 22:27:44 +00002727 uint64_t Offset = DeclContextOffsets[DC].first;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002728 if (Offset == 0) {
2729 Error("DeclContext has no lexical decls in storage");
2730 return true;
2731 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002732
Douglas Gregor0b748912009-04-14 21:18:50 +00002733 // Keep track of where we are in the stream, then jump back there
2734 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002735 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002736
Douglas Gregor2cf26342009-04-09 22:27:44 +00002737 // Load the record containing all of the declarations lexically in
2738 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002739 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002740 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002741 unsigned Code = DeclsCursor.ReadCode();
2742 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002743 if (RecCode != pch::DECL_CONTEXT_LEXICAL) {
2744 Error("Expected lexical block");
2745 return true;
2746 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002747
2748 // Load all of the declaration IDs
John McCall76bd1f32010-06-01 09:23:16 +00002749 for (RecordData::iterator I = Record.begin(), E = Record.end(); I != E; ++I)
2750 Decls.push_back(GetDecl(*I));
Douglas Gregor25123082009-04-22 22:34:57 +00002751 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002752 return false;
2753}
2754
John McCall76bd1f32010-06-01 09:23:16 +00002755DeclContext::lookup_result
2756PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2757 DeclarationName Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00002758 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002759 "DeclContext has no visible decls in storage");
2760 uint64_t Offset = DeclContextOffsets[DC].second;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002761 if (Offset == 0) {
2762 Error("DeclContext has no visible decls in storage");
John McCall76bd1f32010-06-01 09:23:16 +00002763 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2764 DeclContext::lookup_iterator());
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002765 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002766
Douglas Gregor0b748912009-04-14 21:18:50 +00002767 // Keep track of where we are in the stream, then jump back there
2768 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002769 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002770
Douglas Gregor2cf26342009-04-09 22:27:44 +00002771 // Load the record containing all of the declarations visible in
2772 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002773 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002774 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002775 unsigned Code = DeclsCursor.ReadCode();
2776 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002777 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2778 Error("Expected visible block");
John McCall76bd1f32010-06-01 09:23:16 +00002779 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2780 DeclContext::lookup_iterator());
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002781 }
2782
John McCall76bd1f32010-06-01 09:23:16 +00002783 llvm::SmallVector<VisibleDeclaration, 64> Decls;
2784 if (Record.empty()) {
2785 SetExternalVisibleDecls(DC, Decls);
2786 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2787 DeclContext::lookup_iterator());
2788 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002789
2790 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002791 while (Idx < Record.size()) {
2792 Decls.push_back(VisibleDeclaration());
2793 Decls.back().Name = ReadDeclarationName(Record, Idx);
2794
Douglas Gregor2cf26342009-04-09 22:27:44 +00002795 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002796 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002797 LoadedDecls.reserve(Size);
2798 for (unsigned I = 0; I < Size; ++I)
2799 LoadedDecls.push_back(Record[Idx++]);
2800 }
2801
Douglas Gregor25123082009-04-22 22:34:57 +00002802 ++NumVisibleDeclContextsRead;
John McCall76bd1f32010-06-01 09:23:16 +00002803
2804 SetExternalVisibleDecls(DC, Decls);
2805 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002806}
2807
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00002808void PCHReader::PassInterestingDeclsToConsumer() {
2809 assert(Consumer);
2810 while (!InterestingDecls.empty()) {
2811 DeclGroupRef DG(InterestingDecls.front());
2812 InterestingDecls.pop_front();
2813 Consumer->HandleTopLevelDecl(DG);
2814 }
2815}
2816
Douglas Gregorfdd01722009-04-14 00:24:19 +00002817void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002818 this->Consumer = Consumer;
2819
Douglas Gregorfdd01722009-04-14 00:24:19 +00002820 if (!Consumer)
2821 return;
2822
2823 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00002824 // Force deserialization of this decl, which will cause it to be queued for
2825 // passing to the consumer.
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002826 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002827 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002828
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00002829 PassInterestingDeclsToConsumer();
Douglas Gregorfdd01722009-04-14 00:24:19 +00002830}
2831
Douglas Gregor2cf26342009-04-09 22:27:44 +00002832void PCHReader::PrintStats() {
2833 std::fprintf(stderr, "*** PCH Statistics:\n");
2834
Mike Stump1eb44332009-09-09 15:08:12 +00002835 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002836 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002837 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002838 unsigned NumDeclsLoaded
2839 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2840 (Decl *)0);
2841 unsigned NumIdentifiersLoaded
2842 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2843 IdentifiersLoaded.end(),
2844 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002845 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002846 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2847 SelectorsLoaded.end(),
2848 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002849
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002850 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2851 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002852 if (TotalNumSLocEntries)
2853 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2854 NumSLocEntriesRead, TotalNumSLocEntries,
2855 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002856 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002857 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002858 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2859 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2860 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002861 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002862 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2863 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002864 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002865 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002866 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2867 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002868 if (TotalNumSelectors)
2869 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2870 NumSelectorsLoaded, TotalNumSelectors,
2871 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2872 if (TotalNumStatements)
2873 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2874 NumStatementsRead, TotalNumStatements,
2875 ((float)NumStatementsRead/TotalNumStatements * 100));
2876 if (TotalNumMacros)
2877 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2878 NumMacrosRead, TotalNumMacros,
2879 ((float)NumMacrosRead/TotalNumMacros * 100));
2880 if (TotalLexicalDeclContexts)
2881 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2882 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2883 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2884 * 100));
2885 if (TotalVisibleDeclContexts)
2886 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2887 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2888 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2889 * 100));
2890 if (TotalSelectorsInMethodPool) {
2891 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2892 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2893 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2894 * 100));
2895 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2896 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002897 std::fprintf(stderr, "\n");
2898}
2899
Douglas Gregor668c1a42009-04-21 22:25:48 +00002900void PCHReader::InitializeSema(Sema &S) {
2901 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002902 S.ExternalSource = this;
2903
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002904 // Makes sure any declarations that were deserialized "too early"
2905 // still get added to the identifier's declaration chains.
2906 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2907 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2908 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002909 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002910 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002911
2912 // If there were any tentative definitions, deserialize them and add
Sebastian Redle9d12b62010-01-31 22:27:38 +00002913 // them to Sema's list of tentative definitions.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002914 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2915 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redle9d12b62010-01-31 22:27:38 +00002916 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002917 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00002918
Tanya Lattnere6bbc012010-02-12 00:07:30 +00002919 // If there were any unused static functions, deserialize them and add to
2920 // Sema's list of unused static functions.
2921 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
2922 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
2923 SemaObj->UnusedStaticFuncs.push_back(FD);
2924 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002925
2926 // If there were any locally-scoped external declarations,
2927 // deserialize them and add them to Sema's table of locally-scoped
2928 // external declarations.
2929 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2930 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2931 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2932 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002933
2934 // If there were any ext_vector type declarations, deserialize them
2935 // and add them to Sema's vector of such declarations.
2936 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2937 SemaObj->ExtVectorDecls.push_back(
2938 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00002939
2940 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
2941 // Can we cut them down before writing them ?
2942
2943 // If there were any VTable uses, deserialize the information and add it
2944 // to Sema's vector and map of VTable uses.
2945 unsigned Idx = 0;
2946 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
2947 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
2948 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
2949 bool DefinitionRequired = VTableUses[Idx++];
2950 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
2951 SemaObj->VTablesUsed[Class] = DefinitionRequired;
2952 }
2953
2954 // If there were any dynamic classes declarations, deserialize them
2955 // and add them to Sema's vector of such declarations.
2956 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
2957 SemaObj->DynamicClasses.push_back(
2958 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002959}
2960
2961IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2962 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00002963 PCHIdentifierLookupTable *IdTable
Douglas Gregor668c1a42009-04-21 22:25:48 +00002964 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2965 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2966 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2967 if (Pos == IdTable->end())
2968 return 0;
2969
2970 // Dereferencing the iterator has the effect of building the
2971 // IdentifierInfo node and populating it with the various
2972 // declarations it needs.
2973 return *Pos;
2974}
2975
Mike Stump1eb44332009-09-09 15:08:12 +00002976std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002977PCHReader::ReadMethodPool(Selector Sel) {
2978 if (!MethodPoolLookupTable)
2979 return std::pair<ObjCMethodList, ObjCMethodList>();
2980
2981 // Try to find this selector within our on-disk hash table.
2982 PCHMethodPoolLookupTable *PoolTable
2983 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2984 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002985 if (Pos == PoolTable->end()) {
2986 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002987 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002988 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002989
Douglas Gregor83941df2009-04-25 17:48:32 +00002990 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002991 return *Pos;
2992}
2993
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002994void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002995 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002996 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002997 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002998}
2999
Douglas Gregord89275b2009-07-06 18:54:52 +00003000/// \brief Set the globally-visible declarations associated with the given
3001/// identifier.
3002///
3003/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00003004/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00003005/// them.
3006///
3007/// \param II an IdentifierInfo that refers to one or more globally-visible
3008/// declarations.
3009///
3010/// \param DeclIDs the set of declaration IDs with the name @p II that are
3011/// visible at global scope.
3012///
3013/// \param Nonrecursive should be true to indicate that the caller knows that
3014/// this call is non-recursive, and therefore the globally-visible declarations
3015/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00003016void
3017PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00003018 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3019 bool Nonrecursive) {
3020 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
3021 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3022 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3023 PII.II = II;
3024 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3025 PII.DeclIDs.push_back(DeclIDs[I]);
3026 return;
3027 }
Mike Stump1eb44332009-09-09 15:08:12 +00003028
Douglas Gregord89275b2009-07-06 18:54:52 +00003029 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3030 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3031 if (SemaObj) {
3032 // Introduce this declaration into the translation-unit scope
3033 // and add it to the declaration chain for this identifier, so
3034 // that (unqualified) name lookup will find it.
3035 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3036 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3037 } else {
3038 // Queue this declaration so that it will be added to the
3039 // translation unit scope and identifier's declaration chain
3040 // once a Sema object is known.
3041 PreloadedDecls.push_back(D);
3042 }
3043 }
3044}
3045
Chris Lattner7356a312009-04-11 21:15:38 +00003046IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00003047 if (ID == 0)
3048 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003049
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003050 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003051 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00003052 return 0;
3053 }
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003055 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003056 if (!IdentifiersLoaded[ID - 1]) {
3057 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00003058 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00003059
Douglas Gregor02fc7512009-04-28 20:01:51 +00003060 // All of the strings in the PCH file are preceded by a 16-bit
3061 // length. Extract that 16-bit length to avoid having to execute
3062 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00003063 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3064 // unsigned integers. This is important to avoid integer overflow when
3065 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00003066 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00003067 unsigned StrLen = (((unsigned) StrLenPtr[0])
3068 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003069 IdentifiersLoaded[ID - 1]
Kovarththanan Rajaratnam811f4262010-03-12 10:32:27 +00003070 = &PP->getIdentifierTable().get(Str, StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00003071 }
Mike Stump1eb44332009-09-09 15:08:12 +00003072
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003073 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00003074}
3075
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003076void PCHReader::ReadSLocEntry(unsigned ID) {
3077 ReadSLocEntryRecord(ID);
3078}
3079
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003080Selector PCHReader::DecodeSelector(unsigned ID) {
3081 if (ID == 0)
3082 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Douglas Gregora02b1472009-04-28 21:53:25 +00003084 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003085 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00003086
3087 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003088 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003089 return Selector();
3090 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003091
3092 unsigned Index = ID - 1;
3093 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
3094 // Load this selector from the selector table.
3095 // FIXME: endianness portability issues with SelectorOffsets table
3096 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00003097 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00003098 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
3099 }
3100
3101 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003102}
3103
John McCall76bd1f32010-06-01 09:23:16 +00003104Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003105 return DecodeSelector(ID);
3106}
3107
John McCall76bd1f32010-06-01 09:23:16 +00003108uint32_t PCHReader::GetNumExternalSelectors() {
Douglas Gregor719770d2010-04-06 17:30:22 +00003109 return TotalNumSelectors + 1;
3110}
3111
Mike Stump1eb44332009-09-09 15:08:12 +00003112DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00003113PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3114 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3115 switch (Kind) {
3116 case DeclarationName::Identifier:
3117 return DeclarationName(GetIdentifierInfo(Record, Idx));
3118
3119 case DeclarationName::ObjCZeroArgSelector:
3120 case DeclarationName::ObjCOneArgSelector:
3121 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00003122 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003123
3124 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003125 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003126 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003127
3128 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003129 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003130 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003131
3132 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003133 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003134 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003135
3136 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003137 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00003138 (OverloadedOperatorKind)Record[Idx++]);
3139
Sean Hunt3e518bd2009-11-29 07:34:05 +00003140 case DeclarationName::CXXLiteralOperatorName:
3141 return Context->DeclarationNames.getCXXLiteralOperatorName(
3142 GetIdentifierInfo(Record, Idx));
3143
Douglas Gregor2cf26342009-04-09 22:27:44 +00003144 case DeclarationName::CXXUsingDirective:
3145 return DeclarationName::getUsingDirectiveName();
3146 }
3147
3148 // Required to silence GCC warning
3149 return DeclarationName();
3150}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003151
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003152TemplateName
3153PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3154 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3155 switch (Kind) {
3156 case TemplateName::Template:
3157 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3158
3159 case TemplateName::OverloadedTemplate: {
3160 unsigned size = Record[Idx++];
3161 UnresolvedSet<8> Decls;
3162 while (size--)
3163 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3164
3165 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3166 }
3167
3168 case TemplateName::QualifiedTemplate: {
3169 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3170 bool hasTemplKeyword = Record[Idx++];
3171 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3172 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3173 }
3174
3175 case TemplateName::DependentTemplate: {
3176 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3177 if (Record[Idx++]) // isIdentifier
3178 return Context->getDependentTemplateName(NNS,
3179 GetIdentifierInfo(Record, Idx));
3180 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00003181 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003182 }
3183 }
3184
3185 assert(0 && "Unhandled template name kind!");
3186 return TemplateName();
3187}
3188
3189TemplateArgument
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00003190PCHReader::ReadTemplateArgument(const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003191 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3192 case TemplateArgument::Null:
3193 return TemplateArgument();
3194 case TemplateArgument::Type:
3195 return TemplateArgument(GetType(Record[Idx++]));
3196 case TemplateArgument::Declaration:
3197 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00003198 case TemplateArgument::Integral: {
3199 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3200 QualType T = GetType(Record[Idx++]);
3201 return TemplateArgument(Value, T);
3202 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003203 case TemplateArgument::Template:
3204 return TemplateArgument(ReadTemplateName(Record, Idx));
3205 case TemplateArgument::Expression:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00003206 return TemplateArgument(ReadExpr());
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003207 case TemplateArgument::Pack: {
3208 unsigned NumArgs = Record[Idx++];
3209 llvm::SmallVector<TemplateArgument, 8> Args;
3210 Args.reserve(NumArgs);
3211 while (NumArgs--)
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00003212 Args.push_back(ReadTemplateArgument(Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003213 TemplateArgument TemplArg;
3214 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3215 return TemplArg;
3216 }
3217 }
3218
3219 assert(0 && "Unhandled template argument kind!");
3220 return TemplateArgument();
3221}
3222
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003223TemplateParameterList *
3224PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3225 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3226 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3227 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3228
3229 unsigned NumParams = Record[Idx++];
3230 llvm::SmallVector<NamedDecl *, 16> Params;
3231 Params.reserve(NumParams);
3232 while (NumParams--)
3233 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3234
3235 TemplateParameterList* TemplateParams =
3236 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3237 Params.data(), Params.size(), RAngleLoc);
3238 return TemplateParams;
3239}
3240
3241void
3242PCHReader::
3243ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
3244 const RecordData &Record, unsigned &Idx) {
3245 unsigned NumTemplateArgs = Record[Idx++];
3246 TemplArgs.reserve(NumTemplateArgs);
3247 while (NumTemplateArgs--)
3248 TemplArgs.push_back(ReadTemplateArgument(Record, Idx));
3249}
3250
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00003251/// \brief Read a UnresolvedSet structure.
3252void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3253 const RecordData &Record, unsigned &Idx) {
3254 unsigned NumDecls = Record[Idx++];
3255 while (NumDecls--) {
3256 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3257 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3258 Set.addDecl(D, AS);
3259 }
3260}
3261
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003262CXXBaseSpecifier
3263PCHReader::ReadCXXBaseSpecifier(const RecordData &Record, unsigned &Idx) {
3264 bool isVirtual = static_cast<bool>(Record[Idx++]);
3265 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3266 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
3267 QualType T = GetType(Record[Idx++]);
3268 SourceRange Range = ReadSourceRange(Record, Idx);
3269 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, T);
3270}
3271
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003272NestedNameSpecifier *
3273PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3274 unsigned N = Record[Idx++];
3275 NestedNameSpecifier *NNS = 0, *Prev = 0;
3276 for (unsigned I = 0; I != N; ++I) {
3277 NestedNameSpecifier::SpecifierKind Kind
3278 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3279 switch (Kind) {
3280 case NestedNameSpecifier::Identifier: {
3281 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3282 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3283 break;
3284 }
3285
3286 case NestedNameSpecifier::Namespace: {
3287 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3288 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3289 break;
3290 }
3291
3292 case NestedNameSpecifier::TypeSpec:
3293 case NestedNameSpecifier::TypeSpecWithTemplate: {
3294 Type *T = GetType(Record[Idx++]).getTypePtr();
3295 bool Template = Record[Idx++];
3296 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3297 break;
3298 }
3299
3300 case NestedNameSpecifier::Global: {
3301 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3302 // No associated value, and there can't be a prefix.
3303 break;
3304 }
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003305 }
Argyrios Kyrtzidisd2bb2c02010-07-07 15:46:30 +00003306 Prev = NNS;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003307 }
3308 return NNS;
3309}
3310
3311SourceRange
3312PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar8ee59392010-06-02 15:47:10 +00003313 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3314 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3315 return SourceRange(beg, end);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003316}
3317
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00003318/// \brief Read an integral value
3319llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3320 unsigned BitWidth = Record[Idx++];
3321 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3322 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3323 Idx += NumWords;
3324 return Result;
3325}
3326
3327/// \brief Read a signed integral value
3328llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3329 bool isUnsigned = Record[Idx++];
3330 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3331}
3332
Douglas Gregor17fc2232009-04-14 21:55:33 +00003333/// \brief Read a floating-point value
3334llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00003335 return llvm::APFloat(ReadAPInt(Record, Idx));
3336}
3337
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003338// \brief Read a string
3339std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3340 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00003341 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003342 Idx += Len;
3343 return Result;
3344}
3345
Chris Lattnerd2598362010-05-10 00:25:06 +00003346CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3347 unsigned &Idx) {
3348 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3349 return CXXTemporary::Create(*Context, Decl);
3350}
3351
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003352DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00003353 return Diag(SourceLocation(), DiagID);
3354}
3355
3356DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003357 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003358}
Douglas Gregor025452f2009-04-17 00:04:06 +00003359
Douglas Gregor668c1a42009-04-21 22:25:48 +00003360/// \brief Retrieve the identifier table associated with the
3361/// preprocessor.
3362IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003363 assert(PP && "Forgot to set Preprocessor ?");
3364 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00003365}
3366
Douglas Gregor025452f2009-04-17 00:04:06 +00003367/// \brief Record that the given ID maps to the given switch-case
3368/// statement.
3369void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3370 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3371 SwitchCaseStmts[ID] = SC;
3372}
3373
3374/// \brief Retrieve the switch-case statement with the given ID.
3375SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3376 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3377 return SwitchCaseStmts[ID];
3378}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003379
3380/// \brief Record that the given label statement has been
3381/// deserialized and has the given ID.
3382void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00003383 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003384 "Deserialized label twice");
3385 LabelStmts[ID] = S;
3386
3387 // If we've already seen any goto statements that point to this
3388 // label, resolve them now.
3389 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3390 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3391 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3392 Goto->second->setLabel(S);
3393 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003394
3395 // If we've already seen any address-label statements that point to
3396 // this label, resolve them now.
3397 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00003398 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003399 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00003400 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003401 AddrLabel != AddrLabels.second; ++AddrLabel)
3402 AddrLabel->second->setLabel(S);
3403 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003404}
3405
3406/// \brief Set the label of the given statement to the label
3407/// identified by ID.
3408///
3409/// Depending on the order in which the label and other statements
3410/// referencing that label occur, this operation may complete
3411/// immediately (updating the statement) or it may queue the
3412/// statement to be back-patched later.
3413void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3414 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3415 if (Label != LabelStmts.end()) {
3416 // We've already seen this label, so set the label of the goto and
3417 // we're done.
3418 S->setLabel(Label->second);
3419 } else {
3420 // We haven't seen this label yet, so add this goto to the set of
3421 // unresolved goto statements.
3422 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3423 }
3424}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003425
3426/// \brief Set the label of the given expression to the label
3427/// identified by ID.
3428///
3429/// Depending on the order in which the label and other statements
3430/// referencing that label occur, this operation may complete
3431/// immediately (updating the statement) or it may queue the
3432/// statement to be back-patched later.
3433void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3434 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3435 if (Label != LabelStmts.end()) {
3436 // We've already seen this label, so set the label of the
3437 // label-address expression and we're done.
3438 S->setLabel(Label->second);
3439 } else {
3440 // We haven't seen this label yet, so add this label-address
3441 // expression to the set of unresolved label-address expressions.
3442 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3443 }
3444}
Douglas Gregord89275b2009-07-06 18:54:52 +00003445
3446
Mike Stump1eb44332009-09-09 15:08:12 +00003447PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00003448 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
3449 Reader.CurrentlyLoadingTypeOrDecl = this;
3450}
3451
3452PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
3453 if (!Parent) {
3454 // If any identifiers with corresponding top-level declarations have
3455 // been loaded, load those declarations now.
3456 while (!Reader.PendingIdentifierInfos.empty()) {
3457 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
3458 Reader.PendingIdentifierInfos.front().DeclIDs,
3459 true);
3460 Reader.PendingIdentifierInfos.pop_front();
3461 }
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003462
3463 // We are not in recursive loading, so it's safe to pass the "interesting"
3464 // decls to the consumer.
3465 if (Reader.Consumer)
3466 Reader.PassInterestingDeclsToConsumer();
Douglas Gregord89275b2009-07-06 18:54:52 +00003467 }
3468
Mike Stump1eb44332009-09-09 15:08:12 +00003469 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00003470}