blob: aab5dd8783ff158cc543f4d8d1af5f5098cbd63b [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000021#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000024#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregor2cf26342009-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 Gregore721f952009-04-28 18:58:38 +000033#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000035#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-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);
72 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
73 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000074 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-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);
79 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
80 diag::warn_pch_thread_safe_statics);
81 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
82 PARSE_LANGOPT_BENIGN(EmitAllDecls);
83 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
84 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
85 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
86 diag::warn_pch_heinous_extensions);
87 // FIXME: Most of the options below are benign if the macro wasn't
88 // used. Unfortunately, this means that a PCH compiled without
89 // optimization can't be used with optimization turned on, even
90 // though the only thing that changes is whether __OPTIMIZE__ was
91 // defined... but if __OPTIMIZE__ never showed up in the header, it
92 // doesn't matter. We could consider making this some special kind
93 // of check.
94 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
95 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
96 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
97 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
98 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
99 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
100 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
101 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
102 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
103 Reader.Diag(diag::warn_pch_gc_mode)
104 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
105 return true;
106 }
107 PARSE_LANGOPT_BENIGN(getVisibilityMode());
108 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000109 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000110#undef PARSE_LANGOPT_IRRELEVANT
111#undef PARSE_LANGOPT_BENIGN
112
113 return false;
114}
115
116bool PCHValidator::ReadTargetTriple(const std::string &Triple) {
117 if (Triple != PP.getTargetInfo().getTargetTriple()) {
118 Reader.Diag(diag::warn_pch_target_triple)
119 << Triple << PP.getTargetInfo().getTargetTriple();
120 return true;
121 }
122 return false;
123}
124
125/// \brief Split the given string into a vector of lines, eliminating
126/// any empty lines in the process.
127///
128/// \param Str the string to split.
129/// \param Len the length of Str.
130/// \param KeepEmptyLines true if empty lines should be included
131/// \returns a vector of lines, with the line endings removed
132static std::vector<std::string> splitLines(const char *Str, unsigned Len,
133 bool KeepEmptyLines = false) {
134 std::vector<std::string> Lines;
135 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
136 unsigned LineEnd = LineStart;
137 while (LineEnd < Len && Str[LineEnd] != '\n')
138 ++LineEnd;
139 if (LineStart != LineEnd || KeepEmptyLines)
140 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
141 LineStart = LineEnd;
142 }
143 return Lines;
144}
145
146/// \brief Determine whether the string Haystack starts with the
147/// substring Needle.
148static bool startsWith(const std::string &Haystack, const char *Needle) {
149 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
150 if (I == N)
151 return false;
152 if (Haystack[I] != Needle[I])
153 return false;
154 }
155
156 return true;
157}
158
159/// \brief Determine whether the string Haystack starts with the
160/// substring Needle.
161static inline bool startsWith(const std::string &Haystack,
162 const std::string &Needle) {
163 return startsWith(Haystack, Needle.c_str());
164}
165
166bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef,
167 unsigned PCHPredefLen,
168 FileID PCHBufferID,
169 std::string &SuggestedPredefines) {
170 const char *Predef = PP.getPredefines().c_str();
171 unsigned PredefLen = PP.getPredefines().size();
172
173 // If the two predefines buffers compare equal, we're done!
174 if (PredefLen == PCHPredefLen &&
175 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
176 return false;
177
178 SourceManager &SourceMgr = PP.getSourceManager();
179
180 // The predefines buffers are different. Determine what the
181 // differences are, and whether they require us to reject the PCH
182 // file.
183 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
184 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
185
186 // Sort both sets of predefined buffer lines, since
187 std::sort(CmdLineLines.begin(), CmdLineLines.end());
188 std::sort(PCHLines.begin(), PCHLines.end());
189
190 // Determine which predefines that where used to build the PCH file
191 // are missing from the command line.
192 std::vector<std::string> MissingPredefines;
193 std::set_difference(PCHLines.begin(), PCHLines.end(),
194 CmdLineLines.begin(), CmdLineLines.end(),
195 std::back_inserter(MissingPredefines));
196
197 bool MissingDefines = false;
198 bool ConflictingDefines = false;
199 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
200 const std::string &Missing = MissingPredefines[I];
201 if (!startsWith(Missing, "#define ") != 0) {
202 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
203 return true;
204 }
205
206 // This is a macro definition. Determine the name of the macro
207 // we're defining.
208 std::string::size_type StartOfMacroName = strlen("#define ");
209 std::string::size_type EndOfMacroName
210 = Missing.find_first_of("( \n\r", StartOfMacroName);
211 assert(EndOfMacroName != std::string::npos &&
212 "Couldn't find the end of the macro name");
213 std::string MacroName = Missing.substr(StartOfMacroName,
214 EndOfMacroName - StartOfMacroName);
215
216 // Determine whether this macro was given a different definition
217 // on the command line.
218 std::string MacroDefStart = "#define " + MacroName;
219 std::string::size_type MacroDefLen = MacroDefStart.size();
220 std::vector<std::string>::iterator ConflictPos
221 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
222 MacroDefStart);
223 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
224 if (!startsWith(*ConflictPos, MacroDefStart)) {
225 // Different macro; we're done.
226 ConflictPos = CmdLineLines.end();
227 break;
228 }
229
230 assert(ConflictPos->size() > MacroDefLen &&
231 "Invalid #define in predefines buffer?");
232 if ((*ConflictPos)[MacroDefLen] != ' ' &&
233 (*ConflictPos)[MacroDefLen] != '(')
234 continue; // Longer macro name; keep trying.
235
236 // We found a conflicting macro definition.
237 break;
238 }
239
240 if (ConflictPos != CmdLineLines.end()) {
241 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
242 << MacroName;
243
244 // Show the definition of this macro within the PCH file.
245 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
246 unsigned Offset = MissingDef - PCHPredef;
247 SourceLocation PCHMissingLoc
248 = SourceMgr.getLocForStartOfFile(PCHBufferID)
249 .getFileLocWithOffset(Offset);
250 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
251 << MacroName;
252
253 ConflictingDefines = true;
254 continue;
255 }
256
257 // If the macro doesn't conflict, then we'll just pick up the
258 // macro definition from the PCH file. Warn the user that they
259 // made a mistake.
260 if (ConflictingDefines)
261 continue; // Don't complain if there are already conflicting defs
262
263 if (!MissingDefines) {
264 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
265 MissingDefines = true;
266 }
267
268 // Show the definition of this macro within the PCH file.
269 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
270 unsigned Offset = MissingDef - PCHPredef;
271 SourceLocation PCHMissingLoc
272 = SourceMgr.getLocForStartOfFile(PCHBufferID)
273 .getFileLocWithOffset(Offset);
274 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
275 }
276
277 if (ConflictingDefines)
278 return true;
279
280 // Determine what predefines were introduced based on command-line
281 // parameters that were not present when building the PCH
282 // file. Extra #defines are okay, so long as the identifiers being
283 // defined were not used within the precompiled header.
284 std::vector<std::string> ExtraPredefines;
285 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
286 PCHLines.begin(), PCHLines.end(),
287 std::back_inserter(ExtraPredefines));
288 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
289 const std::string &Extra = ExtraPredefines[I];
290 if (!startsWith(Extra, "#define ") != 0) {
291 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
292 return true;
293 }
294
295 // This is an extra macro definition. Determine the name of the
296 // macro we're defining.
297 std::string::size_type StartOfMacroName = strlen("#define ");
298 std::string::size_type EndOfMacroName
299 = Extra.find_first_of("( \n\r", StartOfMacroName);
300 assert(EndOfMacroName != std::string::npos &&
301 "Couldn't find the end of the macro name");
302 std::string MacroName = Extra.substr(StartOfMacroName,
303 EndOfMacroName - StartOfMacroName);
304
305 // Check whether this name was used somewhere in the PCH file. If
306 // so, defining it as a macro could change behavior, so we reject
307 // the PCH file.
308 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
309 MacroName.c_str() + MacroName.size())) {
310 Reader.Diag(diag::warn_macro_name_used_in_pch)
311 << II;
312 return true;
313 }
314
315 // Add this definition to the suggested predefines buffer.
316 SuggestedPredefines += Extra;
317 SuggestedPredefines += '\n';
318 }
319
320 // If we get here, it's because the predefines buffer had compatible
321 // contents. Accept the PCH file.
322 return false;
323}
324
325void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
326 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
327}
328
329void PCHValidator::ReadCounter(unsigned Value) {
330 PP.setCounterValue(Value);
331}
332
333
334
335//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000336// PCH reader implementation
337//===----------------------------------------------------------------------===//
338
Douglas Gregore650c8c2009-07-07 00:12:59 +0000339PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
340 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000341 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
342 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
343 SemaObj(0), PP(&PP), Context(Context), Consumer(0),
344 IdentifierTableData(0), IdentifierLookupTable(0),
345 IdentifierOffsets(0),
346 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
347 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000348 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Douglas Gregor2e222532009-07-02 17:08:52 +0000349 NumStatHits(0), NumStatMisses(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000350 NumSLocEntriesRead(0), NumStatementsRead(0),
351 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000352 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
353 CurrentlyLoadingTypeOrDecl(0) {
354 RelocatablePCH = false;
355}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000356
357PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000358 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000359 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Argyrios Kyrtzidis57102112009-06-19 07:55:35 +0000360 SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000361 IdentifierTableData(0), IdentifierLookupTable(0),
362 IdentifierOffsets(0),
363 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
364 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000365 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
366 NumStatHits(0), NumStatMisses(0),
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000367 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000368 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000369 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000370 CurrentlyLoadingTypeOrDecl(0) {
371 RelocatablePCH = false;
372}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000373
374PCHReader::~PCHReader() {}
375
Chris Lattnerda930612009-04-27 05:58:23 +0000376Expr *PCHReader::ReadDeclExpr() {
377 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
378}
379
380Expr *PCHReader::ReadTypeExpr() {
Chris Lattner52e97d12009-04-27 05:41:06 +0000381 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000382}
383
384
Douglas Gregor668c1a42009-04-21 22:25:48 +0000385namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000386class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
387 PCHReader &Reader;
388
389public:
390 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
391
392 typedef Selector external_key_type;
393 typedef external_key_type internal_key_type;
394
395 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
396
397 static bool EqualKey(const internal_key_type& a,
398 const internal_key_type& b) {
399 return a == b;
400 }
401
402 static unsigned ComputeHash(Selector Sel) {
403 unsigned N = Sel.getNumArgs();
404 if (N == 0)
405 ++N;
406 unsigned R = 5381;
407 for (unsigned I = 0; I != N; ++I)
408 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
409 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
410 return R;
411 }
412
413 // This hopefully will just get inlined and removed by the optimizer.
414 static const internal_key_type&
415 GetInternalKey(const external_key_type& x) { return x; }
416
417 static std::pair<unsigned, unsigned>
418 ReadKeyDataLength(const unsigned char*& d) {
419 using namespace clang::io;
420 unsigned KeyLen = ReadUnalignedLE16(d);
421 unsigned DataLen = ReadUnalignedLE16(d);
422 return std::make_pair(KeyLen, DataLen);
423 }
424
Douglas Gregor83941df2009-04-25 17:48:32 +0000425 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000426 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000427 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000428 unsigned N = ReadUnalignedLE16(d);
429 IdentifierInfo *FirstII
430 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
431 if (N == 0)
432 return SelTable.getNullarySelector(FirstII);
433 else if (N == 1)
434 return SelTable.getUnarySelector(FirstII);
435
436 llvm::SmallVector<IdentifierInfo *, 16> Args;
437 Args.push_back(FirstII);
438 for (unsigned I = 1; I != N; ++I)
439 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
440
Douglas Gregor75fdb232009-05-22 22:45:36 +0000441 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000442 }
443
444 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
445 using namespace clang::io;
446 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
447 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
448
449 data_type Result;
450
451 // Load instance methods
452 ObjCMethodList *Prev = 0;
453 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
454 ObjCMethodDecl *Method
455 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
456 if (!Result.first.Method) {
457 // This is the first method, which is the easy case.
458 Result.first.Method = Method;
459 Prev = &Result.first;
460 continue;
461 }
462
463 Prev->Next = new ObjCMethodList(Method, 0);
464 Prev = Prev->Next;
465 }
466
467 // Load factory methods
468 Prev = 0;
469 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
470 ObjCMethodDecl *Method
471 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
472 if (!Result.second.Method) {
473 // This is the first method, which is the easy case.
474 Result.second.Method = Method;
475 Prev = &Result.second;
476 continue;
477 }
478
479 Prev->Next = new ObjCMethodList(Method, 0);
480 Prev = Prev->Next;
481 }
482
483 return Result;
484 }
485};
486
487} // end anonymous namespace
488
489/// \brief The on-disk hash table used for the global method pool.
490typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
491 PCHMethodPoolLookupTable;
492
493namespace {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000494class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
495 PCHReader &Reader;
496
497 // If we know the IdentifierInfo in advance, it is here and we will
498 // not build a new one. Used when deserializing information about an
499 // identifier that was constructed before the PCH file was read.
500 IdentifierInfo *KnownII;
501
502public:
503 typedef IdentifierInfo * data_type;
504
505 typedef const std::pair<const char*, unsigned> external_key_type;
506
507 typedef external_key_type internal_key_type;
508
509 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
510 : Reader(Reader), KnownII(II) { }
511
512 static bool EqualKey(const internal_key_type& a,
513 const internal_key_type& b) {
514 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
515 : false;
516 }
517
518 static unsigned ComputeHash(const internal_key_type& a) {
519 return BernsteinHash(a.first, a.second);
520 }
521
522 // This hopefully will just get inlined and removed by the optimizer.
523 static const internal_key_type&
524 GetInternalKey(const external_key_type& x) { return x; }
525
526 static std::pair<unsigned, unsigned>
527 ReadKeyDataLength(const unsigned char*& d) {
528 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000529 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000530 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000531 return std::make_pair(KeyLen, DataLen);
532 }
533
534 static std::pair<const char*, unsigned>
535 ReadKey(const unsigned char* d, unsigned n) {
536 assert(n >= 2 && d[n-1] == '\0');
537 return std::make_pair((const char*) d, n-1);
538 }
539
540 IdentifierInfo *ReadData(const internal_key_type& k,
541 const unsigned char* d,
542 unsigned DataLen) {
543 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000544 pch::IdentID ID = ReadUnalignedLE32(d);
545 bool IsInteresting = ID & 0x01;
546
547 // Wipe out the "is interesting" bit.
548 ID = ID >> 1;
549
550 if (!IsInteresting) {
551 // For unintersting identifiers, just build the IdentifierInfo
552 // and associate it with the persistent ID.
553 IdentifierInfo *II = KnownII;
554 if (!II)
555 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
556 k.first, k.first + k.second);
557 Reader.SetIdentifierInfo(ID, II);
558 return II;
559 }
560
Douglas Gregor5998da52009-04-28 21:32:13 +0000561 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000562 bool CPlusPlusOperatorKeyword = Bits & 0x01;
563 Bits >>= 1;
564 bool Poisoned = Bits & 0x01;
565 Bits >>= 1;
566 bool ExtensionToken = Bits & 0x01;
567 Bits >>= 1;
568 bool hasMacroDefinition = Bits & 0x01;
569 Bits >>= 1;
570 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
571 Bits >>= 10;
Douglas Gregora92193e2009-04-28 21:18:29 +0000572
Douglas Gregor2deaea32009-04-22 18:49:13 +0000573 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000574 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000575
576 // Build the IdentifierInfo itself and link the identifier ID with
577 // the new IdentifierInfo.
578 IdentifierInfo *II = KnownII;
579 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000580 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
581 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000582 Reader.SetIdentifierInfo(ID, II);
583
Douglas Gregor2deaea32009-04-22 18:49:13 +0000584 // Set or check the various bits in the IdentifierInfo structure.
585 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000586 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
587 assert(II->isExtensionToken() == ExtensionToken &&
588 "Incorrect extension token flag");
589 (void)ExtensionToken;
590 II->setIsPoisoned(Poisoned);
591 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
592 "Incorrect C++ operator keyword flag");
593 (void)CPlusPlusOperatorKeyword;
594
Douglas Gregor37e26842009-04-21 23:56:24 +0000595 // If this identifier is a macro, deserialize the macro
596 // definition.
597 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000598 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000599 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000600 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000601 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000602
603 // Read all of the declarations visible at global scope with this
604 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000605 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000606 if (DataLen > 0) {
607 llvm::SmallVector<uint32_t, 4> DeclIDs;
608 for (; DataLen > 0; DataLen -= 4)
609 DeclIDs.push_back(ReadUnalignedLE32(d));
610 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000611 }
Douglas Gregord89275b2009-07-06 18:54:52 +0000612
Douglas Gregor668c1a42009-04-21 22:25:48 +0000613 return II;
614 }
615};
616
617} // end anonymous namespace
618
619/// \brief The on-disk hash table used to contain information about
620/// all of the identifiers in the program.
621typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
622 PCHIdentifierLookupTable;
623
Douglas Gregora02b1472009-04-28 21:53:25 +0000624bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000625 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
626 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000627 return true;
628}
629
Douglas Gregore1d918e2009-04-10 23:10:45 +0000630/// \brief Check the contents of the predefines buffer against the
631/// contents of the predefines buffer used to build the PCH file.
632///
633/// The contents of the two predefines buffers should be the same. If
634/// not, then some command-line option changed the preprocessor state
635/// and we must reject the PCH file.
636///
637/// \param PCHPredef The start of the predefines buffer in the PCH
638/// file.
639///
640/// \param PCHPredefLen The length of the predefines buffer in the PCH
641/// file.
642///
643/// \param PCHBufferID The FileID for the PCH predefines buffer.
644///
645/// \returns true if there was a mismatch (in which case the PCH file
646/// should be ignored), or false otherwise.
647bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
648 unsigned PCHPredefLen,
649 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000650 if (Listener)
651 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
652 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000653 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000654}
655
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000656//===----------------------------------------------------------------------===//
657// Source Manager Deserialization
658//===----------------------------------------------------------------------===//
659
Douglas Gregorbd945002009-04-13 16:31:14 +0000660/// \brief Read the line table in the source manager block.
661/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000662bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000663 unsigned Idx = 0;
664 LineTableInfo &LineTable = SourceMgr.getLineTable();
665
666 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000667 std::map<int, int> FileIDs;
668 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000669 // Extract the file name
670 unsigned FilenameLen = Record[Idx++];
671 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
672 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000673 MaybeAddSystemRootToFilename(Filename);
Douglas Gregorff0a9872009-04-13 17:12:42 +0000674 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
675 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000676 }
677
678 // Parse the line entries
679 std::vector<LineEntry> Entries;
680 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000681 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000682
683 // Extract the line entries
684 unsigned NumEntries = Record[Idx++];
685 Entries.clear();
686 Entries.reserve(NumEntries);
687 for (unsigned I = 0; I != NumEntries; ++I) {
688 unsigned FileOffset = Record[Idx++];
689 unsigned LineNo = Record[Idx++];
690 int FilenameID = Record[Idx++];
691 SrcMgr::CharacteristicKind FileKind
692 = (SrcMgr::CharacteristicKind)Record[Idx++];
693 unsigned IncludeOffset = Record[Idx++];
694 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
695 FileKind, IncludeOffset));
696 }
697 LineTable.AddEntry(FID, Entries);
698 }
699
700 return false;
701}
702
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000703namespace {
704
705class VISIBILITY_HIDDEN PCHStatData {
706public:
707 const bool hasStat;
708 const ino_t ino;
709 const dev_t dev;
710 const mode_t mode;
711 const time_t mtime;
712 const off_t size;
713
714 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
715 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
716
717 PCHStatData()
718 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
719};
720
721class VISIBILITY_HIDDEN PCHStatLookupTrait {
722 public:
723 typedef const char *external_key_type;
724 typedef const char *internal_key_type;
725
726 typedef PCHStatData data_type;
727
728 static unsigned ComputeHash(const char *path) {
729 return BernsteinHash(path);
730 }
731
732 static internal_key_type GetInternalKey(const char *path) { return path; }
733
734 static bool EqualKey(internal_key_type a, internal_key_type b) {
735 return strcmp(a, b) == 0;
736 }
737
738 static std::pair<unsigned, unsigned>
739 ReadKeyDataLength(const unsigned char*& d) {
740 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
741 unsigned DataLen = (unsigned) *d++;
742 return std::make_pair(KeyLen + 1, DataLen);
743 }
744
745 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
746 return (const char *)d;
747 }
748
749 static data_type ReadData(const internal_key_type, const unsigned char *d,
750 unsigned /*DataLen*/) {
751 using namespace clang::io;
752
753 if (*d++ == 1)
754 return data_type();
755
756 ino_t ino = (ino_t) ReadUnalignedLE32(d);
757 dev_t dev = (dev_t) ReadUnalignedLE32(d);
758 mode_t mode = (mode_t) ReadUnalignedLE16(d);
759 time_t mtime = (time_t) ReadUnalignedLE64(d);
760 off_t size = (off_t) ReadUnalignedLE64(d);
761 return data_type(ino, dev, mode, mtime, size);
762 }
763};
764
765/// \brief stat() cache for precompiled headers.
766///
767/// This cache is very similar to the stat cache used by pretokenized
768/// headers.
769class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
770 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
771 CacheTy *Cache;
772
773 unsigned &NumStatHits, &NumStatMisses;
774public:
775 PCHStatCache(const unsigned char *Buckets,
776 const unsigned char *Base,
777 unsigned &NumStatHits,
778 unsigned &NumStatMisses)
779 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
780 Cache = CacheTy::Create(Buckets, Base);
781 }
782
783 ~PCHStatCache() { delete Cache; }
784
785 int stat(const char *path, struct stat *buf) {
786 // Do the lookup for the file's data in the PCH file.
787 CacheTy::iterator I = Cache->find(path);
788
789 // If we don't get a hit in the PCH file just forward to 'stat'.
790 if (I == Cache->end()) {
791 ++NumStatMisses;
792 return ::stat(path, buf);
793 }
794
795 ++NumStatHits;
796 PCHStatData Data = *I;
797
798 if (!Data.hasStat)
799 return 1;
800
801 buf->st_ino = Data.ino;
802 buf->st_dev = Data.dev;
803 buf->st_mtime = Data.mtime;
804 buf->st_mode = Data.mode;
805 buf->st_size = Data.size;
806 return 0;
807 }
808};
809} // end anonymous namespace
810
811
Douglas Gregor14f79002009-04-10 03:52:48 +0000812/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000813PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000814 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000815
816 // Set the source-location entry cursor to the current position in
817 // the stream. This cursor will be used to read the contents of the
818 // source manager block initially, and then lazily read
819 // source-location entries as needed.
820 SLocEntryCursor = Stream;
821
822 // The stream itself is going to skip over the source manager block.
823 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000824 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000825 return Failure;
826 }
827
828 // Enter the source manager block.
829 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000830 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000831 return Failure;
832 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000833
Douglas Gregor14f79002009-04-10 03:52:48 +0000834 RecordData Record;
835 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000836 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000837 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000838 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000839 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000840 return Failure;
841 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000842 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000843 }
844
845 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
846 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000847 SLocEntryCursor.ReadSubBlockID();
848 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000849 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000850 return Failure;
851 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000852 continue;
853 }
854
855 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000856 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000857 continue;
858 }
859
860 // Read a record.
861 const char *BlobStart;
862 unsigned BlobLen;
863 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000864 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000865 default: // Default behavior: ignore.
866 break;
867
Chris Lattner2c78b872009-04-14 23:22:57 +0000868 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000869 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000870 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000871 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000872
873 case pch::SM_HEADER_FILE_INFO: {
874 HeaderFileInfo HFI;
875 HFI.isImport = Record[0];
876 HFI.DirInfo = Record[1];
877 HFI.NumIncludes = Record[2];
878 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000879 if (Listener)
880 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000881 break;
882 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000883
884 case pch::SM_SLOC_FILE_ENTRY:
885 case pch::SM_SLOC_BUFFER_ENTRY:
886 case pch::SM_SLOC_INSTANTIATION_ENTRY:
887 // Once we hit one of the source location entries, we're done.
888 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000889 }
890 }
891}
892
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000893/// \brief Read in the source location entry with the given ID.
894PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
895 if (ID == 0)
896 return Success;
897
898 if (ID > TotalNumSLocEntries) {
899 Error("source location entry ID out-of-range for PCH file");
900 return Failure;
901 }
902
903 ++NumSLocEntriesRead;
904 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
905 unsigned Code = SLocEntryCursor.ReadCode();
906 if (Code == llvm::bitc::END_BLOCK ||
907 Code == llvm::bitc::ENTER_SUBBLOCK ||
908 Code == llvm::bitc::DEFINE_ABBREV) {
909 Error("incorrectly-formatted source location entry in PCH file");
910 return Failure;
911 }
912
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000913 RecordData Record;
914 const char *BlobStart;
915 unsigned BlobLen;
916 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
917 default:
918 Error("incorrectly-formatted source location entry in PCH file");
919 return Failure;
920
921 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000922 std::string Filename(BlobStart, BlobStart + BlobLen);
923 MaybeAddSystemRootToFilename(Filename);
924 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000925 if (File == 0) {
926 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000927 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000928 ErrorStr += "' referenced by PCH file";
929 Error(ErrorStr.c_str());
930 return Failure;
931 }
932
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000933 FileID FID = SourceMgr.createFileID(File,
934 SourceLocation::getFromRawEncoding(Record[1]),
935 (SrcMgr::CharacteristicKind)Record[2],
936 ID, Record[0]);
937 if (Record[3])
938 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
939 .setHasLineDirectives();
940
941 break;
942 }
943
944 case pch::SM_SLOC_BUFFER_ENTRY: {
945 const char *Name = BlobStart;
946 unsigned Offset = Record[0];
947 unsigned Code = SLocEntryCursor.ReadCode();
948 Record.clear();
949 unsigned RecCode
950 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
951 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
952 (void)RecCode;
953 llvm::MemoryBuffer *Buffer
954 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
955 BlobStart + BlobLen - 1,
956 Name);
957 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
958
Douglas Gregor92b059e2009-04-28 20:33:11 +0000959 if (strcmp(Name, "<built-in>") == 0) {
960 PCHPredefinesBufferID = BufferID;
961 PCHPredefines = BlobStart;
962 PCHPredefinesLen = BlobLen - 1;
963 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000964
965 break;
966 }
967
968 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
969 SourceLocation SpellingLoc
970 = SourceLocation::getFromRawEncoding(Record[1]);
971 SourceMgr.createInstantiationLoc(SpellingLoc,
972 SourceLocation::getFromRawEncoding(Record[2]),
973 SourceLocation::getFromRawEncoding(Record[3]),
974 Record[4],
975 ID,
976 Record[0]);
977 break;
978 }
979 }
980
981 return Success;
982}
983
Chris Lattner6367f6d2009-04-27 01:05:14 +0000984/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
985/// specified cursor. Read the abbreviations that are at the top of the block
986/// and then leave the cursor pointing into the block.
987bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
988 unsigned BlockID) {
989 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000990 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000991 return Failure;
992 }
993
Chris Lattner6367f6d2009-04-27 01:05:14 +0000994 while (true) {
995 unsigned Code = Cursor.ReadCode();
996
997 // We expect all abbrevs to be at the start of the block.
998 if (Code != llvm::bitc::DEFINE_ABBREV)
999 return false;
1000 Cursor.ReadAbbrevRecord();
1001 }
1002}
1003
Douglas Gregor37e26842009-04-21 23:56:24 +00001004void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001005 assert(PP && "Forgot to set Preprocessor ?");
1006
Douglas Gregor37e26842009-04-21 23:56:24 +00001007 // Keep track of where we are in the stream, then jump back there
1008 // after reading this macro.
1009 SavedStreamPosition SavedPosition(Stream);
1010
1011 Stream.JumpToBit(Offset);
1012 RecordData Record;
1013 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1014 MacroInfo *Macro = 0;
Steve Naroff83d63c72009-04-24 20:03:17 +00001015
Douglas Gregor37e26842009-04-21 23:56:24 +00001016 while (true) {
1017 unsigned Code = Stream.ReadCode();
1018 switch (Code) {
1019 case llvm::bitc::END_BLOCK:
1020 return;
1021
1022 case llvm::bitc::ENTER_SUBBLOCK:
1023 // No known subblocks, always skip them.
1024 Stream.ReadSubBlockID();
1025 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001026 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001027 return;
1028 }
1029 continue;
1030
1031 case llvm::bitc::DEFINE_ABBREV:
1032 Stream.ReadAbbrevRecord();
1033 continue;
1034 default: break;
1035 }
1036
1037 // Read a record.
1038 Record.clear();
1039 pch::PreprocessorRecordTypes RecType =
1040 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1041 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001042 case pch::PP_MACRO_OBJECT_LIKE:
1043 case pch::PP_MACRO_FUNCTION_LIKE: {
1044 // If we already have a macro, that means that we've hit the end
1045 // of the definition of the macro we were looking for. We're
1046 // done.
1047 if (Macro)
1048 return;
1049
1050 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1051 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001052 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001053 return;
1054 }
1055 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1056 bool isUsed = Record[2];
1057
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001058 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001059 MI->setIsUsed(isUsed);
1060
1061 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1062 // Decode function-like macro info.
1063 bool isC99VarArgs = Record[3];
1064 bool isGNUVarArgs = Record[4];
1065 MacroArgs.clear();
1066 unsigned NumArgs = Record[5];
1067 for (unsigned i = 0; i != NumArgs; ++i)
1068 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1069
1070 // Install function-like macro info.
1071 MI->setIsFunctionLike();
1072 if (isC99VarArgs) MI->setIsC99Varargs();
1073 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001074 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001075 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001076 }
1077
1078 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001079 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001080
1081 // Remember that we saw this macro last so that we add the tokens that
1082 // form its body to it.
1083 Macro = MI;
1084 ++NumMacrosRead;
1085 break;
1086 }
1087
1088 case pch::PP_TOKEN: {
1089 // If we see a TOKEN before a PP_MACRO_*, then the file is
1090 // erroneous, just pretend we didn't see this.
1091 if (Macro == 0) break;
1092
1093 Token Tok;
1094 Tok.startToken();
1095 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1096 Tok.setLength(Record[1]);
1097 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1098 Tok.setIdentifierInfo(II);
1099 Tok.setKind((tok::TokenKind)Record[3]);
1100 Tok.setFlag((Token::TokenFlags)Record[4]);
1101 Macro->AddTokenToBody(Tok);
1102 break;
1103 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001104 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001105 }
1106}
1107
Douglas Gregore650c8c2009-07-07 00:12:59 +00001108/// \brief If we are loading a relocatable PCH file, and the filename is
1109/// not an absolute path, add the system root to the beginning of the file
1110/// name.
1111void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1112 // If this is not a relocatable PCH file, there's nothing to do.
1113 if (!RelocatablePCH)
1114 return;
1115
1116 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1117 return;
1118
1119 std::string FIXME = Filename;
1120
1121 if (isysroot == 0) {
1122 // If no system root was given, default to '/'
1123 Filename.insert(Filename.begin(), '/');
1124 return;
1125 }
1126
1127 unsigned Length = strlen(isysroot);
1128 if (isysroot[Length - 1] != '/')
1129 Filename.insert(Filename.begin(), '/');
1130
1131 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1132}
1133
Douglas Gregor668c1a42009-04-21 22:25:48 +00001134PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001135PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001136 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001137 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001138 return Failure;
1139 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001140
1141 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001142 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001143 while (!Stream.AtEndOfStream()) {
1144 unsigned Code = Stream.ReadCode();
1145 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001146 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001147 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001148 return Failure;
1149 }
Chris Lattner7356a312009-04-11 21:15:38 +00001150
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001151 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001152 }
1153
1154 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1155 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001156 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1157 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001158 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001159 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001160 return Failure;
1161 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001162 break;
1163
Chris Lattner6367f6d2009-04-27 01:05:14 +00001164 case pch::DECLS_BLOCK_ID:
1165 // We lazily load the decls block, but we want to set up the
1166 // DeclsCursor cursor to point into it. Clone our current bitcode
1167 // cursor to it, enter the block and read the abbrevs in that block.
1168 // With the main cursor, we just skip over it.
1169 DeclsCursor = Stream;
1170 if (Stream.SkipBlock() || // Skip with the main cursor.
1171 // Read the abbrevs.
1172 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001173 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001174 return Failure;
1175 }
1176 break;
1177
Chris Lattner7356a312009-04-11 21:15:38 +00001178 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001179 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001180 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001181 return Failure;
1182 }
1183 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001184
Douglas Gregor14f79002009-04-10 03:52:48 +00001185 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001186 switch (ReadSourceManagerBlock()) {
1187 case Success:
1188 break;
1189
1190 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001191 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001192 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001193
1194 case IgnorePCH:
1195 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001196 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001197 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001198 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001199 continue;
1200 }
1201
1202 if (Code == llvm::bitc::DEFINE_ABBREV) {
1203 Stream.ReadAbbrevRecord();
1204 continue;
1205 }
1206
1207 // Read and process a record.
1208 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001209 const char *BlobStart = 0;
1210 unsigned BlobLen = 0;
1211 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1212 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001213 default: // Default behavior: ignore.
1214 break;
1215
1216 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001217 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001218 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001219 return Failure;
1220 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001221 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001222 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001223 break;
1224
1225 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001226 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001227 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001228 return Failure;
1229 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001230 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001231 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001232 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001233
1234 case pch::LANGUAGE_OPTIONS:
1235 if (ParseLanguageOptions(Record))
1236 return IgnorePCH;
1237 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001238
Douglas Gregorab41e632009-04-27 22:23:34 +00001239 case pch::METADATA: {
1240 if (Record[0] != pch::VERSION_MAJOR) {
1241 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1242 : diag::warn_pch_version_too_new);
1243 return IgnorePCH;
1244 }
1245
Douglas Gregore650c8c2009-07-07 00:12:59 +00001246 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001247 if (Listener) {
1248 std::string TargetTriple(BlobStart, BlobLen);
1249 if (Listener->ReadTargetTriple(TargetTriple))
1250 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001251 }
1252 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001253 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001254
1255 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001256 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001257 if (Record[0]) {
1258 IdentifierLookupTable
1259 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001260 (const unsigned char *)IdentifierTableData + Record[0],
1261 (const unsigned char *)IdentifierTableData,
1262 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001263 if (PP)
1264 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001265 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001266 break;
1267
1268 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001269 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001270 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001271 return Failure;
1272 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001273 IdentifierOffsets = (const uint32_t *)BlobStart;
1274 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001275 if (PP)
1276 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001277 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001278
1279 case pch::EXTERNAL_DEFINITIONS:
1280 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001281 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001282 return Failure;
1283 }
1284 ExternalDefinitions.swap(Record);
1285 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001286
Douglas Gregorad1de002009-04-18 05:55:16 +00001287 case pch::SPECIAL_TYPES:
1288 SpecialTypes.swap(Record);
1289 break;
1290
Douglas Gregor3e1af842009-04-17 22:13:46 +00001291 case pch::STATISTICS:
1292 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001293 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001294 TotalLexicalDeclContexts = Record[2];
1295 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001296 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001297
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001298 case pch::TENTATIVE_DEFINITIONS:
1299 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001300 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001301 return Failure;
1302 }
1303 TentativeDefinitions.swap(Record);
1304 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001305
1306 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1307 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001308 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001309 return Failure;
1310 }
1311 LocallyScopedExternalDecls.swap(Record);
1312 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001313
Douglas Gregor83941df2009-04-25 17:48:32 +00001314 case pch::SELECTOR_OFFSETS:
1315 SelectorOffsets = (const uint32_t *)BlobStart;
1316 TotalNumSelectors = Record[0];
1317 SelectorsLoaded.resize(TotalNumSelectors);
1318 break;
1319
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001320 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001321 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1322 if (Record[0])
1323 MethodPoolLookupTable
1324 = PCHMethodPoolLookupTable::Create(
1325 MethodPoolLookupTableData + Record[0],
1326 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001327 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001328 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001329 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001330
1331 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001332 if (!Record.empty() && Listener)
1333 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001334 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001335
1336 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001337 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001338 TotalNumSLocEntries = Record[0];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001339 SourceMgr.PreallocateSLocEntries(this,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001340 TotalNumSLocEntries,
1341 Record[1]);
1342 break;
1343
1344 case pch::SOURCE_LOCATION_PRELOADS:
1345 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1346 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1347 if (Result != Success)
1348 return Result;
1349 }
1350 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001351
1352 case pch::STAT_CACHE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001353 FileMgr.setStatCache(
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001354 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1355 (const unsigned char *)BlobStart,
1356 NumStatHits, NumStatMisses));
1357 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001358
1359 case pch::EXT_VECTOR_DECLS:
1360 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001361 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001362 return Failure;
1363 }
1364 ExtVectorDecls.swap(Record);
1365 break;
1366
Douglas Gregorb64c1932009-05-12 01:31:05 +00001367 case pch::ORIGINAL_FILE_NAME:
1368 OriginalFileName.assign(BlobStart, BlobLen);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001369 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001370 break;
Douglas Gregor2e222532009-07-02 17:08:52 +00001371
1372 case pch::COMMENT_RANGES:
1373 Comments = (SourceRange *)BlobStart;
1374 NumComments = BlobLen / sizeof(SourceRange);
1375 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001376 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001377 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001378 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001379 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001380}
1381
Douglas Gregore1d918e2009-04-10 23:10:45 +00001382PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001383 // Set the PCH file name.
1384 this->FileName = FileName;
1385
Douglas Gregor2cf26342009-04-09 22:27:44 +00001386 // Open the PCH file.
1387 std::string ErrStr;
1388 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001389 if (!Buffer) {
1390 Error(ErrStr.c_str());
1391 return IgnorePCH;
1392 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001393
1394 // Initialize the stream
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001395 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1396 (const unsigned char *)Buffer->getBufferEnd());
1397 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001398
1399 // Sniff for the signature.
1400 if (Stream.Read(8) != 'C' ||
1401 Stream.Read(8) != 'P' ||
1402 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001403 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001404 Diag(diag::err_not_a_pch_file) << FileName;
1405 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001406 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001407
Douglas Gregor2cf26342009-04-09 22:27:44 +00001408 while (!Stream.AtEndOfStream()) {
1409 unsigned Code = Stream.ReadCode();
1410
Douglas Gregore1d918e2009-04-10 23:10:45 +00001411 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001412 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001413 return Failure;
1414 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001415
1416 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001417
Douglas Gregor2cf26342009-04-09 22:27:44 +00001418 // We only know the PCH subblock ID.
1419 switch (BlockID) {
1420 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001421 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001422 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001423 return Failure;
1424 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001425 break;
1426 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001427 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001428 case Success:
1429 break;
1430
1431 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001432 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001433
1434 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001435 // FIXME: We could consider reading through to the end of this
1436 // PCH block, skipping subblocks, to see if there are other
1437 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001438
1439 // Clear out any preallocated source location entries, so that
1440 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001441 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001442
1443 // Remove the stat cache.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001444 FileMgr.setStatCache(0);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001445
Douglas Gregore1d918e2009-04-10 23:10:45 +00001446 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001447 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001448 break;
1449 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001450 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001451 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001452 return Failure;
1453 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001454 break;
1455 }
1456 }
Douglas Gregor92b059e2009-04-28 20:33:11 +00001457
1458 // Check the predefines buffer.
1459 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1460 PCHPredefinesBufferID))
1461 return IgnorePCH;
1462
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001463 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001464 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001465 // PCH file is read, so there may be some identifiers that were
1466 // loaded into the IdentifierTable before we intercepted the
1467 // creation of identifiers. Iterate through the list of known
1468 // identifiers and determine whether we have to establish
1469 // preprocessor definitions or top-level identifier declaration
1470 // chains for those identifiers.
1471 //
1472 // We copy the IdentifierInfo pointers to a small vector first,
1473 // since de-serializing declarations or macro definitions can add
1474 // new entries into the identifier table, invalidating the
1475 // iterators.
1476 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1477 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1478 IdEnd = PP->getIdentifierTable().end();
1479 Id != IdEnd; ++Id)
1480 Identifiers.push_back(Id->second);
1481 PCHIdentifierLookupTable *IdTable
1482 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1483 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1484 IdentifierInfo *II = Identifiers[I];
1485 // Look in the on-disk hash table for an entry for
1486 PCHIdentifierLookupTrait Info(*this, II);
1487 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1488 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1489 if (Pos == IdTable->end())
1490 continue;
1491
1492 // Dereferencing the iterator has the effect of populating the
1493 // IdentifierInfo node with the various declarations it needs.
1494 (void)*Pos;
1495 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001496 }
1497
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001498 if (Context)
1499 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001500
Douglas Gregor668c1a42009-04-21 22:25:48 +00001501 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001502}
1503
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001504void PCHReader::InitializeContext(ASTContext &Ctx) {
1505 Context = &Ctx;
1506 assert(Context && "Passed null context!");
1507
1508 assert(PP && "Forgot to set Preprocessor ?");
1509 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1510 PP->getHeaderSearchInfo().SetExternalLookup(this);
1511
1512 // Load the translation unit declaration
1513 ReadDeclRecord(DeclOffsets[0], 0);
1514
1515 // Load the special types.
1516 Context->setBuiltinVaListType(
1517 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1518 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1519 Context->setObjCIdType(GetType(Id));
1520 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1521 Context->setObjCSelType(GetType(Sel));
1522 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1523 Context->setObjCProtoType(GetType(Proto));
1524 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1525 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001526
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001527 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1528 Context->setCFConstantStringType(GetType(String));
1529 if (unsigned FastEnum
1530 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1531 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001532 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1533 QualType FileType = GetType(File);
1534 assert(!FileType.isNull() && "FILE type is NULL");
1535 if (const TypedefType *Typedef = FileType->getAsTypedefType())
1536 Context->setFILEDecl(Typedef->getDecl());
1537 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001538 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001539 assert(Tag && "Invalid FILE type in PCH file");
1540 Context->setFILEDecl(Tag->getDecl());
1541 }
1542 }
Mike Stump782fa302009-07-28 02:25:19 +00001543 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1544 QualType Jmp_bufType = GetType(Jmp_buf);
1545 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
1546 if (const TypedefType *Typedef = Jmp_bufType->getAsTypedefType())
1547 Context->setjmp_bufDecl(Typedef->getDecl());
1548 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001549 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001550 assert(Tag && "Invalid jmp_bug type in PCH file");
1551 Context->setjmp_bufDecl(Tag->getDecl());
1552 }
1553 }
1554 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1555 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1556 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
1557 if (const TypedefType *Typedef = Sigjmp_bufType->getAsTypedefType())
1558 Context->setsigjmp_bufDecl(Typedef->getDecl());
1559 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001560 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001561 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1562 Context->setsigjmp_bufDecl(Tag->getDecl());
1563 }
1564 }
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001565}
1566
Douglas Gregorb64c1932009-05-12 01:31:05 +00001567/// \brief Retrieve the name of the original source file name
1568/// directly from the PCH file, without actually loading the PCH
1569/// file.
1570std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1571 // Open the PCH file.
1572 std::string ErrStr;
1573 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1574 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1575 if (!Buffer) {
1576 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1577 return std::string();
1578 }
1579
1580 // Initialize the stream
1581 llvm::BitstreamReader StreamFile;
1582 llvm::BitstreamCursor Stream;
1583 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1584 (const unsigned char *)Buffer->getBufferEnd());
1585 Stream.init(StreamFile);
1586
1587 // Sniff for the signature.
1588 if (Stream.Read(8) != 'C' ||
1589 Stream.Read(8) != 'P' ||
1590 Stream.Read(8) != 'C' ||
1591 Stream.Read(8) != 'H') {
1592 fprintf(stderr,
1593 "error: '%s' does not appear to be a precompiled header file\n",
1594 PCHFileName.c_str());
1595 return std::string();
1596 }
1597
1598 RecordData Record;
1599 while (!Stream.AtEndOfStream()) {
1600 unsigned Code = Stream.ReadCode();
1601
1602 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1603 unsigned BlockID = Stream.ReadSubBlockID();
1604
1605 // We only know the PCH subblock ID.
1606 switch (BlockID) {
1607 case pch::PCH_BLOCK_ID:
1608 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1609 fprintf(stderr, "error: malformed block record in PCH file\n");
1610 return std::string();
1611 }
1612 break;
1613
1614 default:
1615 if (Stream.SkipBlock()) {
1616 fprintf(stderr, "error: malformed block record in PCH file\n");
1617 return std::string();
1618 }
1619 break;
1620 }
1621 continue;
1622 }
1623
1624 if (Code == llvm::bitc::END_BLOCK) {
1625 if (Stream.ReadBlockEnd()) {
1626 fprintf(stderr, "error: error at end of module block in PCH file\n");
1627 return std::string();
1628 }
1629 continue;
1630 }
1631
1632 if (Code == llvm::bitc::DEFINE_ABBREV) {
1633 Stream.ReadAbbrevRecord();
1634 continue;
1635 }
1636
1637 Record.clear();
1638 const char *BlobStart = 0;
1639 unsigned BlobLen = 0;
1640 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
1641 == pch::ORIGINAL_FILE_NAME)
1642 return std::string(BlobStart, BlobLen);
1643 }
1644
1645 return std::string();
1646}
1647
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001648/// \brief Parse the record that corresponds to a LangOptions data
1649/// structure.
1650///
1651/// This routine compares the language options used to generate the
1652/// PCH file against the language options set for the current
1653/// compilation. For each option, we classify differences between the
1654/// two compiler states as either "benign" or "important". Benign
1655/// differences don't matter, and we accept them without complaint
1656/// (and without modifying the language options). Differences between
1657/// the states for important options cause the PCH file to be
1658/// unusable, so we emit a warning and return true to indicate that
1659/// there was an error.
1660///
1661/// \returns true if the PCH file is unacceptable, false otherwise.
1662bool PCHReader::ParseLanguageOptions(
1663 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001664 if (Listener) {
1665 LangOptions LangOpts;
1666
1667 #define PARSE_LANGOPT(Option) \
1668 LangOpts.Option = Record[Idx]; \
1669 ++Idx
1670
1671 unsigned Idx = 0;
1672 PARSE_LANGOPT(Trigraphs);
1673 PARSE_LANGOPT(BCPLComment);
1674 PARSE_LANGOPT(DollarIdents);
1675 PARSE_LANGOPT(AsmPreprocessor);
1676 PARSE_LANGOPT(GNUMode);
1677 PARSE_LANGOPT(ImplicitInt);
1678 PARSE_LANGOPT(Digraphs);
1679 PARSE_LANGOPT(HexFloats);
1680 PARSE_LANGOPT(C99);
1681 PARSE_LANGOPT(Microsoft);
1682 PARSE_LANGOPT(CPlusPlus);
1683 PARSE_LANGOPT(CPlusPlus0x);
1684 PARSE_LANGOPT(CXXOperatorNames);
1685 PARSE_LANGOPT(ObjC1);
1686 PARSE_LANGOPT(ObjC2);
1687 PARSE_LANGOPT(ObjCNonFragileABI);
1688 PARSE_LANGOPT(PascalStrings);
1689 PARSE_LANGOPT(WritableStrings);
1690 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001691 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001692 PARSE_LANGOPT(Exceptions);
1693 PARSE_LANGOPT(NeXTRuntime);
1694 PARSE_LANGOPT(Freestanding);
1695 PARSE_LANGOPT(NoBuiltin);
1696 PARSE_LANGOPT(ThreadsafeStatics);
1697 PARSE_LANGOPT(Blocks);
1698 PARSE_LANGOPT(EmitAllDecls);
1699 PARSE_LANGOPT(MathErrno);
1700 PARSE_LANGOPT(OverflowChecking);
1701 PARSE_LANGOPT(HeinousExtensions);
1702 PARSE_LANGOPT(Optimize);
1703 PARSE_LANGOPT(OptimizeSize);
1704 PARSE_LANGOPT(Static);
1705 PARSE_LANGOPT(PICLevel);
1706 PARSE_LANGOPT(GNUInline);
1707 PARSE_LANGOPT(NoInline);
1708 PARSE_LANGOPT(AccessControl);
1709 PARSE_LANGOPT(CharIsSigned);
1710 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1711 ++Idx;
1712 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1713 ++Idx;
1714 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001715 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001716 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001717
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001718 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001719 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001720
1721 return false;
1722}
1723
Douglas Gregor2e222532009-07-02 17:08:52 +00001724void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1725 Comments.resize(NumComments);
1726 std::copy(this->Comments, this->Comments + NumComments,
1727 Comments.begin());
1728}
1729
Douglas Gregor2cf26342009-04-09 22:27:44 +00001730/// \brief Read and return the type at the given offset.
1731///
1732/// This routine actually reads the record corresponding to the type
1733/// at the given offset in the bitstream. It is a helper routine for
1734/// GetType, which deals with reading type IDs.
1735QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001736 // Keep track of where we are in the stream, then jump back there
1737 // after reading this type.
1738 SavedStreamPosition SavedPosition(Stream);
1739
Douglas Gregord89275b2009-07-06 18:54:52 +00001740 // Note that we are loading a type record.
1741 LoadingTypeOrDecl Loading(*this);
1742
Douglas Gregor2cf26342009-04-09 22:27:44 +00001743 Stream.JumpToBit(Offset);
1744 RecordData Record;
1745 unsigned Code = Stream.ReadCode();
1746 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001747 case pch::TYPE_EXT_QUAL: {
1748 assert(Record.size() == 3 &&
1749 "Incorrect encoding of extended qualifier type");
1750 QualType Base = GetType(Record[0]);
1751 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1752 unsigned AddressSpace = Record[2];
1753
1754 QualType T = Base;
1755 if (GCAttr != QualType::GCNone)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001756 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor6d473962009-04-15 22:00:08 +00001757 if (AddressSpace)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001758 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor6d473962009-04-15 22:00:08 +00001759 return T;
1760 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001761
Douglas Gregor2cf26342009-04-09 22:27:44 +00001762 case pch::TYPE_FIXED_WIDTH_INT: {
1763 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001764 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001765 }
1766
1767 case pch::TYPE_COMPLEX: {
1768 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1769 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001770 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001771 }
1772
1773 case pch::TYPE_POINTER: {
1774 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1775 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001776 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001777 }
1778
1779 case pch::TYPE_BLOCK_POINTER: {
1780 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1781 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001782 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001783 }
1784
1785 case pch::TYPE_LVALUE_REFERENCE: {
1786 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1787 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001788 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001789 }
1790
1791 case pch::TYPE_RVALUE_REFERENCE: {
1792 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1793 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001794 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001795 }
1796
1797 case pch::TYPE_MEMBER_POINTER: {
1798 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1799 QualType PointeeType = GetType(Record[0]);
1800 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001801 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001802 }
1803
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001804 case pch::TYPE_CONSTANT_ARRAY: {
1805 QualType ElementType = GetType(Record[0]);
1806 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1807 unsigned IndexTypeQuals = Record[2];
1808 unsigned Idx = 3;
1809 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001810 return Context->getConstantArrayType(ElementType, Size,
1811 ASM, IndexTypeQuals);
1812 }
1813
1814 case pch::TYPE_CONSTANT_ARRAY_WITH_EXPR: {
1815 QualType ElementType = GetType(Record[0]);
1816 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1817 unsigned IndexTypeQuals = Record[2];
1818 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1819 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
1820 unsigned Idx = 5;
1821 llvm::APInt Size = ReadAPInt(Record, Idx);
1822 return Context->getConstantArrayWithExprType(ElementType,
1823 Size, ReadTypeExpr(),
1824 ASM, IndexTypeQuals,
1825 SourceRange(LBLoc, RBLoc));
1826 }
1827
1828 case pch::TYPE_CONSTANT_ARRAY_WITHOUT_EXPR: {
1829 QualType ElementType = GetType(Record[0]);
1830 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1831 unsigned IndexTypeQuals = Record[2];
1832 unsigned Idx = 3;
1833 llvm::APInt Size = ReadAPInt(Record, Idx);
1834 return Context->getConstantArrayWithoutExprType(ElementType, Size,
1835 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001836 }
1837
1838 case pch::TYPE_INCOMPLETE_ARRAY: {
1839 QualType ElementType = GetType(Record[0]);
1840 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1841 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001842 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001843 }
1844
1845 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001846 QualType ElementType = GetType(Record[0]);
1847 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1848 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001849 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1850 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001851 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001852 ASM, IndexTypeQuals,
1853 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001854 }
1855
1856 case pch::TYPE_VECTOR: {
1857 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001858 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001859 return QualType();
1860 }
1861
1862 QualType ElementType = GetType(Record[0]);
1863 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001864 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001865 }
1866
1867 case pch::TYPE_EXT_VECTOR: {
1868 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001869 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001870 return QualType();
1871 }
1872
1873 QualType ElementType = GetType(Record[0]);
1874 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001875 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001876 }
1877
1878 case pch::TYPE_FUNCTION_NO_PROTO: {
1879 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001880 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001881 return QualType();
1882 }
1883 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001884 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001885 }
1886
1887 case pch::TYPE_FUNCTION_PROTO: {
1888 QualType ResultType = GetType(Record[0]);
1889 unsigned Idx = 1;
1890 unsigned NumParams = Record[Idx++];
1891 llvm::SmallVector<QualType, 16> ParamTypes;
1892 for (unsigned I = 0; I != NumParams; ++I)
1893 ParamTypes.push_back(GetType(Record[Idx++]));
1894 bool isVariadic = Record[Idx++];
1895 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001896 bool hasExceptionSpec = Record[Idx++];
1897 bool hasAnyExceptionSpec = Record[Idx++];
1898 unsigned NumExceptions = Record[Idx++];
1899 llvm::SmallVector<QualType, 2> Exceptions;
1900 for (unsigned I = 0; I != NumExceptions; ++I)
1901 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001902 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001903 isVariadic, Quals, hasExceptionSpec,
1904 hasAnyExceptionSpec, NumExceptions,
1905 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001906 }
1907
1908 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001909 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001910 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001911
1912 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001913 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001914
1915 case pch::TYPE_TYPEOF: {
1916 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001917 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001918 return QualType();
1919 }
1920 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001921 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001922 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001923
1924 case pch::TYPE_DECLTYPE:
1925 return Context->getDecltypeType(ReadTypeExpr());
1926
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001927 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001928 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001929 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001930
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001931 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001932 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001933 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001934
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001935 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001936 unsigned Idx = 0;
1937 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1938 unsigned NumProtos = Record[Idx++];
1939 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1940 for (unsigned I = 0; I != NumProtos; ++I)
1941 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001942 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001943 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001944
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001945 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001946 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00001947 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001948 unsigned NumProtos = Record[Idx++];
1949 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1950 for (unsigned I = 0; I != NumProtos; ++I)
1951 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00001952 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001953 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001954 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001955 // Suppress a GCC warning
1956 return QualType();
1957}
1958
Douglas Gregor2cf26342009-04-09 22:27:44 +00001959
Douglas Gregor8038d512009-04-10 17:25:41 +00001960QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001961 unsigned Quals = ID & 0x07;
1962 unsigned Index = ID >> 3;
1963
1964 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1965 QualType T;
1966 switch ((pch::PredefinedTypeIDs)Index) {
1967 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001968 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1969 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001970
1971 case pch::PREDEF_TYPE_CHAR_U_ID:
1972 case pch::PREDEF_TYPE_CHAR_S_ID:
1973 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001974 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001975 break;
1976
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001977 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1978 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1979 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1980 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1981 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001982 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001983 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1984 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1985 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1986 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1987 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1988 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001989 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001990 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1991 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1992 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1993 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1994 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001995 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001996 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
1997 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00001998 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
1999 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002000 }
2001
2002 assert(!T.isNull() && "Unknown predefined type");
2003 return T.getQualifiedType(Quals);
2004 }
2005
2006 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002007 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002008 if (!TypesLoaded[Index])
2009 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregor2cf26342009-04-09 22:27:44 +00002010
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002011 return QualType(TypesLoaded[Index], Quals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002012}
2013
Douglas Gregor8038d512009-04-10 17:25:41 +00002014Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002015 if (ID == 0)
2016 return 0;
2017
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002018 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002019 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002020 return 0;
2021 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002022
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002023 unsigned Index = ID - 1;
2024 if (!DeclsLoaded[Index])
2025 ReadDeclRecord(DeclOffsets[Index], Index);
2026
2027 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002028}
2029
Chris Lattner887e2b32009-04-27 05:46:25 +00002030/// \brief Resolve the offset of a statement into a statement.
2031///
2032/// This operation will read a new statement from the external
2033/// source each time it is called, and is meant to be used via a
2034/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2035Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002036 // Since we know tha this statement is part of a decl, make sure to use the
2037 // decl cursor to read it.
2038 DeclsCursor.JumpToBit(Offset);
2039 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002040}
2041
Douglas Gregor2cf26342009-04-09 22:27:44 +00002042bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002043 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002044 assert(DC->hasExternalLexicalStorage() &&
2045 "DeclContext has no lexical decls in storage");
2046 uint64_t Offset = DeclContextOffsets[DC].first;
2047 assert(Offset && "DeclContext has no lexical decls in storage");
2048
Douglas Gregor0b748912009-04-14 21:18:50 +00002049 // Keep track of where we are in the stream, then jump back there
2050 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002051 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002052
Douglas Gregor2cf26342009-04-09 22:27:44 +00002053 // Load the record containing all of the declarations lexically in
2054 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002055 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002056 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002057 unsigned Code = DeclsCursor.ReadCode();
2058 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002059 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002060 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2061
2062 // Load all of the declaration IDs
2063 Decls.clear();
2064 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002065 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002066 return false;
2067}
2068
2069bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002070 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002071 assert(DC->hasExternalVisibleStorage() &&
2072 "DeclContext has no visible decls in storage");
2073 uint64_t Offset = DeclContextOffsets[DC].second;
2074 assert(Offset && "DeclContext has no visible decls in storage");
2075
Douglas Gregor0b748912009-04-14 21:18:50 +00002076 // Keep track of where we are in the stream, then jump back there
2077 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002078 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002079
Douglas Gregor2cf26342009-04-09 22:27:44 +00002080 // Load the record containing all of the declarations visible in
2081 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002082 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002083 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002084 unsigned Code = DeclsCursor.ReadCode();
2085 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002086 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002087 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2088 if (Record.size() == 0)
2089 return false;
2090
2091 Decls.clear();
2092
2093 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002094 while (Idx < Record.size()) {
2095 Decls.push_back(VisibleDeclaration());
2096 Decls.back().Name = ReadDeclarationName(Record, Idx);
2097
Douglas Gregor2cf26342009-04-09 22:27:44 +00002098 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002099 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002100 LoadedDecls.reserve(Size);
2101 for (unsigned I = 0; I < Size; ++I)
2102 LoadedDecls.push_back(Record[Idx++]);
2103 }
2104
Douglas Gregor25123082009-04-22 22:34:57 +00002105 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002106 return false;
2107}
2108
Douglas Gregorfdd01722009-04-14 00:24:19 +00002109void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002110 this->Consumer = Consumer;
2111
Douglas Gregorfdd01722009-04-14 00:24:19 +00002112 if (!Consumer)
2113 return;
2114
2115 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
2116 Decl *D = GetDecl(ExternalDefinitions[I]);
2117 DeclGroupRef DG(D);
2118 Consumer->HandleTopLevelDecl(DG);
2119 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002120
2121 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2122 DeclGroupRef DG(InterestingDecls[I]);
2123 Consumer->HandleTopLevelDecl(DG);
2124 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002125}
2126
Douglas Gregor2cf26342009-04-09 22:27:44 +00002127void PCHReader::PrintStats() {
2128 std::fprintf(stderr, "*** PCH Statistics:\n");
2129
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002130 unsigned NumTypesLoaded
2131 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
2132 (Type *)0);
2133 unsigned NumDeclsLoaded
2134 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2135 (Decl *)0);
2136 unsigned NumIdentifiersLoaded
2137 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2138 IdentifiersLoaded.end(),
2139 (IdentifierInfo *)0);
2140 unsigned NumSelectorsLoaded
2141 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2142 SelectorsLoaded.end(),
2143 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002144
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002145 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2146 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002147 if (TotalNumSLocEntries)
2148 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2149 NumSLocEntriesRead, TotalNumSLocEntries,
2150 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002151 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002152 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002153 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2154 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2155 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002156 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002157 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2158 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002159 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002160 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002161 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2162 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002163 if (TotalNumSelectors)
2164 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2165 NumSelectorsLoaded, TotalNumSelectors,
2166 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2167 if (TotalNumStatements)
2168 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2169 NumStatementsRead, TotalNumStatements,
2170 ((float)NumStatementsRead/TotalNumStatements * 100));
2171 if (TotalNumMacros)
2172 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2173 NumMacrosRead, TotalNumMacros,
2174 ((float)NumMacrosRead/TotalNumMacros * 100));
2175 if (TotalLexicalDeclContexts)
2176 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2177 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2178 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2179 * 100));
2180 if (TotalVisibleDeclContexts)
2181 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2182 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2183 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2184 * 100));
2185 if (TotalSelectorsInMethodPool) {
2186 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2187 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2188 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2189 * 100));
2190 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2191 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002192 std::fprintf(stderr, "\n");
2193}
2194
Douglas Gregor668c1a42009-04-21 22:25:48 +00002195void PCHReader::InitializeSema(Sema &S) {
2196 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002197 S.ExternalSource = this;
2198
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002199 // Makes sure any declarations that were deserialized "too early"
2200 // still get added to the identifier's declaration chains.
2201 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2202 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2203 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002204 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002205 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002206
2207 // If there were any tentative definitions, deserialize them and add
2208 // them to Sema's table of tentative definitions.
2209 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2210 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2211 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
2212 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002213
2214 // If there were any locally-scoped external declarations,
2215 // deserialize them and add them to Sema's table of locally-scoped
2216 // external declarations.
2217 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2218 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2219 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2220 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002221
2222 // If there were any ext_vector type declarations, deserialize them
2223 // and add them to Sema's vector of such declarations.
2224 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2225 SemaObj->ExtVectorDecls.push_back(
2226 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002227}
2228
2229IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2230 // Try to find this name within our on-disk hash table
2231 PCHIdentifierLookupTable *IdTable
2232 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2233 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2234 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2235 if (Pos == IdTable->end())
2236 return 0;
2237
2238 // Dereferencing the iterator has the effect of building the
2239 // IdentifierInfo node and populating it with the various
2240 // declarations it needs.
2241 return *Pos;
2242}
2243
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002244std::pair<ObjCMethodList, ObjCMethodList>
2245PCHReader::ReadMethodPool(Selector Sel) {
2246 if (!MethodPoolLookupTable)
2247 return std::pair<ObjCMethodList, ObjCMethodList>();
2248
2249 // Try to find this selector within our on-disk hash table.
2250 PCHMethodPoolLookupTable *PoolTable
2251 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2252 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002253 if (Pos == PoolTable->end()) {
2254 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002255 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002256 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002257
Douglas Gregor83941df2009-04-25 17:48:32 +00002258 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002259 return *Pos;
2260}
2261
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002262void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002263 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002264 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002265 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002266}
2267
Douglas Gregord89275b2009-07-06 18:54:52 +00002268/// \brief Set the globally-visible declarations associated with the given
2269/// identifier.
2270///
2271/// If the PCH reader is currently in a state where the given declaration IDs
2272/// cannot safely be resolved, they are queued until it is safe to resolve
2273/// them.
2274///
2275/// \param II an IdentifierInfo that refers to one or more globally-visible
2276/// declarations.
2277///
2278/// \param DeclIDs the set of declaration IDs with the name @p II that are
2279/// visible at global scope.
2280///
2281/// \param Nonrecursive should be true to indicate that the caller knows that
2282/// this call is non-recursive, and therefore the globally-visible declarations
2283/// will not be placed onto the pending queue.
2284void
2285PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
2286 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2287 bool Nonrecursive) {
2288 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2289 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2290 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2291 PII.II = II;
2292 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2293 PII.DeclIDs.push_back(DeclIDs[I]);
2294 return;
2295 }
2296
2297 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2298 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2299 if (SemaObj) {
2300 // Introduce this declaration into the translation-unit scope
2301 // and add it to the declaration chain for this identifier, so
2302 // that (unqualified) name lookup will find it.
2303 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2304 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2305 } else {
2306 // Queue this declaration so that it will be added to the
2307 // translation unit scope and identifier's declaration chain
2308 // once a Sema object is known.
2309 PreloadedDecls.push_back(D);
2310 }
2311 }
2312}
2313
Chris Lattner7356a312009-04-11 21:15:38 +00002314IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002315 if (ID == 0)
2316 return 0;
Chris Lattner7356a312009-04-11 21:15:38 +00002317
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002318 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002319 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002320 return 0;
2321 }
Chris Lattner7356a312009-04-11 21:15:38 +00002322
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002323 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002324 if (!IdentifiersLoaded[ID - 1]) {
2325 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002326 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002327
Douglas Gregor02fc7512009-04-28 20:01:51 +00002328 // All of the strings in the PCH file are preceded by a 16-bit
2329 // length. Extract that 16-bit length to avoid having to execute
2330 // strlen().
2331 const char *StrLenPtr = Str - 2;
2332 unsigned StrLen = (((unsigned) StrLenPtr[0])
2333 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2334 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002335 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002336 }
Chris Lattner7356a312009-04-11 21:15:38 +00002337
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002338 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002339}
2340
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002341void PCHReader::ReadSLocEntry(unsigned ID) {
2342 ReadSLocEntryRecord(ID);
2343}
2344
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002345Selector PCHReader::DecodeSelector(unsigned ID) {
2346 if (ID == 0)
2347 return Selector();
2348
Douglas Gregora02b1472009-04-28 21:53:25 +00002349 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002350 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002351
2352 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002353 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002354 return Selector();
2355 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002356
2357 unsigned Index = ID - 1;
2358 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2359 // Load this selector from the selector table.
2360 // FIXME: endianness portability issues with SelectorOffsets table
2361 PCHMethodPoolLookupTrait Trait(*this);
2362 SelectorsLoaded[Index]
2363 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2364 }
2365
2366 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002367}
2368
Douglas Gregor2cf26342009-04-09 22:27:44 +00002369DeclarationName
2370PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2371 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2372 switch (Kind) {
2373 case DeclarationName::Identifier:
2374 return DeclarationName(GetIdentifierInfo(Record, Idx));
2375
2376 case DeclarationName::ObjCZeroArgSelector:
2377 case DeclarationName::ObjCOneArgSelector:
2378 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002379 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002380
2381 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002382 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002383 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002384
2385 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002386 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002387 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002388
2389 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002390 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002391 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002392
2393 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002394 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002395 (OverloadedOperatorKind)Record[Idx++]);
2396
2397 case DeclarationName::CXXUsingDirective:
2398 return DeclarationName::getUsingDirectiveName();
2399 }
2400
2401 // Required to silence GCC warning
2402 return DeclarationName();
2403}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002404
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002405/// \brief Read an integral value
2406llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2407 unsigned BitWidth = Record[Idx++];
2408 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2409 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2410 Idx += NumWords;
2411 return Result;
2412}
2413
2414/// \brief Read a signed integral value
2415llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2416 bool isUnsigned = Record[Idx++];
2417 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2418}
2419
Douglas Gregor17fc2232009-04-14 21:55:33 +00002420/// \brief Read a floating-point value
2421llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002422 return llvm::APFloat(ReadAPInt(Record, Idx));
2423}
2424
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002425// \brief Read a string
2426std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2427 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002428 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002429 Idx += Len;
2430 return Result;
2431}
2432
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002433DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002434 return Diag(SourceLocation(), DiagID);
2435}
2436
2437DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002438 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002439}
Douglas Gregor025452f2009-04-17 00:04:06 +00002440
Douglas Gregor668c1a42009-04-21 22:25:48 +00002441/// \brief Retrieve the identifier table associated with the
2442/// preprocessor.
2443IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002444 assert(PP && "Forgot to set Preprocessor ?");
2445 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002446}
2447
Douglas Gregor025452f2009-04-17 00:04:06 +00002448/// \brief Record that the given ID maps to the given switch-case
2449/// statement.
2450void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2451 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2452 SwitchCaseStmts[ID] = SC;
2453}
2454
2455/// \brief Retrieve the switch-case statement with the given ID.
2456SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2457 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2458 return SwitchCaseStmts[ID];
2459}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002460
2461/// \brief Record that the given label statement has been
2462/// deserialized and has the given ID.
2463void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2464 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2465 "Deserialized label twice");
2466 LabelStmts[ID] = S;
2467
2468 // If we've already seen any goto statements that point to this
2469 // label, resolve them now.
2470 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2471 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2472 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2473 Goto->second->setLabel(S);
2474 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002475
2476 // If we've already seen any address-label statements that point to
2477 // this label, resolve them now.
2478 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2479 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2480 = UnresolvedAddrLabelExprs.equal_range(ID);
2481 for (AddrLabelIter AddrLabel = AddrLabels.first;
2482 AddrLabel != AddrLabels.second; ++AddrLabel)
2483 AddrLabel->second->setLabel(S);
2484 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002485}
2486
2487/// \brief Set the label of the given statement to the label
2488/// identified by ID.
2489///
2490/// Depending on the order in which the label and other statements
2491/// referencing that label occur, this operation may complete
2492/// immediately (updating the statement) or it may queue the
2493/// statement to be back-patched later.
2494void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2495 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2496 if (Label != LabelStmts.end()) {
2497 // We've already seen this label, so set the label of the goto and
2498 // we're done.
2499 S->setLabel(Label->second);
2500 } else {
2501 // We haven't seen this label yet, so add this goto to the set of
2502 // unresolved goto statements.
2503 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2504 }
2505}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002506
2507/// \brief Set the label of the given expression to the label
2508/// identified by ID.
2509///
2510/// Depending on the order in which the label and other statements
2511/// referencing that label occur, this operation may complete
2512/// immediately (updating the statement) or it may queue the
2513/// statement to be back-patched later.
2514void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2515 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2516 if (Label != LabelStmts.end()) {
2517 // We've already seen this label, so set the label of the
2518 // label-address expression and we're done.
2519 S->setLabel(Label->second);
2520 } else {
2521 // We haven't seen this label yet, so add this label-address
2522 // expression to the set of unresolved label-address expressions.
2523 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2524 }
2525}
Douglas Gregord89275b2009-07-06 18:54:52 +00002526
2527
2528PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
2529 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2530 Reader.CurrentlyLoadingTypeOrDecl = this;
2531}
2532
2533PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2534 if (!Parent) {
2535 // If any identifiers with corresponding top-level declarations have
2536 // been loaded, load those declarations now.
2537 while (!Reader.PendingIdentifierInfos.empty()) {
2538 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2539 Reader.PendingIdentifierInfos.front().DeclIDs,
2540 true);
2541 Reader.PendingIdentifierInfos.pop_front();
2542 }
2543 }
2544
2545 Reader.CurrentlyLoadingTypeOrDecl = Parent;
2546}