blob: e85f58b0e91be411a8a435243259b8498cd51030 [file] [log] [blame]
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner92ba5ff2009-04-27 05:14:47 +000013
Douglas Gregoref84c4b2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor55abb232009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor1a0d0b92009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
Chris Lattner34321bc2009-04-10 21:41:48 +000021#include "clang/Lex/MacroInfo.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000024#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000025#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000029#include "llvm/Bitcode/BitstreamReader.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include <algorithm>
Douglas Gregorc379c072009-04-28 18:58:38 +000033#include <iterator>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000034#include <cstdio>
Douglas Gregorc5046832009-04-27 18:38:38 +000035#include <sys/stat.h>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000039// PCH reader validator implementation
40//===----------------------------------------------------------------------===//
41
42PCHReaderListener::~PCHReaderListener() {}
43
44bool
45PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
46 const LangOptions &PPLangOpts = PP.getLangOptions();
47#define PARSE_LANGOPT_BENIGN(Option)
48#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
49 if (PPLangOpts.Option != LangOpts.Option) { \
50 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
51 return true; \
52 }
53
54 PARSE_LANGOPT_BENIGN(Trigraphs);
55 PARSE_LANGOPT_BENIGN(BCPLComment);
56 PARSE_LANGOPT_BENIGN(DollarIdents);
57 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
58 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
59 PARSE_LANGOPT_BENIGN(ImplicitInt);
60 PARSE_LANGOPT_BENIGN(Digraphs);
61 PARSE_LANGOPT_BENIGN(HexFloats);
62 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
63 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
64 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
65 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
66 PARSE_LANGOPT_BENIGN(CXXOperatorName);
67 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
68 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
69 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
70 PARSE_LANGOPT_BENIGN(PascalStrings);
71 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump11289f42009-09-09 15:08:12 +000072 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000073 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +000074 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000075 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
76 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
77 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
78 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +000079 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000080 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000081 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000082 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
83 PARSE_LANGOPT_BENIGN(EmitAllDecls);
84 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
85 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump11289f42009-09-09 15:08:12 +000086 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000087 diag::warn_pch_heinous_extensions);
88 // FIXME: Most of the options below are benign if the macro wasn't
89 // used. Unfortunately, this means that a PCH compiled without
90 // optimization can't be used with optimization turned on, even
91 // though the only thing that changes is whether __OPTIMIZE__ was
92 // defined... but if __OPTIMIZE__ never showed up in the header, it
93 // doesn't matter. We could consider making this some special kind
94 // of check.
95 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
96 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
97 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
98 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
99 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
100 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
101 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
102 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
103 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000104 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000105 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
106 return true;
107 }
108 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000109 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
110 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000111 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000112 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000113 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000114#undef PARSE_LANGOPT_IRRELEVANT
115#undef PARSE_LANGOPT_BENIGN
116
117 return false;
118}
119
120bool PCHValidator::ReadTargetTriple(const std::string &Triple) {
Daniel Dunbar40165182009-08-24 09:10:05 +0000121 if (Triple != PP.getTargetInfo().getTriple().getTriple()) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000122 Reader.Diag(diag::warn_pch_target_triple)
Daniel Dunbar40165182009-08-24 09:10:05 +0000123 << Triple << PP.getTargetInfo().getTriple().getTriple();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000124 return true;
125 }
126 return false;
127}
128
129/// \brief Split the given string into a vector of lines, eliminating
130/// any empty lines in the process.
131///
132/// \param Str the string to split.
133/// \param Len the length of Str.
134/// \param KeepEmptyLines true if empty lines should be included
135/// \returns a vector of lines, with the line endings removed
136static std::vector<std::string> splitLines(const char *Str, unsigned Len,
137 bool KeepEmptyLines = false) {
138 std::vector<std::string> Lines;
139 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
140 unsigned LineEnd = LineStart;
141 while (LineEnd < Len && Str[LineEnd] != '\n')
142 ++LineEnd;
143 if (LineStart != LineEnd || KeepEmptyLines)
144 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
145 LineStart = LineEnd;
146 }
147 return Lines;
148}
149
150/// \brief Determine whether the string Haystack starts with the
151/// substring Needle.
152static bool startsWith(const std::string &Haystack, const char *Needle) {
153 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
154 if (I == N)
155 return false;
156 if (Haystack[I] != Needle[I])
157 return false;
158 }
159
160 return true;
161}
162
163/// \brief Determine whether the string Haystack starts with the
164/// substring Needle.
165static inline bool startsWith(const std::string &Haystack,
166 const std::string &Needle) {
167 return startsWith(Haystack, Needle.c_str());
168}
169
Mike Stump11289f42009-09-09 15:08:12 +0000170bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000171 unsigned PCHPredefLen,
172 FileID PCHBufferID,
173 std::string &SuggestedPredefines) {
174 const char *Predef = PP.getPredefines().c_str();
175 unsigned PredefLen = PP.getPredefines().size();
176
177 // If the two predefines buffers compare equal, we're done!
Mike Stump11289f42009-09-09 15:08:12 +0000178 if (PredefLen == PCHPredefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000179 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
180 return false;
181
182 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000183
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000184 // The predefines buffers are different. Determine what the
185 // differences are, and whether they require us to reject the PCH
186 // file.
187 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
188 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
189
Mike Stump11289f42009-09-09 15:08:12 +0000190 // Sort both sets of predefined buffer lines, since
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000191 std::sort(CmdLineLines.begin(), CmdLineLines.end());
192 std::sort(PCHLines.begin(), PCHLines.end());
193
194 // Determine which predefines that where used to build the PCH file
195 // are missing from the command line.
196 std::vector<std::string> MissingPredefines;
197 std::set_difference(PCHLines.begin(), PCHLines.end(),
198 CmdLineLines.begin(), CmdLineLines.end(),
199 std::back_inserter(MissingPredefines));
200
201 bool MissingDefines = false;
202 bool ConflictingDefines = false;
203 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
204 const std::string &Missing = MissingPredefines[I];
205 if (!startsWith(Missing, "#define ") != 0) {
206 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
207 return true;
208 }
Mike Stump11289f42009-09-09 15:08:12 +0000209
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000210 // This is a macro definition. Determine the name of the macro
211 // we're defining.
212 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000213 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000214 = Missing.find_first_of("( \n\r", StartOfMacroName);
215 assert(EndOfMacroName != std::string::npos &&
216 "Couldn't find the end of the macro name");
217 std::string MacroName = Missing.substr(StartOfMacroName,
218 EndOfMacroName - StartOfMacroName);
219
220 // Determine whether this macro was given a different definition
221 // on the command line.
222 std::string MacroDefStart = "#define " + MacroName;
223 std::string::size_type MacroDefLen = MacroDefStart.size();
224 std::vector<std::string>::iterator ConflictPos
225 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
226 MacroDefStart);
227 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
228 if (!startsWith(*ConflictPos, MacroDefStart)) {
229 // Different macro; we're done.
230 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000231 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000232 }
Mike Stump11289f42009-09-09 15:08:12 +0000233
234 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000235 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000236 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000237 (*ConflictPos)[MacroDefLen] != '(')
238 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000239
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000240 // We found a conflicting macro definition.
241 break;
242 }
Mike Stump11289f42009-09-09 15:08:12 +0000243
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000244 if (ConflictPos != CmdLineLines.end()) {
245 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
246 << MacroName;
247
248 // Show the definition of this macro within the PCH file.
249 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
250 unsigned Offset = MissingDef - PCHPredef;
251 SourceLocation PCHMissingLoc
252 = SourceMgr.getLocForStartOfFile(PCHBufferID)
253 .getFileLocWithOffset(Offset);
254 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
255 << MacroName;
256
257 ConflictingDefines = true;
258 continue;
259 }
Mike Stump11289f42009-09-09 15:08:12 +0000260
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000261 // If the macro doesn't conflict, then we'll just pick up the
262 // macro definition from the PCH file. Warn the user that they
263 // made a mistake.
264 if (ConflictingDefines)
265 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000266
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000267 if (!MissingDefines) {
268 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
269 MissingDefines = true;
270 }
271
272 // Show the definition of this macro within the PCH file.
273 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
274 unsigned Offset = MissingDef - PCHPredef;
275 SourceLocation PCHMissingLoc
276 = SourceMgr.getLocForStartOfFile(PCHBufferID)
277 .getFileLocWithOffset(Offset);
278 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
279 }
Mike Stump11289f42009-09-09 15:08:12 +0000280
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000281 if (ConflictingDefines)
282 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000283
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000284 // Determine what predefines were introduced based on command-line
285 // parameters that were not present when building the PCH
286 // file. Extra #defines are okay, so long as the identifiers being
287 // defined were not used within the precompiled header.
288 std::vector<std::string> ExtraPredefines;
289 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
290 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000291 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000292 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
293 const std::string &Extra = ExtraPredefines[I];
294 if (!startsWith(Extra, "#define ") != 0) {
295 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
296 return true;
297 }
298
299 // This is an extra macro definition. Determine the name of the
300 // macro we're defining.
301 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000302 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000303 = Extra.find_first_of("( \n\r", StartOfMacroName);
304 assert(EndOfMacroName != std::string::npos &&
305 "Couldn't find the end of the macro name");
306 std::string MacroName = Extra.substr(StartOfMacroName,
307 EndOfMacroName - StartOfMacroName);
308
309 // Check whether this name was used somewhere in the PCH file. If
310 // so, defining it as a macro could change behavior, so we reject
311 // the PCH file.
312 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
313 MacroName.c_str() + MacroName.size())) {
314 Reader.Diag(diag::warn_macro_name_used_in_pch)
315 << II;
316 return true;
317 }
318
319 // Add this definition to the suggested predefines buffer.
320 SuggestedPredefines += Extra;
321 SuggestedPredefines += '\n';
322 }
323
324 // If we get here, it's because the predefines buffer had compatible
325 // contents. Accept the PCH file.
326 return false;
327}
328
329void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
330 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
331}
332
333void PCHValidator::ReadCounter(unsigned Value) {
334 PP.setCounterValue(Value);
335}
336
337
338
339//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000340// PCH reader implementation
341//===----------------------------------------------------------------------===//
342
Mike Stump11289f42009-09-09 15:08:12 +0000343PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
344 const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000345 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
346 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
347 SemaObj(0), PP(&PP), Context(Context), Consumer(0),
348 IdentifierTableData(0), IdentifierLookupTable(0),
349 IdentifierOffsets(0),
350 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
351 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000352 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000353 NumStatHits(0), NumStatMisses(0),
354 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000355 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000356 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000357 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000358 RelocatablePCH = false;
359}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000360
361PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000362 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000363 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Argyrios Kyrtzidise55f6ff2009-06-19 07:55:35 +0000364 SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000365 IdentifierTableData(0), IdentifierLookupTable(0),
366 IdentifierOffsets(0),
367 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
368 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000369 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000370 NumStatHits(0), NumStatMisses(0),
371 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000372 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000373 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000374 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000375 RelocatablePCH = false;
376}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000377
378PCHReader::~PCHReader() {}
379
Chris Lattner1de76db2009-04-27 05:58:23 +0000380Expr *PCHReader::ReadDeclExpr() {
381 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
382}
383
384Expr *PCHReader::ReadTypeExpr() {
Chris Lattnerf4262532009-04-27 05:41:06 +0000385 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000386}
387
388
Douglas Gregora868bbd2009-04-21 22:25:48 +0000389namespace {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000390class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
391 PCHReader &Reader;
392
393public:
394 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
395
396 typedef Selector external_key_type;
397 typedef external_key_type internal_key_type;
398
399 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000400
Douglas Gregorc78d3462009-04-24 21:10:55 +0000401 static bool EqualKey(const internal_key_type& a,
402 const internal_key_type& b) {
403 return a == b;
404 }
Mike Stump11289f42009-09-09 15:08:12 +0000405
Douglas Gregorc78d3462009-04-24 21:10:55 +0000406 static unsigned ComputeHash(Selector Sel) {
407 unsigned N = Sel.getNumArgs();
408 if (N == 0)
409 ++N;
410 unsigned R = 5381;
411 for (unsigned I = 0; I != N; ++I)
412 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
413 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
414 return R;
415 }
Mike Stump11289f42009-09-09 15:08:12 +0000416
Douglas Gregorc78d3462009-04-24 21:10:55 +0000417 // This hopefully will just get inlined and removed by the optimizer.
418 static const internal_key_type&
419 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000420
Douglas Gregorc78d3462009-04-24 21:10:55 +0000421 static std::pair<unsigned, unsigned>
422 ReadKeyDataLength(const unsigned char*& d) {
423 using namespace clang::io;
424 unsigned KeyLen = ReadUnalignedLE16(d);
425 unsigned DataLen = ReadUnalignedLE16(d);
426 return std::make_pair(KeyLen, DataLen);
427 }
Mike Stump11289f42009-09-09 15:08:12 +0000428
Douglas Gregor95c13f52009-04-25 17:48:32 +0000429 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000430 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000431 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000432 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000433 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000434 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
435 if (N == 0)
436 return SelTable.getNullarySelector(FirstII);
437 else if (N == 1)
438 return SelTable.getUnarySelector(FirstII);
439
440 llvm::SmallVector<IdentifierInfo *, 16> Args;
441 Args.push_back(FirstII);
442 for (unsigned I = 1; I != N; ++I)
443 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
444
Douglas Gregor038c3382009-05-22 22:45:36 +0000445 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000446 }
Mike Stump11289f42009-09-09 15:08:12 +0000447
Douglas Gregorc78d3462009-04-24 21:10:55 +0000448 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
449 using namespace clang::io;
450 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
451 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
452
453 data_type Result;
454
455 // Load instance methods
456 ObjCMethodList *Prev = 0;
457 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000458 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000459 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
460 if (!Result.first.Method) {
461 // This is the first method, which is the easy case.
462 Result.first.Method = Method;
463 Prev = &Result.first;
464 continue;
465 }
466
467 Prev->Next = new ObjCMethodList(Method, 0);
468 Prev = Prev->Next;
469 }
470
471 // Load factory methods
472 Prev = 0;
473 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000474 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000475 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
476 if (!Result.second.Method) {
477 // This is the first method, which is the easy case.
478 Result.second.Method = Method;
479 Prev = &Result.second;
480 continue;
481 }
482
483 Prev->Next = new ObjCMethodList(Method, 0);
484 Prev = Prev->Next;
485 }
486
487 return Result;
488 }
489};
Mike Stump11289f42009-09-09 15:08:12 +0000490
491} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000492
493/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000494typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000495 PCHMethodPoolLookupTable;
496
497namespace {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000498class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
499 PCHReader &Reader;
500
501 // If we know the IdentifierInfo in advance, it is here and we will
502 // not build a new one. Used when deserializing information about an
503 // identifier that was constructed before the PCH file was read.
504 IdentifierInfo *KnownII;
505
506public:
507 typedef IdentifierInfo * data_type;
508
509 typedef const std::pair<const char*, unsigned> external_key_type;
510
511 typedef external_key_type internal_key_type;
512
Mike Stump11289f42009-09-09 15:08:12 +0000513 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregora868bbd2009-04-21 22:25:48 +0000514 : Reader(Reader), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000515
Douglas Gregora868bbd2009-04-21 22:25:48 +0000516 static bool EqualKey(const internal_key_type& a,
517 const internal_key_type& b) {
518 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
519 : false;
520 }
Mike Stump11289f42009-09-09 15:08:12 +0000521
Douglas Gregora868bbd2009-04-21 22:25:48 +0000522 static unsigned ComputeHash(const internal_key_type& a) {
523 return BernsteinHash(a.first, a.second);
524 }
Mike Stump11289f42009-09-09 15:08:12 +0000525
Douglas Gregora868bbd2009-04-21 22:25:48 +0000526 // This hopefully will just get inlined and removed by the optimizer.
527 static const internal_key_type&
528 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000529
Douglas Gregora868bbd2009-04-21 22:25:48 +0000530 static std::pair<unsigned, unsigned>
531 ReadKeyDataLength(const unsigned char*& d) {
532 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000533 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000534 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000535 return std::make_pair(KeyLen, DataLen);
536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Douglas Gregora868bbd2009-04-21 22:25:48 +0000538 static std::pair<const char*, unsigned>
539 ReadKey(const unsigned char* d, unsigned n) {
540 assert(n >= 2 && d[n-1] == '\0');
541 return std::make_pair((const char*) d, n-1);
542 }
Mike Stump11289f42009-09-09 15:08:12 +0000543
544 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000545 const unsigned char* d,
546 unsigned DataLen) {
547 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000548 pch::IdentID ID = ReadUnalignedLE32(d);
549 bool IsInteresting = ID & 0x01;
550
551 // Wipe out the "is interesting" bit.
552 ID = ID >> 1;
553
554 if (!IsInteresting) {
555 // For unintersting identifiers, just build the IdentifierInfo
556 // and associate it with the persistent ID.
557 IdentifierInfo *II = KnownII;
558 if (!II)
559 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
560 k.first, k.first + k.second);
561 Reader.SetIdentifierInfo(ID, II);
562 return II;
563 }
564
Douglas Gregorb9256522009-04-28 21:32:13 +0000565 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000566 bool CPlusPlusOperatorKeyword = Bits & 0x01;
567 Bits >>= 1;
568 bool Poisoned = Bits & 0x01;
569 Bits >>= 1;
570 bool ExtensionToken = Bits & 0x01;
571 Bits >>= 1;
572 bool hasMacroDefinition = Bits & 0x01;
573 Bits >>= 1;
574 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
575 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000576
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000577 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000578 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000579
580 // Build the IdentifierInfo itself and link the identifier ID with
581 // the new IdentifierInfo.
582 IdentifierInfo *II = KnownII;
583 if (!II)
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000584 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
585 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000586 Reader.SetIdentifierInfo(ID, II);
587
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000588 // Set or check the various bits in the IdentifierInfo structure.
589 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000590 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000591 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000592 "Incorrect extension token flag");
593 (void)ExtensionToken;
594 II->setIsPoisoned(Poisoned);
595 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
596 "Incorrect C++ operator keyword flag");
597 (void)CPlusPlusOperatorKeyword;
598
Douglas Gregorc3366a52009-04-21 23:56:24 +0000599 // If this identifier is a macro, deserialize the macro
600 // definition.
601 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000602 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregorc3366a52009-04-21 23:56:24 +0000603 Reader.ReadMacroRecord(Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000604 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000605 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000606
607 // Read all of the declarations visible at global scope with this
608 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000609 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000610 if (DataLen > 0) {
611 llvm::SmallVector<uint32_t, 4> DeclIDs;
612 for (; DataLen > 0; DataLen -= 4)
613 DeclIDs.push_back(ReadUnalignedLE32(d));
614 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000615 }
Mike Stump11289f42009-09-09 15:08:12 +0000616
Douglas Gregora868bbd2009-04-21 22:25:48 +0000617 return II;
618 }
619};
Mike Stump11289f42009-09-09 15:08:12 +0000620
621} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000622
623/// \brief The on-disk hash table used to contain information about
624/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000625typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000626 PCHIdentifierLookupTable;
627
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000628bool PCHReader::Error(const char *Msg) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000629 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
630 Diag(DiagID);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000631 return true;
632}
633
Douglas Gregor92863e42009-04-10 23:10:45 +0000634/// \brief Check the contents of the predefines buffer against the
635/// contents of the predefines buffer used to build the PCH file.
636///
637/// The contents of the two predefines buffers should be the same. If
638/// not, then some command-line option changed the preprocessor state
639/// and we must reject the PCH file.
640///
641/// \param PCHPredef The start of the predefines buffer in the PCH
642/// file.
643///
644/// \param PCHPredefLen The length of the predefines buffer in the PCH
645/// file.
646///
647/// \param PCHBufferID The FileID for the PCH predefines buffer.
648///
649/// \returns true if there was a mismatch (in which case the PCH file
650/// should be ignored), or false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +0000651bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
Douglas Gregor92863e42009-04-10 23:10:45 +0000652 unsigned PCHPredefLen,
653 FileID PCHBufferID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000654 if (Listener)
655 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
656 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000657 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000658}
659
Douglas Gregorc5046832009-04-27 18:38:38 +0000660//===----------------------------------------------------------------------===//
661// Source Manager Deserialization
662//===----------------------------------------------------------------------===//
663
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000664/// \brief Read the line table in the source manager block.
665/// \returns true if ther was an error.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000666bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000667 unsigned Idx = 0;
668 LineTableInfo &LineTable = SourceMgr.getLineTable();
669
670 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000671 std::map<int, int> FileIDs;
672 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000673 // Extract the file name
674 unsigned FilenameLen = Record[Idx++];
675 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
676 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000677 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000678 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000679 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000680 }
681
682 // Parse the line entries
683 std::vector<LineEntry> Entries;
684 while (Idx < Record.size()) {
Douglas Gregora8854652009-04-13 17:12:42 +0000685 int FID = FileIDs[Record[Idx++]];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000686
687 // Extract the line entries
688 unsigned NumEntries = Record[Idx++];
689 Entries.clear();
690 Entries.reserve(NumEntries);
691 for (unsigned I = 0; I != NumEntries; ++I) {
692 unsigned FileOffset = Record[Idx++];
693 unsigned LineNo = Record[Idx++];
694 int FilenameID = Record[Idx++];
Mike Stump11289f42009-09-09 15:08:12 +0000695 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000696 = (SrcMgr::CharacteristicKind)Record[Idx++];
697 unsigned IncludeOffset = Record[Idx++];
698 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
699 FileKind, IncludeOffset));
700 }
701 LineTable.AddEntry(FID, Entries);
702 }
703
704 return false;
705}
706
Douglas Gregorc5046832009-04-27 18:38:38 +0000707namespace {
708
709class VISIBILITY_HIDDEN PCHStatData {
710public:
711 const bool hasStat;
712 const ino_t ino;
713 const dev_t dev;
714 const mode_t mode;
715 const time_t mtime;
716 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000717
Douglas Gregorc5046832009-04-27 18:38:38 +0000718 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000719 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
720
Douglas Gregorc5046832009-04-27 18:38:38 +0000721 PCHStatData()
722 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
723};
724
725class VISIBILITY_HIDDEN PCHStatLookupTrait {
726 public:
727 typedef const char *external_key_type;
728 typedef const char *internal_key_type;
729
730 typedef PCHStatData data_type;
731
732 static unsigned ComputeHash(const char *path) {
733 return BernsteinHash(path);
734 }
735
736 static internal_key_type GetInternalKey(const char *path) { return path; }
737
738 static bool EqualKey(internal_key_type a, internal_key_type b) {
739 return strcmp(a, b) == 0;
740 }
741
742 static std::pair<unsigned, unsigned>
743 ReadKeyDataLength(const unsigned char*& d) {
744 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
745 unsigned DataLen = (unsigned) *d++;
746 return std::make_pair(KeyLen + 1, DataLen);
747 }
748
749 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
750 return (const char *)d;
751 }
752
753 static data_type ReadData(const internal_key_type, const unsigned char *d,
754 unsigned /*DataLen*/) {
755 using namespace clang::io;
756
757 if (*d++ == 1)
758 return data_type();
759
760 ino_t ino = (ino_t) ReadUnalignedLE32(d);
761 dev_t dev = (dev_t) ReadUnalignedLE32(d);
762 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000763 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000764 off_t size = (off_t) ReadUnalignedLE64(d);
765 return data_type(ino, dev, mode, mtime, size);
766 }
767};
768
769/// \brief stat() cache for precompiled headers.
770///
771/// This cache is very similar to the stat cache used by pretokenized
772/// headers.
773class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
774 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
775 CacheTy *Cache;
776
777 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000778public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000779 PCHStatCache(const unsigned char *Buckets,
780 const unsigned char *Base,
781 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000782 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000783 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
784 Cache = CacheTy::Create(Buckets, Base);
785 }
786
787 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000788
Douglas Gregorc5046832009-04-27 18:38:38 +0000789 int stat(const char *path, struct stat *buf) {
790 // Do the lookup for the file's data in the PCH file.
791 CacheTy::iterator I = Cache->find(path);
792
793 // If we don't get a hit in the PCH file just forward to 'stat'.
794 if (I == Cache->end()) {
795 ++NumStatMisses;
796 return ::stat(path, buf);
797 }
Mike Stump11289f42009-09-09 15:08:12 +0000798
Douglas Gregorc5046832009-04-27 18:38:38 +0000799 ++NumStatHits;
800 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000801
Douglas Gregorc5046832009-04-27 18:38:38 +0000802 if (!Data.hasStat)
803 return 1;
804
805 buf->st_ino = Data.ino;
806 buf->st_dev = Data.dev;
807 buf->st_mtime = Data.mtime;
808 buf->st_mode = Data.mode;
809 buf->st_size = Data.size;
810 return 0;
811 }
812};
813} // end anonymous namespace
814
815
Douglas Gregora7f71a92009-04-10 03:52:48 +0000816/// \brief Read the source manager block
Douglas Gregor92863e42009-04-10 23:10:45 +0000817PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000818 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000819
820 // Set the source-location entry cursor to the current position in
821 // the stream. This cursor will be used to read the contents of the
822 // source manager block initially, and then lazily read
823 // source-location entries as needed.
824 SLocEntryCursor = Stream;
825
826 // The stream itself is going to skip over the source manager block.
827 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000828 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000829 return Failure;
830 }
831
832 // Enter the source manager block.
833 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000834 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000835 return Failure;
836 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000837
Douglas Gregora7f71a92009-04-10 03:52:48 +0000838 RecordData Record;
839 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000840 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000841 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000842 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000843 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000844 return Failure;
845 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000846 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000847 }
Mike Stump11289f42009-09-09 15:08:12 +0000848
Douglas Gregora7f71a92009-04-10 03:52:48 +0000849 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
850 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000851 SLocEntryCursor.ReadSubBlockID();
852 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000853 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000854 return Failure;
855 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000856 continue;
857 }
Mike Stump11289f42009-09-09 15:08:12 +0000858
Douglas Gregora7f71a92009-04-10 03:52:48 +0000859 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000860 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000861 continue;
862 }
Mike Stump11289f42009-09-09 15:08:12 +0000863
Douglas Gregora7f71a92009-04-10 03:52:48 +0000864 // Read a record.
865 const char *BlobStart;
866 unsigned BlobLen;
867 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000868 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000869 default: // Default behavior: ignore.
870 break;
871
Chris Lattner184e65d2009-04-14 23:22:57 +0000872 case pch::SM_LINE_TABLE:
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000873 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000874 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000875 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000876
877 case pch::SM_HEADER_FILE_INFO: {
878 HeaderFileInfo HFI;
879 HFI.isImport = Record[0];
880 HFI.DirInfo = Record[1];
881 HFI.NumIncludes = Record[2];
882 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000883 if (Listener)
884 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregoreda6a892009-04-26 00:07:37 +0000885 break;
886 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000887
888 case pch::SM_SLOC_FILE_ENTRY:
889 case pch::SM_SLOC_BUFFER_ENTRY:
890 case pch::SM_SLOC_INSTANTIATION_ENTRY:
891 // Once we hit one of the source location entries, we're done.
892 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000893 }
894 }
895}
896
Douglas Gregor258ae542009-04-27 06:38:32 +0000897/// \brief Read in the source location entry with the given ID.
898PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
899 if (ID == 0)
900 return Success;
901
902 if (ID > TotalNumSLocEntries) {
903 Error("source location entry ID out-of-range for PCH file");
904 return Failure;
905 }
906
907 ++NumSLocEntriesRead;
908 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
909 unsigned Code = SLocEntryCursor.ReadCode();
910 if (Code == llvm::bitc::END_BLOCK ||
911 Code == llvm::bitc::ENTER_SUBBLOCK ||
912 Code == llvm::bitc::DEFINE_ABBREV) {
913 Error("incorrectly-formatted source location entry in PCH file");
914 return Failure;
915 }
916
Douglas Gregor258ae542009-04-27 06:38:32 +0000917 RecordData Record;
918 const char *BlobStart;
919 unsigned BlobLen;
920 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
921 default:
922 Error("incorrectly-formatted source location entry in PCH file");
923 return Failure;
924
925 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000926 std::string Filename(BlobStart, BlobStart + BlobLen);
927 MaybeAddSystemRootToFilename(Filename);
928 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000929 if (File == 0) {
930 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000931 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000932 ErrorStr += "' referenced by PCH file";
933 Error(ErrorStr.c_str());
934 return Failure;
935 }
Mike Stump11289f42009-09-09 15:08:12 +0000936
Douglas Gregor258ae542009-04-27 06:38:32 +0000937 FileID FID = SourceMgr.createFileID(File,
938 SourceLocation::getFromRawEncoding(Record[1]),
939 (SrcMgr::CharacteristicKind)Record[2],
940 ID, Record[0]);
941 if (Record[3])
942 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
943 .setHasLineDirectives();
944
945 break;
946 }
947
948 case pch::SM_SLOC_BUFFER_ENTRY: {
949 const char *Name = BlobStart;
950 unsigned Offset = Record[0];
951 unsigned Code = SLocEntryCursor.ReadCode();
952 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000953 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +0000954 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
955 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
956 (void)RecCode;
957 llvm::MemoryBuffer *Buffer
Mike Stump11289f42009-09-09 15:08:12 +0000958 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor258ae542009-04-27 06:38:32 +0000959 BlobStart + BlobLen - 1,
960 Name);
961 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000962
Douglas Gregore6648fb2009-04-28 20:33:11 +0000963 if (strcmp(Name, "<built-in>") == 0) {
964 PCHPredefinesBufferID = BufferID;
965 PCHPredefines = BlobStart;
966 PCHPredefinesLen = BlobLen - 1;
967 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000968
969 break;
970 }
971
972 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +0000973 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +0000974 = SourceLocation::getFromRawEncoding(Record[1]);
975 SourceMgr.createInstantiationLoc(SpellingLoc,
976 SourceLocation::getFromRawEncoding(Record[2]),
977 SourceLocation::getFromRawEncoding(Record[3]),
978 Record[4],
979 ID,
980 Record[0]);
981 break;
Mike Stump11289f42009-09-09 15:08:12 +0000982 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000983 }
984
985 return Success;
986}
987
Chris Lattnere78a6be2009-04-27 01:05:14 +0000988/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
989/// specified cursor. Read the abbreviations that are at the top of the block
990/// and then leave the cursor pointing into the block.
991bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
992 unsigned BlockID) {
993 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000994 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +0000995 return Failure;
996 }
Mike Stump11289f42009-09-09 15:08:12 +0000997
Chris Lattnere78a6be2009-04-27 01:05:14 +0000998 while (true) {
999 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001000
Chris Lattnere78a6be2009-04-27 01:05:14 +00001001 // We expect all abbrevs to be at the start of the block.
1002 if (Code != llvm::bitc::DEFINE_ABBREV)
1003 return false;
1004 Cursor.ReadAbbrevRecord();
1005 }
1006}
1007
Douglas Gregorc3366a52009-04-21 23:56:24 +00001008void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001009 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +00001010
Douglas Gregorc3366a52009-04-21 23:56:24 +00001011 // Keep track of where we are in the stream, then jump back there
1012 // after reading this macro.
1013 SavedStreamPosition SavedPosition(Stream);
1014
1015 Stream.JumpToBit(Offset);
1016 RecordData Record;
1017 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1018 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001019
Douglas Gregorc3366a52009-04-21 23:56:24 +00001020 while (true) {
1021 unsigned Code = Stream.ReadCode();
1022 switch (Code) {
1023 case llvm::bitc::END_BLOCK:
1024 return;
1025
1026 case llvm::bitc::ENTER_SUBBLOCK:
1027 // No known subblocks, always skip them.
1028 Stream.ReadSubBlockID();
1029 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001030 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001031 return;
1032 }
1033 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001034
Douglas Gregorc3366a52009-04-21 23:56:24 +00001035 case llvm::bitc::DEFINE_ABBREV:
1036 Stream.ReadAbbrevRecord();
1037 continue;
1038 default: break;
1039 }
1040
1041 // Read a record.
1042 Record.clear();
1043 pch::PreprocessorRecordTypes RecType =
1044 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1045 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001046 case pch::PP_MACRO_OBJECT_LIKE:
1047 case pch::PP_MACRO_FUNCTION_LIKE: {
1048 // If we already have a macro, that means that we've hit the end
1049 // of the definition of the macro we were looking for. We're
1050 // done.
1051 if (Macro)
1052 return;
1053
1054 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1055 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001056 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001057 return;
1058 }
1059 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1060 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001061
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001062 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001063 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregorc3366a52009-04-21 23:56:24 +00001065 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1066 // Decode function-like macro info.
1067 bool isC99VarArgs = Record[3];
1068 bool isGNUVarArgs = Record[4];
1069 MacroArgs.clear();
1070 unsigned NumArgs = Record[5];
1071 for (unsigned i = 0; i != NumArgs; ++i)
1072 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1073
1074 // Install function-like macro info.
1075 MI->setIsFunctionLike();
1076 if (isC99VarArgs) MI->setIsC99Varargs();
1077 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001078 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001079 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001080 }
1081
1082 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001083 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001084
1085 // Remember that we saw this macro last so that we add the tokens that
1086 // form its body to it.
1087 Macro = MI;
1088 ++NumMacrosRead;
1089 break;
1090 }
Mike Stump11289f42009-09-09 15:08:12 +00001091
Douglas Gregorc3366a52009-04-21 23:56:24 +00001092 case pch::PP_TOKEN: {
1093 // If we see a TOKEN before a PP_MACRO_*, then the file is
1094 // erroneous, just pretend we didn't see this.
1095 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001096
Douglas Gregorc3366a52009-04-21 23:56:24 +00001097 Token Tok;
1098 Tok.startToken();
1099 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1100 Tok.setLength(Record[1]);
1101 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1102 Tok.setIdentifierInfo(II);
1103 Tok.setKind((tok::TokenKind)Record[3]);
1104 Tok.setFlag((Token::TokenFlags)Record[4]);
1105 Macro->AddTokenToBody(Tok);
1106 break;
1107 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001108 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001109 }
1110}
1111
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001112/// \brief If we are loading a relocatable PCH file, and the filename is
1113/// not an absolute path, add the system root to the beginning of the file
1114/// name.
1115void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1116 // If this is not a relocatable PCH file, there's nothing to do.
1117 if (!RelocatablePCH)
1118 return;
Mike Stump11289f42009-09-09 15:08:12 +00001119
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001120 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1121 return;
1122
1123 std::string FIXME = Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001124
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001125 if (isysroot == 0) {
1126 // If no system root was given, default to '/'
1127 Filename.insert(Filename.begin(), '/');
1128 return;
1129 }
Mike Stump11289f42009-09-09 15:08:12 +00001130
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001131 unsigned Length = strlen(isysroot);
1132 if (isysroot[Length - 1] != '/')
1133 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001134
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001135 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1136}
1137
Mike Stump11289f42009-09-09 15:08:12 +00001138PCHReader::PCHReadResult
Douglas Gregoreda6a892009-04-26 00:07:37 +00001139PCHReader::ReadPCHBlock() {
Douglas Gregor55abb232009-04-10 20:39:37 +00001140 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001141 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001142 return Failure;
1143 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001144
1145 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001146 RecordData Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001147 while (!Stream.AtEndOfStream()) {
1148 unsigned Code = Stream.ReadCode();
1149 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001150 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001151 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001152 return Failure;
1153 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001154
Douglas Gregor55abb232009-04-10 20:39:37 +00001155 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001156 }
1157
1158 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1159 switch (Stream.ReadSubBlockID()) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001160 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1161 default: // Skip unknown content.
Douglas Gregor55abb232009-04-10 20:39:37 +00001162 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001163 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001164 return Failure;
1165 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001166 break;
1167
Chris Lattnere78a6be2009-04-27 01:05:14 +00001168 case pch::DECLS_BLOCK_ID:
1169 // We lazily load the decls block, but we want to set up the
1170 // DeclsCursor cursor to point into it. Clone our current bitcode
1171 // cursor to it, enter the block and read the abbrevs in that block.
1172 // With the main cursor, we just skip over it.
1173 DeclsCursor = Stream;
1174 if (Stream.SkipBlock() || // Skip with the main cursor.
1175 // Read the abbrevs.
1176 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001177 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001178 return Failure;
1179 }
1180 break;
Mike Stump11289f42009-09-09 15:08:12 +00001181
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001182 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001183 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001184 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001185 return Failure;
1186 }
1187 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001188
Douglas Gregora7f71a92009-04-10 03:52:48 +00001189 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001190 switch (ReadSourceManagerBlock()) {
1191 case Success:
1192 break;
1193
1194 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001195 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001196 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001197
1198 case IgnorePCH:
1199 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001200 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001201 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001202 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001203 continue;
1204 }
1205
1206 if (Code == llvm::bitc::DEFINE_ABBREV) {
1207 Stream.ReadAbbrevRecord();
1208 continue;
1209 }
1210
1211 // Read and process a record.
1212 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001213 const char *BlobStart = 0;
1214 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001215 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001216 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001217 default: // Default behavior: ignore.
1218 break;
1219
1220 case pch::TYPE_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001221 if (!TypesLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001222 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001223 return Failure;
1224 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001225 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001226 TypesLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001227 break;
1228
1229 case pch::DECL_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001230 if (!DeclsLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001231 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001232 return Failure;
1233 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001234 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001235 DeclsLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001236 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001237
1238 case pch::LANGUAGE_OPTIONS:
1239 if (ParseLanguageOptions(Record))
1240 return IgnorePCH;
1241 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001242
Douglas Gregor7b71e632009-04-27 22:23:34 +00001243 case pch::METADATA: {
1244 if (Record[0] != pch::VERSION_MAJOR) {
1245 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1246 : diag::warn_pch_version_too_new);
1247 return IgnorePCH;
1248 }
1249
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001250 RelocatablePCH = Record[4];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001251 if (Listener) {
1252 std::string TargetTriple(BlobStart, BlobLen);
1253 if (Listener->ReadTargetTriple(TargetTriple))
1254 return IgnorePCH;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001255 }
1256 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001257 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001258
1259 case pch::IDENTIFIER_TABLE:
Douglas Gregora868bbd2009-04-21 22:25:48 +00001260 IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001261 if (Record[0]) {
Mike Stump11289f42009-09-09 15:08:12 +00001262 IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001263 = PCHIdentifierLookupTable::Create(
Douglas Gregora868bbd2009-04-21 22:25:48 +00001264 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001265 (const unsigned char *)IdentifierTableData,
Douglas Gregora868bbd2009-04-21 22:25:48 +00001266 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001267 if (PP)
1268 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001269 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001270 break;
1271
1272 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001273 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001274 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001275 return Failure;
1276 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001277 IdentifierOffsets = (const uint32_t *)BlobStart;
1278 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001279 if (PP)
1280 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001281 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001282
1283 case pch::EXTERNAL_DEFINITIONS:
1284 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001285 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001286 return Failure;
1287 }
1288 ExternalDefinitions.swap(Record);
1289 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001290
Douglas Gregor652d82a2009-04-18 05:55:16 +00001291 case pch::SPECIAL_TYPES:
1292 SpecialTypes.swap(Record);
1293 break;
1294
Douglas Gregor08f01292009-04-17 22:13:46 +00001295 case pch::STATISTICS:
1296 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001297 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001298 TotalLexicalDeclContexts = Record[2];
1299 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001300 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001301
Douglas Gregord4df8652009-04-22 22:02:47 +00001302 case pch::TENTATIVE_DEFINITIONS:
1303 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001304 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001305 return Failure;
1306 }
1307 TentativeDefinitions.swap(Record);
1308 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001309
1310 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1311 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001312 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001313 return Failure;
1314 }
1315 LocallyScopedExternalDecls.swap(Record);
1316 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001317
Douglas Gregor95c13f52009-04-25 17:48:32 +00001318 case pch::SELECTOR_OFFSETS:
1319 SelectorOffsets = (const uint32_t *)BlobStart;
1320 TotalNumSelectors = Record[0];
1321 SelectorsLoaded.resize(TotalNumSelectors);
1322 break;
1323
Douglas Gregorc78d3462009-04-24 21:10:55 +00001324 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001325 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1326 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001327 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001328 = PCHMethodPoolLookupTable::Create(
1329 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001330 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001331 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001332 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001333 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001334
1335 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001336 if (!Record.empty() && Listener)
1337 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001338 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001339
1340 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001341 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001342 TotalNumSLocEntries = Record[0];
Mike Stump11289f42009-09-09 15:08:12 +00001343 SourceMgr.PreallocateSLocEntries(this,
1344 TotalNumSLocEntries,
Douglas Gregor258ae542009-04-27 06:38:32 +00001345 Record[1]);
1346 break;
1347
1348 case pch::SOURCE_LOCATION_PRELOADS:
1349 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1350 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1351 if (Result != Success)
1352 return Result;
1353 }
1354 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001355
1356 case pch::STAT_CACHE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001357 FileMgr.setStatCache(
Douglas Gregorc5046832009-04-27 18:38:38 +00001358 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1359 (const unsigned char *)BlobStart,
1360 NumStatHits, NumStatMisses));
1361 break;
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001362
1363 case pch::EXT_VECTOR_DECLS:
1364 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001365 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001366 return Failure;
1367 }
1368 ExtVectorDecls.swap(Record);
1369 break;
1370
Douglas Gregor45fe0362009-05-12 01:31:05 +00001371 case pch::ORIGINAL_FILE_NAME:
1372 OriginalFileName.assign(BlobStart, BlobLen);
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001373 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001374 break;
Mike Stump11289f42009-09-09 15:08:12 +00001375
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001376 case pch::COMMENT_RANGES:
1377 Comments = (SourceRange *)BlobStart;
1378 NumComments = BlobLen / sizeof(SourceRange);
1379 break;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001380 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001381 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001382 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001383 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001384}
1385
Douglas Gregor92863e42009-04-10 23:10:45 +00001386PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001387 // Set the PCH file name.
1388 this->FileName = FileName;
1389
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001390 // Open the PCH file.
1391 std::string ErrStr;
1392 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregor92863e42009-04-10 23:10:45 +00001393 if (!Buffer) {
1394 Error(ErrStr.c_str());
1395 return IgnorePCH;
1396 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001397
1398 // Initialize the stream
Mike Stump11289f42009-09-09 15:08:12 +00001399 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattner9356ace2009-04-26 20:59:20 +00001400 (const unsigned char *)Buffer->getBufferEnd());
1401 Stream.init(StreamFile);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001402
1403 // Sniff for the signature.
1404 if (Stream.Read(8) != 'C' ||
1405 Stream.Read(8) != 'P' ||
1406 Stream.Read(8) != 'C' ||
Douglas Gregor92863e42009-04-10 23:10:45 +00001407 Stream.Read(8) != 'H') {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001408 Diag(diag::err_not_a_pch_file) << FileName;
1409 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001410 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001411
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001412 while (!Stream.AtEndOfStream()) {
1413 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001414
Douglas Gregor92863e42009-04-10 23:10:45 +00001415 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001416 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001417 return Failure;
1418 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001419
1420 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001421
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001422 // We only know the PCH subblock ID.
1423 switch (BlockID) {
1424 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001425 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001426 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001427 return Failure;
1428 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001429 break;
1430 case pch::PCH_BLOCK_ID:
Douglas Gregoreda6a892009-04-26 00:07:37 +00001431 switch (ReadPCHBlock()) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001432 case Success:
1433 break;
1434
1435 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001436 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001437
1438 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001439 // FIXME: We could consider reading through to the end of this
1440 // PCH block, skipping subblocks, to see if there are other
1441 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001442
1443 // Clear out any preallocated source location entries, so that
1444 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001445 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001446
1447 // Remove the stat cache.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001448 FileMgr.setStatCache(0);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001449
Douglas Gregor92863e42009-04-10 23:10:45 +00001450 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001451 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001452 break;
1453 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001454 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001455 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001456 return Failure;
1457 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001458 break;
1459 }
Mike Stump11289f42009-09-09 15:08:12 +00001460 }
1461
Douglas Gregore6648fb2009-04-28 20:33:11 +00001462 // Check the predefines buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001463 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
Douglas Gregore6648fb2009-04-28 20:33:11 +00001464 PCHPredefinesBufferID))
1465 return IgnorePCH;
Mike Stump11289f42009-09-09 15:08:12 +00001466
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001467 if (PP) {
Zhongxing Xu3f51f412009-07-18 09:26:51 +00001468 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001469 // PCH file is read, so there may be some identifiers that were
1470 // loaded into the IdentifierTable before we intercepted the
1471 // creation of identifiers. Iterate through the list of known
1472 // identifiers and determine whether we have to establish
1473 // preprocessor definitions or top-level identifier declaration
1474 // chains for those identifiers.
1475 //
1476 // We copy the IdentifierInfo pointers to a small vector first,
1477 // since de-serializing declarations or macro definitions can add
1478 // new entries into the identifier table, invalidating the
1479 // iterators.
1480 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1481 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1482 IdEnd = PP->getIdentifierTable().end();
1483 Id != IdEnd; ++Id)
1484 Identifiers.push_back(Id->second);
Mike Stump11289f42009-09-09 15:08:12 +00001485 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001486 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1487 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1488 IdentifierInfo *II = Identifiers[I];
1489 // Look in the on-disk hash table for an entry for
1490 PCHIdentifierLookupTrait Info(*this, II);
1491 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1492 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1493 if (Pos == IdTable->end())
1494 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001495
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001496 // Dereferencing the iterator has the effect of populating the
1497 // IdentifierInfo node with the various declarations it needs.
1498 (void)*Pos;
1499 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001500 }
1501
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001502 if (Context)
1503 InitializeContext(*Context);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001504
Douglas Gregora868bbd2009-04-21 22:25:48 +00001505 return Success;
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001506}
1507
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001508void PCHReader::InitializeContext(ASTContext &Ctx) {
1509 Context = &Ctx;
1510 assert(Context && "Passed null context!");
1511
1512 assert(PP && "Forgot to set Preprocessor ?");
1513 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1514 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump11289f42009-09-09 15:08:12 +00001515
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001516 // Load the translation unit declaration
1517 ReadDeclRecord(DeclOffsets[0], 0);
1518
1519 // Load the special types.
1520 Context->setBuiltinVaListType(
1521 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1522 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1523 Context->setObjCIdType(GetType(Id));
1524 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1525 Context->setObjCSelType(GetType(Sel));
1526 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1527 Context->setObjCProtoType(GetType(Proto));
1528 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1529 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001530
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001531 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1532 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001533 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001534 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1535 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001536 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1537 QualType FileType = GetType(File);
1538 assert(!FileType.isNull() && "FILE type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001539 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001540 Context->setFILEDecl(Typedef->getDecl());
1541 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001542 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregor27821ce2009-07-07 16:35:42 +00001543 assert(Tag && "Invalid FILE type in PCH file");
1544 Context->setFILEDecl(Tag->getDecl());
1545 }
1546 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001547 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1548 QualType Jmp_bufType = GetType(Jmp_buf);
1549 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001550 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001551 Context->setjmp_bufDecl(Typedef->getDecl());
1552 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001553 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001554 assert(Tag && "Invalid jmp_bug type in PCH file");
1555 Context->setjmp_bufDecl(Tag->getDecl());
1556 }
1557 }
1558 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1559 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1560 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001561 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001562 Context->setsigjmp_bufDecl(Typedef->getDecl());
1563 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001564 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001565 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1566 Context->setsigjmp_bufDecl(Tag->getDecl());
1567 }
1568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001570 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1571 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001572 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001573 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1574 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001575}
1576
Douglas Gregor45fe0362009-05-12 01:31:05 +00001577/// \brief Retrieve the name of the original source file name
1578/// directly from the PCH file, without actually loading the PCH
1579/// file.
1580std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1581 // Open the PCH file.
1582 std::string ErrStr;
1583 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1584 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1585 if (!Buffer) {
1586 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1587 return std::string();
1588 }
1589
1590 // Initialize the stream
1591 llvm::BitstreamReader StreamFile;
1592 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001593 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001594 (const unsigned char *)Buffer->getBufferEnd());
1595 Stream.init(StreamFile);
1596
1597 // Sniff for the signature.
1598 if (Stream.Read(8) != 'C' ||
1599 Stream.Read(8) != 'P' ||
1600 Stream.Read(8) != 'C' ||
1601 Stream.Read(8) != 'H') {
Mike Stump11289f42009-09-09 15:08:12 +00001602 fprintf(stderr,
Douglas Gregor45fe0362009-05-12 01:31:05 +00001603 "error: '%s' does not appear to be a precompiled header file\n",
1604 PCHFileName.c_str());
1605 return std::string();
1606 }
1607
1608 RecordData Record;
1609 while (!Stream.AtEndOfStream()) {
1610 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001611
Douglas Gregor45fe0362009-05-12 01:31:05 +00001612 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1613 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001614
Douglas Gregor45fe0362009-05-12 01:31:05 +00001615 // We only know the PCH subblock ID.
1616 switch (BlockID) {
1617 case pch::PCH_BLOCK_ID:
1618 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1619 fprintf(stderr, "error: malformed block record in PCH file\n");
1620 return std::string();
1621 }
1622 break;
Mike Stump11289f42009-09-09 15:08:12 +00001623
Douglas Gregor45fe0362009-05-12 01:31:05 +00001624 default:
1625 if (Stream.SkipBlock()) {
1626 fprintf(stderr, "error: malformed block record in PCH file\n");
1627 return std::string();
1628 }
1629 break;
1630 }
1631 continue;
1632 }
1633
1634 if (Code == llvm::bitc::END_BLOCK) {
1635 if (Stream.ReadBlockEnd()) {
1636 fprintf(stderr, "error: error at end of module block in PCH file\n");
1637 return std::string();
1638 }
1639 continue;
1640 }
1641
1642 if (Code == llvm::bitc::DEFINE_ABBREV) {
1643 Stream.ReadAbbrevRecord();
1644 continue;
1645 }
1646
1647 Record.clear();
1648 const char *BlobStart = 0;
1649 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001650 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00001651 == pch::ORIGINAL_FILE_NAME)
1652 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00001653 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00001654
1655 return std::string();
1656}
1657
Douglas Gregor55abb232009-04-10 20:39:37 +00001658/// \brief Parse the record that corresponds to a LangOptions data
1659/// structure.
1660///
1661/// This routine compares the language options used to generate the
1662/// PCH file against the language options set for the current
1663/// compilation. For each option, we classify differences between the
1664/// two compiler states as either "benign" or "important". Benign
1665/// differences don't matter, and we accept them without complaint
1666/// (and without modifying the language options). Differences between
1667/// the states for important options cause the PCH file to be
1668/// unusable, so we emit a warning and return true to indicate that
1669/// there was an error.
1670///
1671/// \returns true if the PCH file is unacceptable, false otherwise.
1672bool PCHReader::ParseLanguageOptions(
1673 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001674 if (Listener) {
1675 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00001676
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001677 #define PARSE_LANGOPT(Option) \
1678 LangOpts.Option = Record[Idx]; \
1679 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00001680
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001681 unsigned Idx = 0;
1682 PARSE_LANGOPT(Trigraphs);
1683 PARSE_LANGOPT(BCPLComment);
1684 PARSE_LANGOPT(DollarIdents);
1685 PARSE_LANGOPT(AsmPreprocessor);
1686 PARSE_LANGOPT(GNUMode);
1687 PARSE_LANGOPT(ImplicitInt);
1688 PARSE_LANGOPT(Digraphs);
1689 PARSE_LANGOPT(HexFloats);
1690 PARSE_LANGOPT(C99);
1691 PARSE_LANGOPT(Microsoft);
1692 PARSE_LANGOPT(CPlusPlus);
1693 PARSE_LANGOPT(CPlusPlus0x);
1694 PARSE_LANGOPT(CXXOperatorNames);
1695 PARSE_LANGOPT(ObjC1);
1696 PARSE_LANGOPT(ObjC2);
1697 PARSE_LANGOPT(ObjCNonFragileABI);
1698 PARSE_LANGOPT(PascalStrings);
1699 PARSE_LANGOPT(WritableStrings);
1700 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00001701 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001702 PARSE_LANGOPT(Exceptions);
1703 PARSE_LANGOPT(NeXTRuntime);
1704 PARSE_LANGOPT(Freestanding);
1705 PARSE_LANGOPT(NoBuiltin);
1706 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00001707 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001708 PARSE_LANGOPT(Blocks);
1709 PARSE_LANGOPT(EmitAllDecls);
1710 PARSE_LANGOPT(MathErrno);
1711 PARSE_LANGOPT(OverflowChecking);
1712 PARSE_LANGOPT(HeinousExtensions);
1713 PARSE_LANGOPT(Optimize);
1714 PARSE_LANGOPT(OptimizeSize);
1715 PARSE_LANGOPT(Static);
1716 PARSE_LANGOPT(PICLevel);
1717 PARSE_LANGOPT(GNUInline);
1718 PARSE_LANGOPT(NoInline);
1719 PARSE_LANGOPT(AccessControl);
1720 PARSE_LANGOPT(CharIsSigned);
1721 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1722 ++Idx;
1723 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1724 ++Idx;
Daniel Dunbar143021e2009-09-21 04:16:19 +00001725 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1726 Record[Idx]);
1727 ++Idx;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001728 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00001729 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001730 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00001731
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001732 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00001733 }
Douglas Gregor55abb232009-04-10 20:39:37 +00001734
1735 return false;
1736}
1737
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001738void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1739 Comments.resize(NumComments);
1740 std::copy(this->Comments, this->Comments + NumComments,
1741 Comments.begin());
1742}
1743
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001744/// \brief Read and return the type at the given offset.
1745///
1746/// This routine actually reads the record corresponding to the type
1747/// at the given offset in the bitstream. It is a helper routine for
1748/// GetType, which deals with reading type IDs.
1749QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001750 // Keep track of where we are in the stream, then jump back there
1751 // after reading this type.
1752 SavedStreamPosition SavedPosition(Stream);
1753
Douglas Gregor1342e842009-07-06 18:54:52 +00001754 // Note that we are loading a type record.
1755 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00001756
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001757 Stream.JumpToBit(Offset);
1758 RecordData Record;
1759 unsigned Code = Stream.ReadCode();
1760 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00001761 case pch::TYPE_EXT_QUAL: {
Mike Stump11289f42009-09-09 15:08:12 +00001762 assert(Record.size() == 3 &&
Douglas Gregor455b8f42009-04-15 22:00:08 +00001763 "Incorrect encoding of extended qualifier type");
1764 QualType Base = GetType(Record[0]);
1765 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1766 unsigned AddressSpace = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001767
Douglas Gregor455b8f42009-04-15 22:00:08 +00001768 QualType T = Base;
1769 if (GCAttr != QualType::GCNone)
Chris Lattner8575daa2009-04-27 21:45:14 +00001770 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor455b8f42009-04-15 22:00:08 +00001771 if (AddressSpace)
Chris Lattner8575daa2009-04-27 21:45:14 +00001772 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor455b8f42009-04-15 22:00:08 +00001773 return T;
1774 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001775
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001776 case pch::TYPE_FIXED_WIDTH_INT: {
1777 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001778 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001779 }
1780
1781 case pch::TYPE_COMPLEX: {
1782 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1783 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001784 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001785 }
1786
1787 case pch::TYPE_POINTER: {
1788 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1789 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001790 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001791 }
1792
1793 case pch::TYPE_BLOCK_POINTER: {
1794 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1795 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001796 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001797 }
1798
1799 case pch::TYPE_LVALUE_REFERENCE: {
1800 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1801 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001802 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001803 }
1804
1805 case pch::TYPE_RVALUE_REFERENCE: {
1806 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1807 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001808 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001809 }
1810
1811 case pch::TYPE_MEMBER_POINTER: {
1812 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1813 QualType PointeeType = GetType(Record[0]);
1814 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001815 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001816 }
1817
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001818 case pch::TYPE_CONSTANT_ARRAY: {
1819 QualType ElementType = GetType(Record[0]);
1820 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1821 unsigned IndexTypeQuals = Record[2];
1822 unsigned Idx = 3;
1823 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00001824 return Context->getConstantArrayType(ElementType, Size,
1825 ASM, IndexTypeQuals);
1826 }
1827
1828 case pch::TYPE_CONSTANT_ARRAY_WITH_EXPR: {
1829 QualType ElementType = GetType(Record[0]);
1830 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1831 unsigned IndexTypeQuals = Record[2];
1832 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1833 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
1834 unsigned Idx = 5;
1835 llvm::APInt Size = ReadAPInt(Record, Idx);
1836 return Context->getConstantArrayWithExprType(ElementType,
1837 Size, ReadTypeExpr(),
1838 ASM, IndexTypeQuals,
1839 SourceRange(LBLoc, RBLoc));
1840 }
1841
1842 case pch::TYPE_CONSTANT_ARRAY_WITHOUT_EXPR: {
1843 QualType ElementType = GetType(Record[0]);
1844 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1845 unsigned IndexTypeQuals = Record[2];
1846 unsigned Idx = 3;
1847 llvm::APInt Size = ReadAPInt(Record, Idx);
1848 return Context->getConstantArrayWithoutExprType(ElementType, Size,
1849 ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001850 }
1851
1852 case pch::TYPE_INCOMPLETE_ARRAY: {
1853 QualType ElementType = GetType(Record[0]);
1854 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1855 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00001856 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001857 }
1858
1859 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001860 QualType ElementType = GetType(Record[0]);
1861 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1862 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00001863 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1864 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001865 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00001866 ASM, IndexTypeQuals,
1867 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001868 }
1869
1870 case pch::TYPE_VECTOR: {
1871 if (Record.size() != 2) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001872 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001873 return QualType();
1874 }
1875
1876 QualType ElementType = GetType(Record[0]);
1877 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001878 return Context->getVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001879 }
1880
1881 case pch::TYPE_EXT_VECTOR: {
1882 if (Record.size() != 2) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001883 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001884 return QualType();
1885 }
1886
1887 QualType ElementType = GetType(Record[0]);
1888 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001889 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001890 }
1891
1892 case pch::TYPE_FUNCTION_NO_PROTO: {
1893 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001894 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001895 return QualType();
1896 }
1897 QualType ResultType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001898 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001899 }
1900
1901 case pch::TYPE_FUNCTION_PROTO: {
1902 QualType ResultType = GetType(Record[0]);
1903 unsigned Idx = 1;
1904 unsigned NumParams = Record[Idx++];
1905 llvm::SmallVector<QualType, 16> ParamTypes;
1906 for (unsigned I = 0; I != NumParams; ++I)
1907 ParamTypes.push_back(GetType(Record[Idx++]));
1908 bool isVariadic = Record[Idx++];
1909 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001910 bool hasExceptionSpec = Record[Idx++];
1911 bool hasAnyExceptionSpec = Record[Idx++];
1912 unsigned NumExceptions = Record[Idx++];
1913 llvm::SmallVector<QualType, 2> Exceptions;
1914 for (unsigned I = 0; I != NumExceptions; ++I)
1915 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00001916 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001917 isVariadic, Quals, hasExceptionSpec,
1918 hasAnyExceptionSpec, NumExceptions,
1919 Exceptions.data());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001920 }
1921
1922 case pch::TYPE_TYPEDEF:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001923 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001924 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001925
1926 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner8575daa2009-04-27 21:45:14 +00001927 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001928
1929 case pch::TYPE_TYPEOF: {
1930 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001931 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001932 return QualType();
1933 }
1934 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001935 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001936 }
Mike Stump11289f42009-09-09 15:08:12 +00001937
Anders Carlsson81df7b82009-06-24 19:06:50 +00001938 case pch::TYPE_DECLTYPE:
1939 return Context->getDecltypeType(ReadTypeExpr());
1940
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001941 case pch::TYPE_RECORD:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001942 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001943 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001944
Douglas Gregor1daeb692009-04-13 18:14:40 +00001945 case pch::TYPE_ENUM:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001946 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001947 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor1daeb692009-04-13 18:14:40 +00001948
John McCallfcc33b02009-09-05 00:15:47 +00001949 case pch::TYPE_ELABORATED: {
1950 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1951 unsigned Tag = Record[1];
1952 return Context->getElaboratedType(GetType(Record[0]),
1953 (ElaboratedType::TagKind) Tag);
1954 }
1955
Steve Naroffc277ad12009-07-18 15:33:26 +00001956 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00001957 unsigned Idx = 0;
1958 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1959 unsigned NumProtos = Record[Idx++];
1960 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1961 for (unsigned I = 0; I != NumProtos; ++I)
1962 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc277ad12009-07-18 15:33:26 +00001963 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00001964 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001965
Steve Narofffb4330f2009-06-17 22:40:22 +00001966 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00001967 unsigned Idx = 0;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001968 QualType OIT = GetType(Record[Idx++]);
Chris Lattner6e054af2009-04-22 06:40:03 +00001969 unsigned NumProtos = Record[Idx++];
1970 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1971 for (unsigned I = 0; I != NumProtos; ++I)
1972 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001973 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattner6e054af2009-04-22 06:40:03 +00001974 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001975 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001976 // Suppress a GCC warning
1977 return QualType();
1978}
1979
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001980
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001981QualType PCHReader::GetType(pch::TypeID ID) {
Mike Stump11289f42009-09-09 15:08:12 +00001982 unsigned Quals = ID & 0x07;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001983 unsigned Index = ID >> 3;
1984
1985 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1986 QualType T;
1987 switch ((pch::PredefinedTypeIDs)Index) {
1988 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00001989 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1990 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001991
1992 case pch::PREDEF_TYPE_CHAR_U_ID:
1993 case pch::PREDEF_TYPE_CHAR_S_ID:
1994 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00001995 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001996 break;
1997
Chris Lattner8575daa2009-04-27 21:45:14 +00001998 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1999 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2000 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2001 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2002 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002003 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002004 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2005 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2006 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2007 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2008 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2009 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002010 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002011 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2012 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2013 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2014 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2015 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002016 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002017 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2018 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002019 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2020 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002021 }
2022
2023 assert(!T.isNull() && "Unknown predefined type");
2024 return T.getQualifiedType(Quals);
2025 }
2026
2027 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002028 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor745ed142009-04-25 18:35:21 +00002029 if (!TypesLoaded[Index])
2030 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002031
Douglas Gregor745ed142009-04-25 18:35:21 +00002032 return QualType(TypesLoaded[Index], Quals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002033}
2034
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002035Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002036 if (ID == 0)
2037 return 0;
2038
Douglas Gregor745ed142009-04-25 18:35:21 +00002039 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002040 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002041 return 0;
2042 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002043
Douglas Gregor745ed142009-04-25 18:35:21 +00002044 unsigned Index = ID - 1;
2045 if (!DeclsLoaded[Index])
2046 ReadDeclRecord(DeclOffsets[Index], Index);
2047
2048 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002049}
2050
Chris Lattner9c28af02009-04-27 05:46:25 +00002051/// \brief Resolve the offset of a statement into a statement.
2052///
2053/// This operation will read a new statement from the external
2054/// source each time it is called, and is meant to be used via a
2055/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2056Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002057 // Since we know tha this statement is part of a decl, make sure to use the
2058 // decl cursor to read it.
2059 DeclsCursor.JumpToBit(Offset);
2060 return ReadStmt(DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002061}
2062
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002063bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002064 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002065 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002066 "DeclContext has no lexical decls in storage");
2067 uint64_t Offset = DeclContextOffsets[DC].first;
2068 assert(Offset && "DeclContext has no lexical decls in storage");
2069
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002070 // Keep track of where we are in the stream, then jump back there
2071 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002072 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002073
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002074 // Load the record containing all of the declarations lexically in
2075 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002076 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002077 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002078 unsigned Code = DeclsCursor.ReadCode();
2079 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002080 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002081 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2082
2083 // Load all of the declaration IDs
2084 Decls.clear();
2085 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002086 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002087 return false;
2088}
2089
2090bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner72405d62009-04-27 07:35:40 +00002091 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002092 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002093 "DeclContext has no visible decls in storage");
2094 uint64_t Offset = DeclContextOffsets[DC].second;
2095 assert(Offset && "DeclContext has no visible decls in storage");
2096
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002097 // Keep track of where we are in the stream, then jump back there
2098 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002099 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002100
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002101 // Load the record containing all of the declarations visible in
2102 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002103 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002104 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002105 unsigned Code = DeclsCursor.ReadCode();
2106 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002107 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002108 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2109 if (Record.size() == 0)
Mike Stump11289f42009-09-09 15:08:12 +00002110 return false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002111
2112 Decls.clear();
2113
2114 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002115 while (Idx < Record.size()) {
2116 Decls.push_back(VisibleDeclaration());
2117 Decls.back().Name = ReadDeclarationName(Record, Idx);
2118
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002119 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002120 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002121 LoadedDecls.reserve(Size);
2122 for (unsigned I = 0; I < Size; ++I)
2123 LoadedDecls.push_back(Record[Idx++]);
2124 }
2125
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002126 ++NumVisibleDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002127 return false;
2128}
2129
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002130void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002131 this->Consumer = Consumer;
2132
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002133 if (!Consumer)
2134 return;
2135
2136 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002137 // Force deserialization of this decl, which will cause it to be passed to
2138 // the consumer (or queued).
2139 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002140 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002141
2142 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2143 DeclGroupRef DG(InterestingDecls[I]);
2144 Consumer->HandleTopLevelDecl(DG);
2145 }
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002146}
2147
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002148void PCHReader::PrintStats() {
2149 std::fprintf(stderr, "*** PCH Statistics:\n");
2150
Mike Stump11289f42009-09-09 15:08:12 +00002151 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002152 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
2153 (Type *)0);
2154 unsigned NumDeclsLoaded
2155 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2156 (Decl *)0);
2157 unsigned NumIdentifiersLoaded
2158 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2159 IdentifiersLoaded.end(),
2160 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002161 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002162 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2163 SelectorsLoaded.end(),
2164 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002165
Douglas Gregorc5046832009-04-27 18:38:38 +00002166 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2167 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002168 if (TotalNumSLocEntries)
2169 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2170 NumSLocEntriesRead, TotalNumSLocEntries,
2171 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002172 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002173 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002174 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2175 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2176 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002177 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002178 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2179 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002180 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002181 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002182 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2183 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002184 if (TotalNumSelectors)
2185 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2186 NumSelectorsLoaded, TotalNumSelectors,
2187 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2188 if (TotalNumStatements)
2189 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2190 NumStatementsRead, TotalNumStatements,
2191 ((float)NumStatementsRead/TotalNumStatements * 100));
2192 if (TotalNumMacros)
2193 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2194 NumMacrosRead, TotalNumMacros,
2195 ((float)NumMacrosRead/TotalNumMacros * 100));
2196 if (TotalLexicalDeclContexts)
2197 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2198 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2199 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2200 * 100));
2201 if (TotalVisibleDeclContexts)
2202 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2203 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2204 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2205 * 100));
2206 if (TotalSelectorsInMethodPool) {
2207 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2208 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2209 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2210 * 100));
2211 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2212 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002213 std::fprintf(stderr, "\n");
2214}
2215
Douglas Gregora868bbd2009-04-21 22:25:48 +00002216void PCHReader::InitializeSema(Sema &S) {
2217 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002218 S.ExternalSource = this;
2219
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002220 // Makes sure any declarations that were deserialized "too early"
2221 // still get added to the identifier's declaration chains.
2222 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2223 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2224 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002225 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002226 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002227
2228 // If there were any tentative definitions, deserialize them and add
2229 // them to Sema's table of tentative definitions.
2230 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2231 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2232 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner0c797362009-09-08 18:19:27 +00002233 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregord4df8652009-04-22 22:02:47 +00002234 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002235
2236 // If there were any locally-scoped external declarations,
2237 // deserialize them and add them to Sema's table of locally-scoped
2238 // external declarations.
2239 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2240 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2241 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2242 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002243
2244 // If there were any ext_vector type declarations, deserialize them
2245 // and add them to Sema's vector of such declarations.
2246 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2247 SemaObj->ExtVectorDecls.push_back(
2248 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00002249}
2250
2251IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2252 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00002253 PCHIdentifierLookupTable *IdTable
Douglas Gregora868bbd2009-04-21 22:25:48 +00002254 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2255 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2256 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2257 if (Pos == IdTable->end())
2258 return 0;
2259
2260 // Dereferencing the iterator has the effect of building the
2261 // IdentifierInfo node and populating it with the various
2262 // declarations it needs.
2263 return *Pos;
2264}
2265
Mike Stump11289f42009-09-09 15:08:12 +00002266std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00002267PCHReader::ReadMethodPool(Selector Sel) {
2268 if (!MethodPoolLookupTable)
2269 return std::pair<ObjCMethodList, ObjCMethodList>();
2270
2271 // Try to find this selector within our on-disk hash table.
2272 PCHMethodPoolLookupTable *PoolTable
2273 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2274 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00002275 if (Pos == PoolTable->end()) {
2276 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002277 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00002278 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00002279
Douglas Gregor95c13f52009-04-25 17:48:32 +00002280 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002281 return *Pos;
2282}
2283
Douglas Gregor0e149972009-04-25 19:10:14 +00002284void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00002285 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002286 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00002287 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00002288}
2289
Douglas Gregor1342e842009-07-06 18:54:52 +00002290/// \brief Set the globally-visible declarations associated with the given
2291/// identifier.
2292///
2293/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00002294/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00002295/// them.
2296///
2297/// \param II an IdentifierInfo that refers to one or more globally-visible
2298/// declarations.
2299///
2300/// \param DeclIDs the set of declaration IDs with the name @p II that are
2301/// visible at global scope.
2302///
2303/// \param Nonrecursive should be true to indicate that the caller knows that
2304/// this call is non-recursive, and therefore the globally-visible declarations
2305/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00002306void
2307PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00002308 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2309 bool Nonrecursive) {
2310 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2311 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2312 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2313 PII.II = II;
2314 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2315 PII.DeclIDs.push_back(DeclIDs[I]);
2316 return;
2317 }
Mike Stump11289f42009-09-09 15:08:12 +00002318
Douglas Gregor1342e842009-07-06 18:54:52 +00002319 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2320 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2321 if (SemaObj) {
2322 // Introduce this declaration into the translation-unit scope
2323 // and add it to the declaration chain for this identifier, so
2324 // that (unqualified) name lookup will find it.
2325 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2326 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2327 } else {
2328 // Queue this declaration so that it will be added to the
2329 // translation unit scope and identifier's declaration chain
2330 // once a Sema object is known.
2331 PreloadedDecls.push_back(D);
2332 }
2333 }
2334}
2335
Chris Lattnerc523d8e2009-04-11 21:15:38 +00002336IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002337 if (ID == 0)
2338 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002339
Douglas Gregor0e149972009-04-25 19:10:14 +00002340 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002341 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002342 return 0;
2343 }
Mike Stump11289f42009-09-09 15:08:12 +00002344
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002345 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00002346 if (!IdentifiersLoaded[ID - 1]) {
2347 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor95272492009-04-25 21:21:38 +00002348 const char *Str = IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00002349
Douglas Gregorab4df582009-04-28 20:01:51 +00002350 // All of the strings in the PCH file are preceded by a 16-bit
2351 // length. Extract that 16-bit length to avoid having to execute
2352 // strlen().
2353 const char *StrLenPtr = Str - 2;
2354 unsigned StrLen = (((unsigned) StrLenPtr[0])
2355 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00002356 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002357 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002358 }
Mike Stump11289f42009-09-09 15:08:12 +00002359
Douglas Gregor0e149972009-04-25 19:10:14 +00002360 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002361}
2362
Douglas Gregor258ae542009-04-27 06:38:32 +00002363void PCHReader::ReadSLocEntry(unsigned ID) {
2364 ReadSLocEntryRecord(ID);
2365}
2366
Steve Naroff2ddea052009-04-23 10:39:46 +00002367Selector PCHReader::DecodeSelector(unsigned ID) {
2368 if (ID == 0)
2369 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00002370
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002371 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00002372 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002373
2374 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002375 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00002376 return Selector();
2377 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00002378
2379 unsigned Index = ID - 1;
2380 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2381 // Load this selector from the selector table.
2382 // FIXME: endianness portability issues with SelectorOffsets table
2383 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002384 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00002385 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2386 }
2387
2388 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00002389}
2390
Mike Stump11289f42009-09-09 15:08:12 +00002391DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002392PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2393 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2394 switch (Kind) {
2395 case DeclarationName::Identifier:
2396 return DeclarationName(GetIdentifierInfo(Record, Idx));
2397
2398 case DeclarationName::ObjCZeroArgSelector:
2399 case DeclarationName::ObjCOneArgSelector:
2400 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00002401 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002402
2403 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002404 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002405 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002406
2407 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002408 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002409 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002410
2411 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002412 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002413 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002414
2415 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002416 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002417 (OverloadedOperatorKind)Record[Idx++]);
2418
2419 case DeclarationName::CXXUsingDirective:
2420 return DeclarationName::getUsingDirectiveName();
2421 }
2422
2423 // Required to silence GCC warning
2424 return DeclarationName();
2425}
Douglas Gregor55abb232009-04-10 20:39:37 +00002426
Douglas Gregor1daeb692009-04-13 18:14:40 +00002427/// \brief Read an integral value
2428llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2429 unsigned BitWidth = Record[Idx++];
2430 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2431 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2432 Idx += NumWords;
2433 return Result;
2434}
2435
2436/// \brief Read a signed integral value
2437llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2438 bool isUnsigned = Record[Idx++];
2439 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2440}
2441
Douglas Gregore0a3a512009-04-14 21:55:33 +00002442/// \brief Read a floating-point value
2443llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00002444 return llvm::APFloat(ReadAPInt(Record, Idx));
2445}
2446
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002447// \brief Read a string
2448std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2449 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00002450 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002451 Idx += Len;
2452 return Result;
2453}
2454
Douglas Gregor55abb232009-04-10 20:39:37 +00002455DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00002456 return Diag(SourceLocation(), DiagID);
2457}
2458
2459DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002460 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00002461}
Douglas Gregora9af1d12009-04-17 00:04:06 +00002462
Douglas Gregora868bbd2009-04-21 22:25:48 +00002463/// \brief Retrieve the identifier table associated with the
2464/// preprocessor.
2465IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002466 assert(PP && "Forgot to set Preprocessor ?");
2467 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00002468}
2469
Douglas Gregora9af1d12009-04-17 00:04:06 +00002470/// \brief Record that the given ID maps to the given switch-case
2471/// statement.
2472void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2473 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2474 SwitchCaseStmts[ID] = SC;
2475}
2476
2477/// \brief Retrieve the switch-case statement with the given ID.
2478SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2479 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2480 return SwitchCaseStmts[ID];
2481}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002482
2483/// \brief Record that the given label statement has been
2484/// deserialized and has the given ID.
2485void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00002486 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002487 "Deserialized label twice");
2488 LabelStmts[ID] = S;
2489
2490 // If we've already seen any goto statements that point to this
2491 // label, resolve them now.
2492 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2493 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2494 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2495 Goto->second->setLabel(S);
2496 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00002497
2498 // If we've already seen any address-label statements that point to
2499 // this label, resolve them now.
2500 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00002501 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00002502 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00002503 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00002504 AddrLabel != AddrLabels.second; ++AddrLabel)
2505 AddrLabel->second->setLabel(S);
2506 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002507}
2508
2509/// \brief Set the label of the given statement to the label
2510/// identified by ID.
2511///
2512/// Depending on the order in which the label and other statements
2513/// referencing that label occur, this operation may complete
2514/// immediately (updating the statement) or it may queue the
2515/// statement to be back-patched later.
2516void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2517 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2518 if (Label != LabelStmts.end()) {
2519 // We've already seen this label, so set the label of the goto and
2520 // we're done.
2521 S->setLabel(Label->second);
2522 } else {
2523 // We haven't seen this label yet, so add this goto to the set of
2524 // unresolved goto statements.
2525 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2526 }
2527}
Douglas Gregor779d8652009-04-17 18:58:21 +00002528
2529/// \brief Set the label of the given expression to the label
2530/// identified by ID.
2531///
2532/// Depending on the order in which the label and other statements
2533/// referencing that label occur, this operation may complete
2534/// immediately (updating the statement) or it may queue the
2535/// statement to be back-patched later.
2536void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2537 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2538 if (Label != LabelStmts.end()) {
2539 // We've already seen this label, so set the label of the
2540 // label-address expression and we're done.
2541 S->setLabel(Label->second);
2542 } else {
2543 // We haven't seen this label yet, so add this label-address
2544 // expression to the set of unresolved label-address expressions.
2545 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2546 }
2547}
Douglas Gregor1342e842009-07-06 18:54:52 +00002548
2549
Mike Stump11289f42009-09-09 15:08:12 +00002550PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00002551 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2552 Reader.CurrentlyLoadingTypeOrDecl = this;
2553}
2554
2555PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2556 if (!Parent) {
2557 // If any identifiers with corresponding top-level declarations have
2558 // been loaded, load those declarations now.
2559 while (!Reader.PendingIdentifierInfos.empty()) {
2560 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2561 Reader.PendingIdentifierInfos.front().DeclIDs,
2562 true);
2563 Reader.PendingIdentifierInfos.pop_front();
2564 }
2565 }
2566
Mike Stump11289f42009-09-09 15:08:12 +00002567 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00002568}