blob: 82e5033dd8b0fae2ce13f140c4a17dce559dcd4b [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"
John McCalla1ee0c52009-10-16 21:56:05 +000021#include "clang/AST/TypeLocVisitor.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000022#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000023#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000025#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000026#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000027#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000028#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000030#include "clang/Basic/Version.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000031#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000032#include "llvm/Bitcode/BitstreamReader.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/MemoryBuffer.h"
35#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000036#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000037#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000038#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000039using namespace clang;
40
41//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000042// PCH reader validator implementation
43//===----------------------------------------------------------------------===//
44
45PCHReaderListener::~PCHReaderListener() {}
46
47bool
48PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
49 const LangOptions &PPLangOpts = PP.getLangOptions();
50#define PARSE_LANGOPT_BENIGN(Option)
51#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
52 if (PPLangOpts.Option != LangOpts.Option) { \
53 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
54 return true; \
55 }
56
57 PARSE_LANGOPT_BENIGN(Trigraphs);
58 PARSE_LANGOPT_BENIGN(BCPLComment);
59 PARSE_LANGOPT_BENIGN(DollarIdents);
60 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
61 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
62 PARSE_LANGOPT_BENIGN(ImplicitInt);
63 PARSE_LANGOPT_BENIGN(Digraphs);
64 PARSE_LANGOPT_BENIGN(HexFloats);
65 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
66 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
67 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
68 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
69 PARSE_LANGOPT_BENIGN(CXXOperatorName);
70 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
71 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
72 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
73 PARSE_LANGOPT_BENIGN(PascalStrings);
74 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000075 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000076 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000077 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000078 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
79 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
80 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
81 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump1eb44332009-09-09 15:08:12 +000082 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000083 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000084 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000085 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
86 PARSE_LANGOPT_BENIGN(EmitAllDecls);
87 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
88 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump1eb44332009-09-09 15:08:12 +000089 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000090 diag::warn_pch_heinous_extensions);
91 // FIXME: Most of the options below are benign if the macro wasn't
92 // used. Unfortunately, this means that a PCH compiled without
93 // optimization can't be used with optimization turned on, even
94 // though the only thing that changes is whether __OPTIMIZE__ was
95 // defined... but if __OPTIMIZE__ never showed up in the header, it
96 // doesn't matter. We could consider making this some special kind
97 // of check.
98 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
99 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
100 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
101 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
102 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
103 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
104 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
105 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
106 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000107 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000108 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
109 return true;
110 }
111 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000112 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
113 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000114 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000115 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000116 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000117#undef PARSE_LANGOPT_IRRELEVANT
118#undef PARSE_LANGOPT_BENIGN
119
120 return false;
121}
122
123bool PCHValidator::ReadTargetTriple(const std::string &Triple) {
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000124 if (Triple != PP.getTargetInfo().getTriple().getTriple()) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000125 Reader.Diag(diag::warn_pch_target_triple)
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000126 << Triple << PP.getTargetInfo().getTriple().getTriple();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000127 return true;
128 }
129 return false;
130}
131
132/// \brief Split the given string into a vector of lines, eliminating
133/// any empty lines in the process.
134///
135/// \param Str the string to split.
136/// \param Len the length of Str.
137/// \param KeepEmptyLines true if empty lines should be included
138/// \returns a vector of lines, with the line endings removed
139static std::vector<std::string> splitLines(const char *Str, unsigned Len,
140 bool KeepEmptyLines = false) {
141 std::vector<std::string> Lines;
142 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
143 unsigned LineEnd = LineStart;
144 while (LineEnd < Len && Str[LineEnd] != '\n')
145 ++LineEnd;
146 if (LineStart != LineEnd || KeepEmptyLines)
147 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
148 LineStart = LineEnd;
149 }
150 return Lines;
151}
152
153/// \brief Determine whether the string Haystack starts with the
154/// substring Needle.
155static bool startsWith(const std::string &Haystack, const char *Needle) {
156 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
157 if (I == N)
158 return false;
159 if (Haystack[I] != Needle[I])
160 return false;
161 }
162
163 return true;
164}
165
166/// \brief Determine whether the string Haystack starts with the
167/// substring Needle.
168static inline bool startsWith(const std::string &Haystack,
169 const std::string &Needle) {
170 return startsWith(Haystack, Needle.c_str());
171}
172
Mike Stump1eb44332009-09-09 15:08:12 +0000173bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000174 unsigned PCHPredefLen,
175 FileID PCHBufferID,
176 std::string &SuggestedPredefines) {
177 const char *Predef = PP.getPredefines().c_str();
178 unsigned PredefLen = PP.getPredefines().size();
179
180 // If the two predefines buffers compare equal, we're done!
Mike Stump1eb44332009-09-09 15:08:12 +0000181 if (PredefLen == PCHPredefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000182 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
183 return false;
184
185 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000187 // The predefines buffers are different. Determine what the
188 // differences are, and whether they require us to reject the PCH
189 // file.
190 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
191 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
192
Mike Stump1eb44332009-09-09 15:08:12 +0000193 // Sort both sets of predefined buffer lines, since
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000194 std::sort(CmdLineLines.begin(), CmdLineLines.end());
195 std::sort(PCHLines.begin(), PCHLines.end());
196
197 // Determine which predefines that where used to build the PCH file
198 // are missing from the command line.
199 std::vector<std::string> MissingPredefines;
200 std::set_difference(PCHLines.begin(), PCHLines.end(),
201 CmdLineLines.begin(), CmdLineLines.end(),
202 std::back_inserter(MissingPredefines));
203
204 bool MissingDefines = false;
205 bool ConflictingDefines = false;
206 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
207 const std::string &Missing = MissingPredefines[I];
208 if (!startsWith(Missing, "#define ") != 0) {
209 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
210 return true;
211 }
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000213 // This is a macro definition. Determine the name of the macro
214 // we're defining.
215 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000216 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000217 = Missing.find_first_of("( \n\r", StartOfMacroName);
218 assert(EndOfMacroName != std::string::npos &&
219 "Couldn't find the end of the macro name");
220 std::string MacroName = Missing.substr(StartOfMacroName,
221 EndOfMacroName - StartOfMacroName);
222
223 // Determine whether this macro was given a different definition
224 // on the command line.
225 std::string MacroDefStart = "#define " + MacroName;
226 std::string::size_type MacroDefLen = MacroDefStart.size();
227 std::vector<std::string>::iterator ConflictPos
228 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
229 MacroDefStart);
230 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
231 if (!startsWith(*ConflictPos, MacroDefStart)) {
232 // Different macro; we're done.
233 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000234 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000235 }
Mike Stump1eb44332009-09-09 15:08:12 +0000236
237 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000238 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000239 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000240 (*ConflictPos)[MacroDefLen] != '(')
241 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000243 // We found a conflicting macro definition.
244 break;
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000247 if (ConflictPos != CmdLineLines.end()) {
248 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
249 << MacroName;
250
251 // Show the definition of this macro within the PCH file.
252 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
253 unsigned Offset = MissingDef - PCHPredef;
254 SourceLocation PCHMissingLoc
255 = SourceMgr.getLocForStartOfFile(PCHBufferID)
256 .getFileLocWithOffset(Offset);
257 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
258 << MacroName;
259
260 ConflictingDefines = true;
261 continue;
262 }
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000264 // If the macro doesn't conflict, then we'll just pick up the
265 // macro definition from the PCH file. Warn the user that they
266 // made a mistake.
267 if (ConflictingDefines)
268 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000270 if (!MissingDefines) {
271 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
272 MissingDefines = true;
273 }
274
275 // Show the definition of this macro within the PCH file.
276 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
277 unsigned Offset = MissingDef - PCHPredef;
278 SourceLocation PCHMissingLoc
279 = SourceMgr.getLocForStartOfFile(PCHBufferID)
280 .getFileLocWithOffset(Offset);
281 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
282 }
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000284 if (ConflictingDefines)
285 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000287 // Determine what predefines were introduced based on command-line
288 // parameters that were not present when building the PCH
289 // file. Extra #defines are okay, so long as the identifiers being
290 // defined were not used within the precompiled header.
291 std::vector<std::string> ExtraPredefines;
292 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
293 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000294 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000295 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
296 const std::string &Extra = ExtraPredefines[I];
297 if (!startsWith(Extra, "#define ") != 0) {
298 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
299 return true;
300 }
301
302 // This is an extra macro definition. Determine the name of the
303 // macro we're defining.
304 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000305 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000306 = Extra.find_first_of("( \n\r", StartOfMacroName);
307 assert(EndOfMacroName != std::string::npos &&
308 "Couldn't find the end of the macro name");
309 std::string MacroName = Extra.substr(StartOfMacroName,
310 EndOfMacroName - StartOfMacroName);
311
312 // Check whether this name was used somewhere in the PCH file. If
313 // so, defining it as a macro could change behavior, so we reject
314 // the PCH file.
315 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
316 MacroName.c_str() + MacroName.size())) {
317 Reader.Diag(diag::warn_macro_name_used_in_pch)
318 << II;
319 return true;
320 }
321
322 // Add this definition to the suggested predefines buffer.
323 SuggestedPredefines += Extra;
324 SuggestedPredefines += '\n';
325 }
326
327 // If we get here, it's because the predefines buffer had compatible
328 // contents. Accept the PCH file.
329 return false;
330}
331
332void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
333 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
334}
335
336void PCHValidator::ReadCounter(unsigned Value) {
337 PP.setCounterValue(Value);
338}
339
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000340//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000341// PCH reader implementation
342//===----------------------------------------------------------------------===//
343
Mike Stump1eb44332009-09-09 15:08:12 +0000344PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
345 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000346 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
347 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregor52e71082009-10-16 18:18:30 +0000348 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000349 IdentifierTableData(0), IdentifierLookupTable(0),
350 IdentifierOffsets(0),
351 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
352 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000353 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000354 NumStatHits(0), NumStatMisses(0),
355 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000356 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000357 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000358 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000359 RelocatablePCH = false;
360}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000361
362PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000363 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000364 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregor52e71082009-10-16 18:18:30 +0000365 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000366 IdentifierTableData(0), IdentifierLookupTable(0),
367 IdentifierOffsets(0),
368 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
369 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000370 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000371 NumStatHits(0), NumStatMisses(0),
372 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000373 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000374 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000375 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000376 RelocatablePCH = false;
377}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000378
379PCHReader::~PCHReader() {}
380
Chris Lattnerda930612009-04-27 05:58:23 +0000381Expr *PCHReader::ReadDeclExpr() {
382 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
383}
384
385Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor61d60ee2009-10-17 00:13:19 +0000386 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000387}
388
389
Douglas Gregor668c1a42009-04-21 22:25:48 +0000390namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000391class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
392 PCHReader &Reader;
393
394public:
395 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
396
397 typedef Selector external_key_type;
398 typedef external_key_type internal_key_type;
399
400 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000402 static bool EqualKey(const internal_key_type& a,
403 const internal_key_type& b) {
404 return a == b;
405 }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000407 static unsigned ComputeHash(Selector Sel) {
408 unsigned N = Sel.getNumArgs();
409 if (N == 0)
410 ++N;
411 unsigned R = 5381;
412 for (unsigned I = 0; I != N; ++I)
413 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000414 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000415 return R;
416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000418 // This hopefully will just get inlined and removed by the optimizer.
419 static const internal_key_type&
420 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000422 static std::pair<unsigned, unsigned>
423 ReadKeyDataLength(const unsigned char*& d) {
424 using namespace clang::io;
425 unsigned KeyLen = ReadUnalignedLE16(d);
426 unsigned DataLen = ReadUnalignedLE16(d);
427 return std::make_pair(KeyLen, DataLen);
428 }
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Douglas Gregor83941df2009-04-25 17:48:32 +0000430 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000431 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000432 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000433 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000434 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000435 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
436 if (N == 0)
437 return SelTable.getNullarySelector(FirstII);
438 else if (N == 1)
439 return SelTable.getUnarySelector(FirstII);
440
441 llvm::SmallVector<IdentifierInfo *, 16> Args;
442 Args.push_back(FirstII);
443 for (unsigned I = 1; I != N; ++I)
444 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
445
Douglas Gregor75fdb232009-05-22 22:45:36 +0000446 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000447 }
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000449 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
450 using namespace clang::io;
451 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
452 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
453
454 data_type Result;
455
456 // Load instance methods
457 ObjCMethodList *Prev = 0;
458 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000459 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000460 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
461 if (!Result.first.Method) {
462 // This is the first method, which is the easy case.
463 Result.first.Method = Method;
464 Prev = &Result.first;
465 continue;
466 }
467
468 Prev->Next = new ObjCMethodList(Method, 0);
469 Prev = Prev->Next;
470 }
471
472 // Load factory methods
473 Prev = 0;
474 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000475 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000476 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
477 if (!Result.second.Method) {
478 // This is the first method, which is the easy case.
479 Result.second.Method = Method;
480 Prev = &Result.second;
481 continue;
482 }
483
484 Prev->Next = new ObjCMethodList(Method, 0);
485 Prev = Prev->Next;
486 }
487
488 return Result;
489 }
490};
Mike Stump1eb44332009-09-09 15:08:12 +0000491
492} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000493
494/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000495typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000496 PCHMethodPoolLookupTable;
497
498namespace {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000499class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
500 PCHReader &Reader;
501
502 // If we know the IdentifierInfo in advance, it is here and we will
503 // not build a new one. Used when deserializing information about an
504 // identifier that was constructed before the PCH file was read.
505 IdentifierInfo *KnownII;
506
507public:
508 typedef IdentifierInfo * data_type;
509
510 typedef const std::pair<const char*, unsigned> external_key_type;
511
512 typedef external_key_type internal_key_type;
513
Mike Stump1eb44332009-09-09 15:08:12 +0000514 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000515 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Douglas Gregor668c1a42009-04-21 22:25:48 +0000517 static bool EqualKey(const internal_key_type& a,
518 const internal_key_type& b) {
519 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
520 : false;
521 }
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Douglas Gregor668c1a42009-04-21 22:25:48 +0000523 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000524 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000525 }
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Douglas Gregor668c1a42009-04-21 22:25:48 +0000527 // This hopefully will just get inlined and removed by the optimizer.
528 static const internal_key_type&
529 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Douglas Gregor668c1a42009-04-21 22:25:48 +0000531 static std::pair<unsigned, unsigned>
532 ReadKeyDataLength(const unsigned char*& d) {
533 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000534 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000535 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000536 return std::make_pair(KeyLen, DataLen);
537 }
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Douglas Gregor668c1a42009-04-21 22:25:48 +0000539 static std::pair<const char*, unsigned>
540 ReadKey(const unsigned char* d, unsigned n) {
541 assert(n >= 2 && d[n-1] == '\0');
542 return std::make_pair((const char*) d, n-1);
543 }
Mike Stump1eb44332009-09-09 15:08:12 +0000544
545 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000546 const unsigned char* d,
547 unsigned DataLen) {
548 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000549 pch::IdentID ID = ReadUnalignedLE32(d);
550 bool IsInteresting = ID & 0x01;
551
552 // Wipe out the "is interesting" bit.
553 ID = ID >> 1;
554
555 if (!IsInteresting) {
556 // For unintersting identifiers, just build the IdentifierInfo
557 // and associate it with the persistent ID.
558 IdentifierInfo *II = KnownII;
559 if (!II)
560 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
561 k.first, k.first + k.second);
562 Reader.SetIdentifierInfo(ID, II);
563 return II;
564 }
565
Douglas Gregor5998da52009-04-28 21:32:13 +0000566 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000567 bool CPlusPlusOperatorKeyword = Bits & 0x01;
568 Bits >>= 1;
569 bool Poisoned = Bits & 0x01;
570 Bits >>= 1;
571 bool ExtensionToken = Bits & 0x01;
572 Bits >>= 1;
573 bool hasMacroDefinition = Bits & 0x01;
574 Bits >>= 1;
575 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
576 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Douglas Gregor2deaea32009-04-22 18:49:13 +0000578 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000579 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000580
581 // Build the IdentifierInfo itself and link the identifier ID with
582 // the new IdentifierInfo.
583 IdentifierInfo *II = KnownII;
584 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000585 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
586 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000587 Reader.SetIdentifierInfo(ID, II);
588
Douglas Gregor2deaea32009-04-22 18:49:13 +0000589 // Set or check the various bits in the IdentifierInfo structure.
590 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000591 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000592 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000593 "Incorrect extension token flag");
594 (void)ExtensionToken;
595 II->setIsPoisoned(Poisoned);
596 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
597 "Incorrect C++ operator keyword flag");
598 (void)CPlusPlusOperatorKeyword;
599
Douglas Gregor37e26842009-04-21 23:56:24 +0000600 // If this identifier is a macro, deserialize the macro
601 // definition.
602 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000603 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000604 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000605 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000606 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000607
608 // Read all of the declarations visible at global scope with this
609 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000610 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000611 if (DataLen > 0) {
612 llvm::SmallVector<uint32_t, 4> DeclIDs;
613 for (; DataLen > 0; DataLen -= 4)
614 DeclIDs.push_back(ReadUnalignedLE32(d));
615 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000616 }
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Douglas Gregor668c1a42009-04-21 22:25:48 +0000618 return II;
619 }
620};
Mike Stump1eb44332009-09-09 15:08:12 +0000621
622} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000623
624/// \brief The on-disk hash table used to contain information about
625/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000626typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000627 PCHIdentifierLookupTable;
628
Douglas Gregora02b1472009-04-28 21:53:25 +0000629bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000630 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
631 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000632 return true;
633}
634
Douglas Gregore1d918e2009-04-10 23:10:45 +0000635/// \brief Check the contents of the predefines buffer against the
636/// contents of the predefines buffer used to build the PCH file.
637///
638/// The contents of the two predefines buffers should be the same. If
639/// not, then some command-line option changed the preprocessor state
640/// and we must reject the PCH file.
641///
642/// \param PCHPredef The start of the predefines buffer in the PCH
643/// file.
644///
645/// \param PCHPredefLen The length of the predefines buffer in the PCH
646/// file.
647///
648/// \param PCHBufferID The FileID for the PCH predefines buffer.
649///
650/// \returns true if there was a mismatch (in which case the PCH file
651/// should be ignored), or false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +0000652bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000653 unsigned PCHPredefLen,
654 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000655 if (Listener)
656 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
657 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000658 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000659}
660
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000661//===----------------------------------------------------------------------===//
662// Source Manager Deserialization
663//===----------------------------------------------------------------------===//
664
Douglas Gregorbd945002009-04-13 16:31:14 +0000665/// \brief Read the line table in the source manager block.
666/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000667bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000668 unsigned Idx = 0;
669 LineTableInfo &LineTable = SourceMgr.getLineTable();
670
671 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000672 std::map<int, int> FileIDs;
673 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000674 // Extract the file name
675 unsigned FilenameLen = Record[Idx++];
676 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
677 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000678 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000679 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000680 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000681 }
682
683 // Parse the line entries
684 std::vector<LineEntry> Entries;
685 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000686 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000687
688 // Extract the line entries
689 unsigned NumEntries = Record[Idx++];
690 Entries.clear();
691 Entries.reserve(NumEntries);
692 for (unsigned I = 0; I != NumEntries; ++I) {
693 unsigned FileOffset = Record[Idx++];
694 unsigned LineNo = Record[Idx++];
695 int FilenameID = Record[Idx++];
Mike Stump1eb44332009-09-09 15:08:12 +0000696 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000697 = (SrcMgr::CharacteristicKind)Record[Idx++];
698 unsigned IncludeOffset = Record[Idx++];
699 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
700 FileKind, IncludeOffset));
701 }
702 LineTable.AddEntry(FID, Entries);
703 }
704
705 return false;
706}
707
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000708namespace {
709
710class VISIBILITY_HIDDEN PCHStatData {
711public:
712 const bool hasStat;
713 const ino_t ino;
714 const dev_t dev;
715 const mode_t mode;
716 const time_t mtime;
717 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000719 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000720 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
721
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000722 PCHStatData()
723 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
724};
725
726class VISIBILITY_HIDDEN PCHStatLookupTrait {
727 public:
728 typedef const char *external_key_type;
729 typedef const char *internal_key_type;
730
731 typedef PCHStatData data_type;
732
733 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000734 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000735 }
736
737 static internal_key_type GetInternalKey(const char *path) { return path; }
738
739 static bool EqualKey(internal_key_type a, internal_key_type b) {
740 return strcmp(a, b) == 0;
741 }
742
743 static std::pair<unsigned, unsigned>
744 ReadKeyDataLength(const unsigned char*& d) {
745 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
746 unsigned DataLen = (unsigned) *d++;
747 return std::make_pair(KeyLen + 1, DataLen);
748 }
749
750 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
751 return (const char *)d;
752 }
753
754 static data_type ReadData(const internal_key_type, const unsigned char *d,
755 unsigned /*DataLen*/) {
756 using namespace clang::io;
757
758 if (*d++ == 1)
759 return data_type();
760
761 ino_t ino = (ino_t) ReadUnalignedLE32(d);
762 dev_t dev = (dev_t) ReadUnalignedLE32(d);
763 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000764 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000765 off_t size = (off_t) ReadUnalignedLE64(d);
766 return data_type(ino, dev, mode, mtime, size);
767 }
768};
769
770/// \brief stat() cache for precompiled headers.
771///
772/// This cache is very similar to the stat cache used by pretokenized
773/// headers.
774class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
775 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
776 CacheTy *Cache;
777
778 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000779public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000780 PCHStatCache(const unsigned char *Buckets,
781 const unsigned char *Base,
782 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000783 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000784 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
785 Cache = CacheTy::Create(Buckets, Base);
786 }
787
788 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000790 int stat(const char *path, struct stat *buf) {
791 // Do the lookup for the file's data in the PCH file.
792 CacheTy::iterator I = Cache->find(path);
793
794 // If we don't get a hit in the PCH file just forward to 'stat'.
795 if (I == Cache->end()) {
796 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000797 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000798 }
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000800 ++NumStatHits;
801 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000803 if (!Data.hasStat)
804 return 1;
805
806 buf->st_ino = Data.ino;
807 buf->st_dev = Data.dev;
808 buf->st_mtime = Data.mtime;
809 buf->st_mode = Data.mode;
810 buf->st_size = Data.size;
811 return 0;
812 }
813};
814} // end anonymous namespace
815
816
Douglas Gregor14f79002009-04-10 03:52:48 +0000817/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000818PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000819 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000820
821 // Set the source-location entry cursor to the current position in
822 // the stream. This cursor will be used to read the contents of the
823 // source manager block initially, and then lazily read
824 // source-location entries as needed.
825 SLocEntryCursor = Stream;
826
827 // The stream itself is going to skip over the source manager block.
828 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000829 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000830 return Failure;
831 }
832
833 // Enter the source manager block.
834 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000835 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000836 return Failure;
837 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000838
Douglas Gregor14f79002009-04-10 03:52:48 +0000839 RecordData Record;
840 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000841 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000842 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000843 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000844 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000845 return Failure;
846 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000847 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000848 }
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Douglas Gregor14f79002009-04-10 03:52:48 +0000850 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
851 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000852 SLocEntryCursor.ReadSubBlockID();
853 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000854 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000855 return Failure;
856 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000857 continue;
858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Douglas Gregor14f79002009-04-10 03:52:48 +0000860 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000861 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000862 continue;
863 }
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Douglas Gregor14f79002009-04-10 03:52:48 +0000865 // Read a record.
866 const char *BlobStart;
867 unsigned BlobLen;
868 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000869 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000870 default: // Default behavior: ignore.
871 break;
872
Chris Lattner2c78b872009-04-14 23:22:57 +0000873 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000874 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000875 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000876 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000877
878 case pch::SM_HEADER_FILE_INFO: {
879 HeaderFileInfo HFI;
880 HFI.isImport = Record[0];
881 HFI.DirInfo = Record[1];
882 HFI.NumIncludes = Record[2];
883 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000884 if (Listener)
885 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000886 break;
887 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000888
889 case pch::SM_SLOC_FILE_ENTRY:
890 case pch::SM_SLOC_BUFFER_ENTRY:
891 case pch::SM_SLOC_INSTANTIATION_ENTRY:
892 // Once we hit one of the source location entries, we're done.
893 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000894 }
895 }
896}
897
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000898/// \brief Read in the source location entry with the given ID.
899PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
900 if (ID == 0)
901 return Success;
902
903 if (ID > TotalNumSLocEntries) {
904 Error("source location entry ID out-of-range for PCH file");
905 return Failure;
906 }
907
908 ++NumSLocEntriesRead;
909 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
910 unsigned Code = SLocEntryCursor.ReadCode();
911 if (Code == llvm::bitc::END_BLOCK ||
912 Code == llvm::bitc::ENTER_SUBBLOCK ||
913 Code == llvm::bitc::DEFINE_ABBREV) {
914 Error("incorrectly-formatted source location entry in PCH file");
915 return Failure;
916 }
917
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000918 RecordData Record;
919 const char *BlobStart;
920 unsigned BlobLen;
921 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
922 default:
923 Error("incorrectly-formatted source location entry in PCH file");
924 return Failure;
925
926 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000927 std::string Filename(BlobStart, BlobStart + BlobLen);
928 MaybeAddSystemRootToFilename(Filename);
929 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000930 if (File == 0) {
931 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000932 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000933 ErrorStr += "' referenced by PCH file";
934 Error(ErrorStr.c_str());
935 return Failure;
936 }
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000938 FileID FID = SourceMgr.createFileID(File,
939 SourceLocation::getFromRawEncoding(Record[1]),
940 (SrcMgr::CharacteristicKind)Record[2],
941 ID, Record[0]);
942 if (Record[3])
943 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
944 .setHasLineDirectives();
945
946 break;
947 }
948
949 case pch::SM_SLOC_BUFFER_ENTRY: {
950 const char *Name = BlobStart;
951 unsigned Offset = Record[0];
952 unsigned Code = SLocEntryCursor.ReadCode();
953 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000954 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000955 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
956 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
957 (void)RecCode;
958 llvm::MemoryBuffer *Buffer
Mike Stump1eb44332009-09-09 15:08:12 +0000959 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000960 BlobStart + BlobLen - 1,
961 Name);
962 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Douglas Gregor92b059e2009-04-28 20:33:11 +0000964 if (strcmp(Name, "<built-in>") == 0) {
965 PCHPredefinesBufferID = BufferID;
966 PCHPredefines = BlobStart;
967 PCHPredefinesLen = BlobLen - 1;
968 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000969
970 break;
971 }
972
973 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +0000974 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000975 = SourceLocation::getFromRawEncoding(Record[1]);
976 SourceMgr.createInstantiationLoc(SpellingLoc,
977 SourceLocation::getFromRawEncoding(Record[2]),
978 SourceLocation::getFromRawEncoding(Record[3]),
979 Record[4],
980 ID,
981 Record[0]);
982 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000983 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000984 }
985
986 return Success;
987}
988
Chris Lattner6367f6d2009-04-27 01:05:14 +0000989/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
990/// specified cursor. Read the abbreviations that are at the top of the block
991/// and then leave the cursor pointing into the block.
992bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
993 unsigned BlockID) {
994 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000995 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000996 return Failure;
997 }
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner6367f6d2009-04-27 01:05:14 +0000999 while (true) {
1000 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chris Lattner6367f6d2009-04-27 01:05:14 +00001002 // We expect all abbrevs to be at the start of the block.
1003 if (Code != llvm::bitc::DEFINE_ABBREV)
1004 return false;
1005 Cursor.ReadAbbrevRecord();
1006 }
1007}
1008
Douglas Gregor37e26842009-04-21 23:56:24 +00001009void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001010 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Douglas Gregor37e26842009-04-21 23:56:24 +00001012 // Keep track of where we are in the stream, then jump back there
1013 // after reading this macro.
1014 SavedStreamPosition SavedPosition(Stream);
1015
1016 Stream.JumpToBit(Offset);
1017 RecordData Record;
1018 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1019 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Douglas Gregor37e26842009-04-21 23:56:24 +00001021 while (true) {
1022 unsigned Code = Stream.ReadCode();
1023 switch (Code) {
1024 case llvm::bitc::END_BLOCK:
1025 return;
1026
1027 case llvm::bitc::ENTER_SUBBLOCK:
1028 // No known subblocks, always skip them.
1029 Stream.ReadSubBlockID();
1030 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001031 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001032 return;
1033 }
1034 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Douglas Gregor37e26842009-04-21 23:56:24 +00001036 case llvm::bitc::DEFINE_ABBREV:
1037 Stream.ReadAbbrevRecord();
1038 continue;
1039 default: break;
1040 }
1041
1042 // Read a record.
1043 Record.clear();
1044 pch::PreprocessorRecordTypes RecType =
1045 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1046 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001047 case pch::PP_MACRO_OBJECT_LIKE:
1048 case pch::PP_MACRO_FUNCTION_LIKE: {
1049 // If we already have a macro, that means that we've hit the end
1050 // of the definition of the macro we were looking for. We're
1051 // done.
1052 if (Macro)
1053 return;
1054
1055 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1056 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001057 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001058 return;
1059 }
1060 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1061 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001063 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001064 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregor37e26842009-04-21 23:56:24 +00001066 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1067 // Decode function-like macro info.
1068 bool isC99VarArgs = Record[3];
1069 bool isGNUVarArgs = Record[4];
1070 MacroArgs.clear();
1071 unsigned NumArgs = Record[5];
1072 for (unsigned i = 0; i != NumArgs; ++i)
1073 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1074
1075 // Install function-like macro info.
1076 MI->setIsFunctionLike();
1077 if (isC99VarArgs) MI->setIsC99Varargs();
1078 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001079 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001080 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001081 }
1082
1083 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001084 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001085
1086 // Remember that we saw this macro last so that we add the tokens that
1087 // form its body to it.
1088 Macro = MI;
1089 ++NumMacrosRead;
1090 break;
1091 }
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Douglas Gregor37e26842009-04-21 23:56:24 +00001093 case pch::PP_TOKEN: {
1094 // If we see a TOKEN before a PP_MACRO_*, then the file is
1095 // erroneous, just pretend we didn't see this.
1096 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Douglas Gregor37e26842009-04-21 23:56:24 +00001098 Token Tok;
1099 Tok.startToken();
1100 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1101 Tok.setLength(Record[1]);
1102 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1103 Tok.setIdentifierInfo(II);
1104 Tok.setKind((tok::TokenKind)Record[3]);
1105 Tok.setFlag((Token::TokenFlags)Record[4]);
1106 Macro->AddTokenToBody(Tok);
1107 break;
1108 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001109 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001110 }
1111}
1112
Douglas Gregore650c8c2009-07-07 00:12:59 +00001113/// \brief If we are loading a relocatable PCH file, and the filename is
1114/// not an absolute path, add the system root to the beginning of the file
1115/// name.
1116void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1117 // If this is not a relocatable PCH file, there's nothing to do.
1118 if (!RelocatablePCH)
1119 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Douglas Gregore650c8c2009-07-07 00:12:59 +00001121 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1122 return;
1123
1124 std::string FIXME = Filename;
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Douglas Gregore650c8c2009-07-07 00:12:59 +00001126 if (isysroot == 0) {
1127 // If no system root was given, default to '/'
1128 Filename.insert(Filename.begin(), '/');
1129 return;
1130 }
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Douglas Gregore650c8c2009-07-07 00:12:59 +00001132 unsigned Length = strlen(isysroot);
1133 if (isysroot[Length - 1] != '/')
1134 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Douglas Gregore650c8c2009-07-07 00:12:59 +00001136 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1137}
1138
Mike Stump1eb44332009-09-09 15:08:12 +00001139PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001140PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001141 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001142 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001143 return Failure;
1144 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001145
1146 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001147 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001148 while (!Stream.AtEndOfStream()) {
1149 unsigned Code = Stream.ReadCode();
1150 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001151 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001152 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001153 return Failure;
1154 }
Chris Lattner7356a312009-04-11 21:15:38 +00001155
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001156 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001157 }
1158
1159 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1160 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001161 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001162 // We lazily load the decls block, but we want to set up the
1163 // DeclsCursor cursor to point into it. Clone our current bitcode
1164 // cursor to it, enter the block and read the abbrevs in that block.
1165 // With the main cursor, we just skip over it.
1166 DeclsCursor = Stream;
1167 if (Stream.SkipBlock() || // Skip with the main cursor.
1168 // Read the abbrevs.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001169 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001170 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001171 return Failure;
1172 }
1173 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Chris Lattner7356a312009-04-11 21:15:38 +00001175 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001176 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001177 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001178 return Failure;
1179 }
1180 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001181
Douglas Gregor14f79002009-04-10 03:52:48 +00001182 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001183 switch (ReadSourceManagerBlock()) {
1184 case Success:
1185 break;
1186
1187 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001188 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001189 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001190
1191 case IgnorePCH:
1192 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001193 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001194 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001195 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001196 continue;
1197 }
1198
1199 if (Code == llvm::bitc::DEFINE_ABBREV) {
1200 Stream.ReadAbbrevRecord();
1201 continue;
1202 }
1203
1204 // Read and process a record.
1205 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001206 const char *BlobStart = 0;
1207 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001208 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001209 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001210 default: // Default behavior: ignore.
1211 break;
1212
1213 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001214 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001215 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001216 return Failure;
1217 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001218 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001219 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001220 break;
1221
1222 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001223 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001224 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001225 return Failure;
1226 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001227 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001228 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001229 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001230
1231 case pch::LANGUAGE_OPTIONS:
1232 if (ParseLanguageOptions(Record))
1233 return IgnorePCH;
1234 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001235
Douglas Gregorab41e632009-04-27 22:23:34 +00001236 case pch::METADATA: {
1237 if (Record[0] != pch::VERSION_MAJOR) {
1238 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1239 : diag::warn_pch_version_too_new);
1240 return IgnorePCH;
1241 }
1242
Douglas Gregore650c8c2009-07-07 00:12:59 +00001243 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001244 if (Listener) {
1245 std::string TargetTriple(BlobStart, BlobLen);
1246 if (Listener->ReadTargetTriple(TargetTriple))
1247 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001248 }
1249 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001250 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001251
1252 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001253 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001254 if (Record[0]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001255 IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001256 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001257 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001258 (const unsigned char *)IdentifierTableData,
Douglas Gregor668c1a42009-04-21 22:25:48 +00001259 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001260 if (PP)
1261 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001262 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001263 break;
1264
1265 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001266 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001267 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001268 return Failure;
1269 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001270 IdentifierOffsets = (const uint32_t *)BlobStart;
1271 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001272 if (PP)
1273 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001274 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001275
1276 case pch::EXTERNAL_DEFINITIONS:
1277 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001278 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001279 return Failure;
1280 }
1281 ExternalDefinitions.swap(Record);
1282 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001283
Douglas Gregorad1de002009-04-18 05:55:16 +00001284 case pch::SPECIAL_TYPES:
1285 SpecialTypes.swap(Record);
1286 break;
1287
Douglas Gregor3e1af842009-04-17 22:13:46 +00001288 case pch::STATISTICS:
1289 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001290 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001291 TotalLexicalDeclContexts = Record[2];
1292 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001293 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001294
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001295 case pch::TENTATIVE_DEFINITIONS:
1296 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001297 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001298 return Failure;
1299 }
1300 TentativeDefinitions.swap(Record);
1301 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001302
1303 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1304 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001305 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001306 return Failure;
1307 }
1308 LocallyScopedExternalDecls.swap(Record);
1309 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001310
Douglas Gregor83941df2009-04-25 17:48:32 +00001311 case pch::SELECTOR_OFFSETS:
1312 SelectorOffsets = (const uint32_t *)BlobStart;
1313 TotalNumSelectors = Record[0];
1314 SelectorsLoaded.resize(TotalNumSelectors);
1315 break;
1316
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001317 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001318 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1319 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001320 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001321 = PCHMethodPoolLookupTable::Create(
1322 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001323 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001324 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001325 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001326 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001327
1328 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001329 if (!Record.empty() && Listener)
1330 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001331 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001332
1333 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001334 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001335 TotalNumSLocEntries = Record[0];
Douglas Gregor445e23e2009-10-05 21:07:28 +00001336 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001337 break;
1338
1339 case pch::SOURCE_LOCATION_PRELOADS:
1340 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1341 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1342 if (Result != Success)
1343 return Result;
1344 }
1345 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001346
Douglas Gregor52e71082009-10-16 18:18:30 +00001347 case pch::STAT_CACHE: {
1348 PCHStatCache *MyStatCache =
1349 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1350 (const unsigned char *)BlobStart,
1351 NumStatHits, NumStatMisses);
1352 FileMgr.addStatCache(MyStatCache);
1353 StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001354 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001355 }
1356
Douglas Gregorb81c1702009-04-27 20:06:05 +00001357 case pch::EXT_VECTOR_DECLS:
1358 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001359 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001360 return Failure;
1361 }
1362 ExtVectorDecls.swap(Record);
1363 break;
1364
Douglas Gregorb64c1932009-05-12 01:31:05 +00001365 case pch::ORIGINAL_FILE_NAME:
1366 OriginalFileName.assign(BlobStart, BlobLen);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001367 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001368 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Douglas Gregor2e222532009-07-02 17:08:52 +00001370 case pch::COMMENT_RANGES:
1371 Comments = (SourceRange *)BlobStart;
1372 NumComments = BlobLen / sizeof(SourceRange);
1373 break;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001374
1375 case pch::SVN_BRANCH_REVISION: {
1376 unsigned CurRevision = getClangSubversionRevision();
1377 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1378 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1379 : diag::warn_pch_version_too_new);
1380 return IgnorePCH;
1381 }
1382
1383 const char *CurBranch = getClangSubversionPath();
1384 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1385 std::string PCHBranch(BlobStart, BlobLen);
1386 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1387 return IgnorePCH;
1388 }
1389 break;
1390 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001391 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001392 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001393 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001394 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001395}
1396
Douglas Gregore1d918e2009-04-10 23:10:45 +00001397PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001398 // Set the PCH file name.
1399 this->FileName = FileName;
1400
Douglas Gregor2cf26342009-04-09 22:27:44 +00001401 // Open the PCH file.
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001402 //
1403 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001404 std::string ErrStr;
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001405 if (FileName == "-")
1406 Buffer.reset(llvm::MemoryBuffer::getSTDIN());
1407 else
1408 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001409 if (!Buffer) {
1410 Error(ErrStr.c_str());
1411 return IgnorePCH;
1412 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001413
1414 // Initialize the stream
Mike Stump1eb44332009-09-09 15:08:12 +00001415 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001416 (const unsigned char *)Buffer->getBufferEnd());
1417 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001418
1419 // Sniff for the signature.
1420 if (Stream.Read(8) != 'C' ||
1421 Stream.Read(8) != 'P' ||
1422 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001423 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001424 Diag(diag::err_not_a_pch_file) << FileName;
1425 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001426 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001427
Douglas Gregor2cf26342009-04-09 22:27:44 +00001428 while (!Stream.AtEndOfStream()) {
1429 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Douglas Gregore1d918e2009-04-10 23:10:45 +00001431 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001432 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001433 return Failure;
1434 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001435
1436 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001437
Douglas Gregor2cf26342009-04-09 22:27:44 +00001438 // We only know the PCH subblock ID.
1439 switch (BlockID) {
1440 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001441 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001442 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001443 return Failure;
1444 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001445 break;
1446 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001447 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001448 case Success:
1449 break;
1450
1451 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001452 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001453
1454 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001455 // FIXME: We could consider reading through to the end of this
1456 // PCH block, skipping subblocks, to see if there are other
1457 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001458
1459 // Clear out any preallocated source location entries, so that
1460 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001461 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001462
1463 // Remove the stat cache.
Douglas Gregor52e71082009-10-16 18:18:30 +00001464 if (StatCache)
1465 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001466
Douglas Gregore1d918e2009-04-10 23:10:45 +00001467 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001468 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001469 break;
1470 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001471 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001472 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001473 return Failure;
1474 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001475 break;
1476 }
Mike Stump1eb44332009-09-09 15:08:12 +00001477 }
1478
Douglas Gregor92b059e2009-04-28 20:33:11 +00001479 // Check the predefines buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001480 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
Douglas Gregor92b059e2009-04-28 20:33:11 +00001481 PCHPredefinesBufferID))
1482 return IgnorePCH;
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001484 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001485 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001486 // PCH file is read, so there may be some identifiers that were
1487 // loaded into the IdentifierTable before we intercepted the
1488 // creation of identifiers. Iterate through the list of known
1489 // identifiers and determine whether we have to establish
1490 // preprocessor definitions or top-level identifier declaration
1491 // chains for those identifiers.
1492 //
1493 // We copy the IdentifierInfo pointers to a small vector first,
1494 // since de-serializing declarations or macro definitions can add
1495 // new entries into the identifier table, invalidating the
1496 // iterators.
1497 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1498 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1499 IdEnd = PP->getIdentifierTable().end();
1500 Id != IdEnd; ++Id)
1501 Identifiers.push_back(Id->second);
Mike Stump1eb44332009-09-09 15:08:12 +00001502 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001503 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1504 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1505 IdentifierInfo *II = Identifiers[I];
1506 // Look in the on-disk hash table for an entry for
1507 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbare013d682009-10-18 20:26:12 +00001508 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001509 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1510 if (Pos == IdTable->end())
1511 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001513 // Dereferencing the iterator has the effect of populating the
1514 // IdentifierInfo node with the various declarations it needs.
1515 (void)*Pos;
1516 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001517 }
1518
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001519 if (Context)
1520 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001521
Douglas Gregor668c1a42009-04-21 22:25:48 +00001522 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001523}
1524
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001525void PCHReader::InitializeContext(ASTContext &Ctx) {
1526 Context = &Ctx;
1527 assert(Context && "Passed null context!");
1528
1529 assert(PP && "Forgot to set Preprocessor ?");
1530 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1531 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001533 // Load the translation unit declaration
1534 ReadDeclRecord(DeclOffsets[0], 0);
1535
1536 // Load the special types.
1537 Context->setBuiltinVaListType(
1538 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1539 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1540 Context->setObjCIdType(GetType(Id));
1541 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1542 Context->setObjCSelType(GetType(Sel));
1543 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1544 Context->setObjCProtoType(GetType(Proto));
1545 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1546 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001547
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001548 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1549 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001550 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001551 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1552 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001553 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1554 QualType FileType = GetType(File);
1555 assert(!FileType.isNull() && "FILE type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001556 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001557 Context->setFILEDecl(Typedef->getDecl());
1558 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001559 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001560 assert(Tag && "Invalid FILE type in PCH file");
1561 Context->setFILEDecl(Tag->getDecl());
1562 }
1563 }
Mike Stump782fa302009-07-28 02:25:19 +00001564 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1565 QualType Jmp_bufType = GetType(Jmp_buf);
1566 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001567 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001568 Context->setjmp_bufDecl(Typedef->getDecl());
1569 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001570 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001571 assert(Tag && "Invalid jmp_bug type in PCH file");
1572 Context->setjmp_bufDecl(Tag->getDecl());
1573 }
1574 }
1575 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1576 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1577 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001578 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001579 Context->setsigjmp_bufDecl(Typedef->getDecl());
1580 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001581 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001582 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1583 Context->setsigjmp_bufDecl(Tag->getDecl());
1584 }
1585 }
Mike Stump1eb44332009-09-09 15:08:12 +00001586 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001587 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1588 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001589 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001590 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1591 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00001592 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1593 Context->setBlockDescriptorType(GetType(String));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001594}
1595
Douglas Gregorb64c1932009-05-12 01:31:05 +00001596/// \brief Retrieve the name of the original source file name
1597/// directly from the PCH file, without actually loading the PCH
1598/// file.
1599std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1600 // Open the PCH file.
1601 std::string ErrStr;
1602 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1603 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1604 if (!Buffer) {
1605 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1606 return std::string();
1607 }
1608
1609 // Initialize the stream
1610 llvm::BitstreamReader StreamFile;
1611 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00001612 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00001613 (const unsigned char *)Buffer->getBufferEnd());
1614 Stream.init(StreamFile);
1615
1616 // Sniff for the signature.
1617 if (Stream.Read(8) != 'C' ||
1618 Stream.Read(8) != 'P' ||
1619 Stream.Read(8) != 'C' ||
1620 Stream.Read(8) != 'H') {
Mike Stump1eb44332009-09-09 15:08:12 +00001621 fprintf(stderr,
Douglas Gregorb64c1932009-05-12 01:31:05 +00001622 "error: '%s' does not appear to be a precompiled header file\n",
1623 PCHFileName.c_str());
1624 return std::string();
1625 }
1626
1627 RecordData Record;
1628 while (!Stream.AtEndOfStream()) {
1629 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Douglas Gregorb64c1932009-05-12 01:31:05 +00001631 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1632 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Douglas Gregorb64c1932009-05-12 01:31:05 +00001634 // We only know the PCH subblock ID.
1635 switch (BlockID) {
1636 case pch::PCH_BLOCK_ID:
1637 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1638 fprintf(stderr, "error: malformed block record in PCH file\n");
1639 return std::string();
1640 }
1641 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Douglas Gregorb64c1932009-05-12 01:31:05 +00001643 default:
1644 if (Stream.SkipBlock()) {
1645 fprintf(stderr, "error: malformed block record in PCH file\n");
1646 return std::string();
1647 }
1648 break;
1649 }
1650 continue;
1651 }
1652
1653 if (Code == llvm::bitc::END_BLOCK) {
1654 if (Stream.ReadBlockEnd()) {
1655 fprintf(stderr, "error: error at end of module block in PCH file\n");
1656 return std::string();
1657 }
1658 continue;
1659 }
1660
1661 if (Code == llvm::bitc::DEFINE_ABBREV) {
1662 Stream.ReadAbbrevRecord();
1663 continue;
1664 }
1665
1666 Record.clear();
1667 const char *BlobStart = 0;
1668 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001669 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00001670 == pch::ORIGINAL_FILE_NAME)
1671 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001672 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00001673
1674 return std::string();
1675}
1676
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001677/// \brief Parse the record that corresponds to a LangOptions data
1678/// structure.
1679///
1680/// This routine compares the language options used to generate the
1681/// PCH file against the language options set for the current
1682/// compilation. For each option, we classify differences between the
1683/// two compiler states as either "benign" or "important". Benign
1684/// differences don't matter, and we accept them without complaint
1685/// (and without modifying the language options). Differences between
1686/// the states for important options cause the PCH file to be
1687/// unusable, so we emit a warning and return true to indicate that
1688/// there was an error.
1689///
1690/// \returns true if the PCH file is unacceptable, false otherwise.
1691bool PCHReader::ParseLanguageOptions(
1692 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001693 if (Listener) {
1694 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001696 #define PARSE_LANGOPT(Option) \
1697 LangOpts.Option = Record[Idx]; \
1698 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001700 unsigned Idx = 0;
1701 PARSE_LANGOPT(Trigraphs);
1702 PARSE_LANGOPT(BCPLComment);
1703 PARSE_LANGOPT(DollarIdents);
1704 PARSE_LANGOPT(AsmPreprocessor);
1705 PARSE_LANGOPT(GNUMode);
1706 PARSE_LANGOPT(ImplicitInt);
1707 PARSE_LANGOPT(Digraphs);
1708 PARSE_LANGOPT(HexFloats);
1709 PARSE_LANGOPT(C99);
1710 PARSE_LANGOPT(Microsoft);
1711 PARSE_LANGOPT(CPlusPlus);
1712 PARSE_LANGOPT(CPlusPlus0x);
1713 PARSE_LANGOPT(CXXOperatorNames);
1714 PARSE_LANGOPT(ObjC1);
1715 PARSE_LANGOPT(ObjC2);
1716 PARSE_LANGOPT(ObjCNonFragileABI);
1717 PARSE_LANGOPT(PascalStrings);
1718 PARSE_LANGOPT(WritableStrings);
1719 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001720 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001721 PARSE_LANGOPT(Exceptions);
1722 PARSE_LANGOPT(NeXTRuntime);
1723 PARSE_LANGOPT(Freestanding);
1724 PARSE_LANGOPT(NoBuiltin);
1725 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00001726 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001727 PARSE_LANGOPT(Blocks);
1728 PARSE_LANGOPT(EmitAllDecls);
1729 PARSE_LANGOPT(MathErrno);
1730 PARSE_LANGOPT(OverflowChecking);
1731 PARSE_LANGOPT(HeinousExtensions);
1732 PARSE_LANGOPT(Optimize);
1733 PARSE_LANGOPT(OptimizeSize);
1734 PARSE_LANGOPT(Static);
1735 PARSE_LANGOPT(PICLevel);
1736 PARSE_LANGOPT(GNUInline);
1737 PARSE_LANGOPT(NoInline);
1738 PARSE_LANGOPT(AccessControl);
1739 PARSE_LANGOPT(CharIsSigned);
1740 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1741 ++Idx;
1742 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1743 ++Idx;
Daniel Dunbarab8e2812009-09-21 04:16:19 +00001744 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1745 Record[Idx]);
1746 ++Idx;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001747 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001748 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001749 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001750
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001751 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001752 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001753
1754 return false;
1755}
1756
Douglas Gregor2e222532009-07-02 17:08:52 +00001757void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1758 Comments.resize(NumComments);
1759 std::copy(this->Comments, this->Comments + NumComments,
1760 Comments.begin());
1761}
1762
Douglas Gregor2cf26342009-04-09 22:27:44 +00001763/// \brief Read and return the type at the given offset.
1764///
1765/// This routine actually reads the record corresponding to the type
1766/// at the given offset in the bitstream. It is a helper routine for
1767/// GetType, which deals with reading type IDs.
1768QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001769 // Keep track of where we are in the stream, then jump back there
1770 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001771 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001772
Douglas Gregord89275b2009-07-06 18:54:52 +00001773 // Note that we are loading a type record.
1774 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001776 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001777 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001778 unsigned Code = DeclsCursor.ReadCode();
1779 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001780 case pch::TYPE_EXT_QUAL: {
John McCall0953e762009-09-24 19:53:00 +00001781 assert(Record.size() == 2 &&
Douglas Gregor6d473962009-04-15 22:00:08 +00001782 "Incorrect encoding of extended qualifier type");
1783 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00001784 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1785 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00001786 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001787
Douglas Gregor2cf26342009-04-09 22:27:44 +00001788 case pch::TYPE_FIXED_WIDTH_INT: {
1789 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001790 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001791 }
1792
1793 case pch::TYPE_COMPLEX: {
1794 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1795 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001796 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001797 }
1798
1799 case pch::TYPE_POINTER: {
1800 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1801 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001802 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001803 }
1804
1805 case pch::TYPE_BLOCK_POINTER: {
1806 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1807 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001808 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001809 }
1810
1811 case pch::TYPE_LVALUE_REFERENCE: {
1812 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1813 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001814 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001815 }
1816
1817 case pch::TYPE_RVALUE_REFERENCE: {
1818 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1819 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001820 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001821 }
1822
1823 case pch::TYPE_MEMBER_POINTER: {
1824 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1825 QualType PointeeType = GetType(Record[0]);
1826 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001827 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001828 }
1829
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001830 case pch::TYPE_CONSTANT_ARRAY: {
1831 QualType ElementType = GetType(Record[0]);
1832 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1833 unsigned IndexTypeQuals = Record[2];
1834 unsigned Idx = 3;
1835 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001836 return Context->getConstantArrayType(ElementType, Size,
1837 ASM, IndexTypeQuals);
1838 }
1839
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001840 case pch::TYPE_INCOMPLETE_ARRAY: {
1841 QualType ElementType = GetType(Record[0]);
1842 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1843 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001844 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001845 }
1846
1847 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001848 QualType ElementType = GetType(Record[0]);
1849 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1850 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001851 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1852 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001853 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001854 ASM, IndexTypeQuals,
1855 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001856 }
1857
1858 case pch::TYPE_VECTOR: {
1859 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001860 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001861 return QualType();
1862 }
1863
1864 QualType ElementType = GetType(Record[0]);
1865 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001866 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001867 }
1868
1869 case pch::TYPE_EXT_VECTOR: {
1870 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001871 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001872 return QualType();
1873 }
1874
1875 QualType ElementType = GetType(Record[0]);
1876 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001877 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001878 }
1879
1880 case pch::TYPE_FUNCTION_NO_PROTO: {
1881 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001882 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001883 return QualType();
1884 }
1885 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001886 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001887 }
1888
1889 case pch::TYPE_FUNCTION_PROTO: {
1890 QualType ResultType = GetType(Record[0]);
1891 unsigned Idx = 1;
1892 unsigned NumParams = Record[Idx++];
1893 llvm::SmallVector<QualType, 16> ParamTypes;
1894 for (unsigned I = 0; I != NumParams; ++I)
1895 ParamTypes.push_back(GetType(Record[Idx++]));
1896 bool isVariadic = Record[Idx++];
1897 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001898 bool hasExceptionSpec = Record[Idx++];
1899 bool hasAnyExceptionSpec = Record[Idx++];
1900 unsigned NumExceptions = Record[Idx++];
1901 llvm::SmallVector<QualType, 2> Exceptions;
1902 for (unsigned I = 0; I != NumExceptions; ++I)
1903 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001904 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001905 isVariadic, Quals, hasExceptionSpec,
1906 hasAnyExceptionSpec, NumExceptions,
1907 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001908 }
1909
1910 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001911 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001912 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001913
1914 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001915 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001916
1917 case pch::TYPE_TYPEOF: {
1918 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001919 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001920 return QualType();
1921 }
1922 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001923 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001924 }
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Anders Carlsson395b4752009-06-24 19:06:50 +00001926 case pch::TYPE_DECLTYPE:
1927 return Context->getDecltypeType(ReadTypeExpr());
1928
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001929 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001930 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001931 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001932
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001933 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001934 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001935 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001936
John McCall7da24312009-09-05 00:15:47 +00001937 case pch::TYPE_ELABORATED: {
1938 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1939 unsigned Tag = Record[1];
1940 return Context->getElaboratedType(GetType(Record[0]),
1941 (ElaboratedType::TagKind) Tag);
1942 }
1943
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001944 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001945 unsigned Idx = 0;
1946 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1947 unsigned NumProtos = Record[Idx++];
1948 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1949 for (unsigned I = 0; I != NumProtos; ++I)
1950 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001951 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001952 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001953
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001954 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001955 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00001956 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001957 unsigned NumProtos = Record[Idx++];
1958 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1959 for (unsigned I = 0; I != NumProtos; ++I)
1960 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00001961 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001962 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00001963
1964 case pch::TYPE_OBJC_PROTOCOL_LIST: {
1965 unsigned Idx = 0;
1966 QualType OIT = GetType(Record[Idx++]);
1967 unsigned NumProtos = Record[Idx++];
1968 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1969 for (unsigned I = 0; I != NumProtos; ++I)
1970 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1971 return Context->getObjCProtocolListType(OIT, Protos.data(), NumProtos);
1972 }
John McCall49a832b2009-10-18 09:09:24 +00001973
1974 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
1975 unsigned Idx = 0;
1976 QualType Parm = GetType(Record[Idx++]);
1977 QualType Replacement = GetType(Record[Idx++]);
1978 return
1979 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
1980 Replacement);
1981 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001982 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001983 // Suppress a GCC warning
1984 return QualType();
1985}
1986
John McCalla1ee0c52009-10-16 21:56:05 +00001987namespace {
1988
1989class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
1990 PCHReader &Reader;
1991 const PCHReader::RecordData &Record;
1992 unsigned &Idx;
1993
1994public:
1995 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
1996 unsigned &Idx)
1997 : Reader(Reader), Record(Record), Idx(Idx) { }
1998
John McCall51bd8032009-10-18 01:05:36 +00001999 // We want compile-time assurance that we've enumerated all of
2000 // these, so unfortunately we have to declare them first, then
2001 // define them out-of-line.
2002#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00002003#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002004 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002005#include "clang/AST/TypeLocNodes.def"
2006
John McCall51bd8032009-10-18 01:05:36 +00002007 void VisitFunctionTypeLoc(FunctionTypeLoc);
2008 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002009};
2010
2011}
2012
John McCall51bd8032009-10-18 01:05:36 +00002013void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002014 // nothing to do
2015}
John McCall51bd8032009-10-18 01:05:36 +00002016void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2017 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002018}
John McCall51bd8032009-10-18 01:05:36 +00002019void TypeLocReader::VisitFixedWidthIntTypeLoc(FixedWidthIntTypeLoc TL) {
2020 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002021}
John McCall51bd8032009-10-18 01:05:36 +00002022void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2023 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002024}
John McCall51bd8032009-10-18 01:05:36 +00002025void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2026 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002027}
John McCall51bd8032009-10-18 01:05:36 +00002028void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2029 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002030}
John McCall51bd8032009-10-18 01:05:36 +00002031void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2032 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002033}
John McCall51bd8032009-10-18 01:05:36 +00002034void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2035 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002036}
John McCall51bd8032009-10-18 01:05:36 +00002037void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2038 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002039}
John McCall51bd8032009-10-18 01:05:36 +00002040void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2041 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2042 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002043 if (Record[Idx++])
John McCall51bd8032009-10-18 01:05:36 +00002044 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002045 else
John McCall51bd8032009-10-18 01:05:36 +00002046 TL.setSizeExpr(0);
2047}
2048void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2049 VisitArrayTypeLoc(TL);
2050}
2051void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2052 VisitArrayTypeLoc(TL);
2053}
2054void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2055 VisitArrayTypeLoc(TL);
2056}
2057void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2058 DependentSizedArrayTypeLoc TL) {
2059 VisitArrayTypeLoc(TL);
2060}
2061void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2062 DependentSizedExtVectorTypeLoc TL) {
2063 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2064}
2065void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2066 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2067}
2068void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2069 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2070}
2071void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2072 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2073 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2074 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
2075 TL.setArg(i, cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
2076 }
2077}
2078void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2079 VisitFunctionTypeLoc(TL);
2080}
2081void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2082 VisitFunctionTypeLoc(TL);
2083}
2084void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2085 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2086}
2087void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2088 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2089}
2090void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2091 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2092}
2093void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2094 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2095}
2096void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2097 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2098}
2099void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2100 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2101}
2102void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2103 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2104}
2105void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2106 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2107}
John McCall49a832b2009-10-18 09:09:24 +00002108void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2109 SubstTemplateTypeParmTypeLoc TL) {
2110 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2111}
John McCall51bd8032009-10-18 01:05:36 +00002112void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2113 TemplateSpecializationTypeLoc TL) {
2114 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2115}
2116void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2117 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2118}
2119void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2120 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2121}
2122void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2123 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2124}
2125void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2126 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2127}
2128void TypeLocReader::VisitObjCProtocolListTypeLoc(ObjCProtocolListTypeLoc TL) {
2129 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2130 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2131 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2132 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002133}
2134
2135DeclaratorInfo *PCHReader::GetDeclaratorInfo(const RecordData &Record,
2136 unsigned &Idx) {
2137 QualType InfoTy = GetType(Record[Idx++]);
2138 if (InfoTy.isNull())
2139 return 0;
2140
2141 DeclaratorInfo *DInfo = getContext()->CreateDeclaratorInfo(InfoTy);
2142 TypeLocReader TLR(*this, Record, Idx);
2143 for (TypeLoc TL = DInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2144 TLR.Visit(TL);
2145 return DInfo;
2146}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002147
Douglas Gregor8038d512009-04-10 17:25:41 +00002148QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002149 unsigned FastQuals = ID & Qualifiers::FastMask;
2150 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002151
2152 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2153 QualType T;
2154 switch ((pch::PredefinedTypeIDs)Index) {
2155 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002156 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2157 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002158
2159 case pch::PREDEF_TYPE_CHAR_U_ID:
2160 case pch::PREDEF_TYPE_CHAR_S_ID:
2161 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002162 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002163 break;
2164
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002165 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2166 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2167 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2168 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2169 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002170 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002171 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2172 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2173 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2174 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2175 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2176 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002177 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002178 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2179 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2180 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2181 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2182 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002183 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002184 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2185 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002186 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2187 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002188 }
2189
2190 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002191 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002192 }
2193
2194 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002195 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall0953e762009-09-24 19:53:00 +00002196 if (TypesLoaded[Index].isNull())
2197 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump1eb44332009-09-09 15:08:12 +00002198
John McCall0953e762009-09-24 19:53:00 +00002199 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002200}
2201
Douglas Gregor8038d512009-04-10 17:25:41 +00002202Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002203 if (ID == 0)
2204 return 0;
2205
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002206 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002207 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002208 return 0;
2209 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002210
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002211 unsigned Index = ID - 1;
2212 if (!DeclsLoaded[Index])
2213 ReadDeclRecord(DeclOffsets[Index], Index);
2214
2215 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002216}
2217
Chris Lattner887e2b32009-04-27 05:46:25 +00002218/// \brief Resolve the offset of a statement into a statement.
2219///
2220/// This operation will read a new statement from the external
2221/// source each time it is called, and is meant to be used via a
2222/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2223Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002224 // Since we know tha this statement is part of a decl, make sure to use the
2225 // decl cursor to read it.
2226 DeclsCursor.JumpToBit(Offset);
2227 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002228}
2229
Douglas Gregor2cf26342009-04-09 22:27:44 +00002230bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002231 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002232 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002233 "DeclContext has no lexical decls in storage");
2234 uint64_t Offset = DeclContextOffsets[DC].first;
2235 assert(Offset && "DeclContext has no lexical decls in storage");
2236
Douglas Gregor0b748912009-04-14 21:18:50 +00002237 // Keep track of where we are in the stream, then jump back there
2238 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002239 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002240
Douglas Gregor2cf26342009-04-09 22:27:44 +00002241 // Load the record containing all of the declarations lexically in
2242 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002243 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002244 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002245 unsigned Code = DeclsCursor.ReadCode();
2246 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002247 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002248 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2249
2250 // Load all of the declaration IDs
2251 Decls.clear();
2252 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002253 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002254 return false;
2255}
2256
2257bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002258 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002259 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002260 "DeclContext has no visible decls in storage");
2261 uint64_t Offset = DeclContextOffsets[DC].second;
2262 assert(Offset && "DeclContext has no visible decls in storage");
2263
Douglas Gregor0b748912009-04-14 21:18:50 +00002264 // Keep track of where we are in the stream, then jump back there
2265 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002266 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002267
Douglas Gregor2cf26342009-04-09 22:27:44 +00002268 // Load the record containing all of the declarations visible in
2269 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002270 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002271 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002272 unsigned Code = DeclsCursor.ReadCode();
2273 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002274 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002275 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2276 if (Record.size() == 0)
Mike Stump1eb44332009-09-09 15:08:12 +00002277 return false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002278
2279 Decls.clear();
2280
2281 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002282 while (Idx < Record.size()) {
2283 Decls.push_back(VisibleDeclaration());
2284 Decls.back().Name = ReadDeclarationName(Record, Idx);
2285
Douglas Gregor2cf26342009-04-09 22:27:44 +00002286 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002287 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002288 LoadedDecls.reserve(Size);
2289 for (unsigned I = 0; I < Size; ++I)
2290 LoadedDecls.push_back(Record[Idx++]);
2291 }
2292
Douglas Gregor25123082009-04-22 22:34:57 +00002293 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002294 return false;
2295}
2296
Douglas Gregorfdd01722009-04-14 00:24:19 +00002297void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002298 this->Consumer = Consumer;
2299
Douglas Gregorfdd01722009-04-14 00:24:19 +00002300 if (!Consumer)
2301 return;
2302
2303 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002304 // Force deserialization of this decl, which will cause it to be passed to
2305 // the consumer (or queued).
2306 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002307 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002308
2309 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2310 DeclGroupRef DG(InterestingDecls[I]);
2311 Consumer->HandleTopLevelDecl(DG);
2312 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002313}
2314
Douglas Gregor2cf26342009-04-09 22:27:44 +00002315void PCHReader::PrintStats() {
2316 std::fprintf(stderr, "*** PCH Statistics:\n");
2317
Mike Stump1eb44332009-09-09 15:08:12 +00002318 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002319 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002320 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002321 unsigned NumDeclsLoaded
2322 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2323 (Decl *)0);
2324 unsigned NumIdentifiersLoaded
2325 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2326 IdentifiersLoaded.end(),
2327 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002328 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002329 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2330 SelectorsLoaded.end(),
2331 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002332
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002333 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2334 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002335 if (TotalNumSLocEntries)
2336 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2337 NumSLocEntriesRead, TotalNumSLocEntries,
2338 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002339 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002340 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002341 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2342 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2343 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002344 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002345 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2346 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002347 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002348 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002349 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2350 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002351 if (TotalNumSelectors)
2352 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2353 NumSelectorsLoaded, TotalNumSelectors,
2354 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2355 if (TotalNumStatements)
2356 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2357 NumStatementsRead, TotalNumStatements,
2358 ((float)NumStatementsRead/TotalNumStatements * 100));
2359 if (TotalNumMacros)
2360 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2361 NumMacrosRead, TotalNumMacros,
2362 ((float)NumMacrosRead/TotalNumMacros * 100));
2363 if (TotalLexicalDeclContexts)
2364 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2365 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2366 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2367 * 100));
2368 if (TotalVisibleDeclContexts)
2369 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2370 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2371 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2372 * 100));
2373 if (TotalSelectorsInMethodPool) {
2374 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2375 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2376 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2377 * 100));
2378 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2379 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002380 std::fprintf(stderr, "\n");
2381}
2382
Douglas Gregor668c1a42009-04-21 22:25:48 +00002383void PCHReader::InitializeSema(Sema &S) {
2384 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002385 S.ExternalSource = this;
2386
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002387 // Makes sure any declarations that were deserialized "too early"
2388 // still get added to the identifier's declaration chains.
2389 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2390 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2391 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002392 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002393 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002394
2395 // If there were any tentative definitions, deserialize them and add
2396 // them to Sema's table of tentative definitions.
2397 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2398 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2399 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner63d65f82009-09-08 18:19:27 +00002400 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002401 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002402
2403 // If there were any locally-scoped external declarations,
2404 // deserialize them and add them to Sema's table of locally-scoped
2405 // external declarations.
2406 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2407 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2408 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2409 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002410
2411 // If there were any ext_vector type declarations, deserialize them
2412 // and add them to Sema's vector of such declarations.
2413 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2414 SemaObj->ExtVectorDecls.push_back(
2415 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002416}
2417
2418IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2419 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00002420 PCHIdentifierLookupTable *IdTable
Douglas Gregor668c1a42009-04-21 22:25:48 +00002421 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2422 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2423 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2424 if (Pos == IdTable->end())
2425 return 0;
2426
2427 // Dereferencing the iterator has the effect of building the
2428 // IdentifierInfo node and populating it with the various
2429 // declarations it needs.
2430 return *Pos;
2431}
2432
Mike Stump1eb44332009-09-09 15:08:12 +00002433std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002434PCHReader::ReadMethodPool(Selector Sel) {
2435 if (!MethodPoolLookupTable)
2436 return std::pair<ObjCMethodList, ObjCMethodList>();
2437
2438 // Try to find this selector within our on-disk hash table.
2439 PCHMethodPoolLookupTable *PoolTable
2440 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2441 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002442 if (Pos == PoolTable->end()) {
2443 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002444 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002445 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002446
Douglas Gregor83941df2009-04-25 17:48:32 +00002447 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002448 return *Pos;
2449}
2450
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002451void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002452 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002453 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002454 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002455}
2456
Douglas Gregord89275b2009-07-06 18:54:52 +00002457/// \brief Set the globally-visible declarations associated with the given
2458/// identifier.
2459///
2460/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00002461/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00002462/// them.
2463///
2464/// \param II an IdentifierInfo that refers to one or more globally-visible
2465/// declarations.
2466///
2467/// \param DeclIDs the set of declaration IDs with the name @p II that are
2468/// visible at global scope.
2469///
2470/// \param Nonrecursive should be true to indicate that the caller knows that
2471/// this call is non-recursive, and therefore the globally-visible declarations
2472/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00002473void
2474PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00002475 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2476 bool Nonrecursive) {
2477 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2478 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2479 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2480 PII.II = II;
2481 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2482 PII.DeclIDs.push_back(DeclIDs[I]);
2483 return;
2484 }
Mike Stump1eb44332009-09-09 15:08:12 +00002485
Douglas Gregord89275b2009-07-06 18:54:52 +00002486 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2487 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2488 if (SemaObj) {
2489 // Introduce this declaration into the translation-unit scope
2490 // and add it to the declaration chain for this identifier, so
2491 // that (unqualified) name lookup will find it.
2492 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2493 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2494 } else {
2495 // Queue this declaration so that it will be added to the
2496 // translation unit scope and identifier's declaration chain
2497 // once a Sema object is known.
2498 PreloadedDecls.push_back(D);
2499 }
2500 }
2501}
2502
Chris Lattner7356a312009-04-11 21:15:38 +00002503IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002504 if (ID == 0)
2505 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002506
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002507 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002508 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002509 return 0;
2510 }
Mike Stump1eb44332009-09-09 15:08:12 +00002511
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002512 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002513 if (!IdentifiersLoaded[ID - 1]) {
2514 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002515 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002516
Douglas Gregor02fc7512009-04-28 20:01:51 +00002517 // All of the strings in the PCH file are preceded by a 16-bit
2518 // length. Extract that 16-bit length to avoid having to execute
2519 // strlen().
2520 const char *StrLenPtr = Str - 2;
2521 unsigned StrLen = (((unsigned) StrLenPtr[0])
2522 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002523 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002524 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002525 }
Mike Stump1eb44332009-09-09 15:08:12 +00002526
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002527 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002528}
2529
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002530void PCHReader::ReadSLocEntry(unsigned ID) {
2531 ReadSLocEntryRecord(ID);
2532}
2533
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002534Selector PCHReader::DecodeSelector(unsigned ID) {
2535 if (ID == 0)
2536 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Douglas Gregora02b1472009-04-28 21:53:25 +00002538 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002539 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002540
2541 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002542 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002543 return Selector();
2544 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002545
2546 unsigned Index = ID - 1;
2547 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2548 // Load this selector from the selector table.
2549 // FIXME: endianness portability issues with SelectorOffsets table
2550 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002551 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00002552 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2553 }
2554
2555 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002556}
2557
Mike Stump1eb44332009-09-09 15:08:12 +00002558DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00002559PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2560 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2561 switch (Kind) {
2562 case DeclarationName::Identifier:
2563 return DeclarationName(GetIdentifierInfo(Record, Idx));
2564
2565 case DeclarationName::ObjCZeroArgSelector:
2566 case DeclarationName::ObjCOneArgSelector:
2567 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002568 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002569
2570 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002571 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002572 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002573
2574 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002575 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002576 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002577
2578 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002579 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002580 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002581
2582 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002583 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002584 (OverloadedOperatorKind)Record[Idx++]);
2585
2586 case DeclarationName::CXXUsingDirective:
2587 return DeclarationName::getUsingDirectiveName();
2588 }
2589
2590 // Required to silence GCC warning
2591 return DeclarationName();
2592}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002593
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002594/// \brief Read an integral value
2595llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2596 unsigned BitWidth = Record[Idx++];
2597 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2598 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2599 Idx += NumWords;
2600 return Result;
2601}
2602
2603/// \brief Read a signed integral value
2604llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2605 bool isUnsigned = Record[Idx++];
2606 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2607}
2608
Douglas Gregor17fc2232009-04-14 21:55:33 +00002609/// \brief Read a floating-point value
2610llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002611 return llvm::APFloat(ReadAPInt(Record, Idx));
2612}
2613
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002614// \brief Read a string
2615std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2616 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002617 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002618 Idx += Len;
2619 return Result;
2620}
2621
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002622DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002623 return Diag(SourceLocation(), DiagID);
2624}
2625
2626DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002627 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002628}
Douglas Gregor025452f2009-04-17 00:04:06 +00002629
Douglas Gregor668c1a42009-04-21 22:25:48 +00002630/// \brief Retrieve the identifier table associated with the
2631/// preprocessor.
2632IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002633 assert(PP && "Forgot to set Preprocessor ?");
2634 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002635}
2636
Douglas Gregor025452f2009-04-17 00:04:06 +00002637/// \brief Record that the given ID maps to the given switch-case
2638/// statement.
2639void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2640 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2641 SwitchCaseStmts[ID] = SC;
2642}
2643
2644/// \brief Retrieve the switch-case statement with the given ID.
2645SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2646 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2647 return SwitchCaseStmts[ID];
2648}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002649
2650/// \brief Record that the given label statement has been
2651/// deserialized and has the given ID.
2652void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00002653 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002654 "Deserialized label twice");
2655 LabelStmts[ID] = S;
2656
2657 // If we've already seen any goto statements that point to this
2658 // label, resolve them now.
2659 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2660 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2661 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2662 Goto->second->setLabel(S);
2663 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002664
2665 // If we've already seen any address-label statements that point to
2666 // this label, resolve them now.
2667 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00002668 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002669 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002670 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002671 AddrLabel != AddrLabels.second; ++AddrLabel)
2672 AddrLabel->second->setLabel(S);
2673 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002674}
2675
2676/// \brief Set the label of the given statement to the label
2677/// identified by ID.
2678///
2679/// Depending on the order in which the label and other statements
2680/// referencing that label occur, this operation may complete
2681/// immediately (updating the statement) or it may queue the
2682/// statement to be back-patched later.
2683void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2684 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2685 if (Label != LabelStmts.end()) {
2686 // We've already seen this label, so set the label of the goto and
2687 // we're done.
2688 S->setLabel(Label->second);
2689 } else {
2690 // We haven't seen this label yet, so add this goto to the set of
2691 // unresolved goto statements.
2692 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2693 }
2694}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002695
2696/// \brief Set the label of the given expression to the label
2697/// identified by ID.
2698///
2699/// Depending on the order in which the label and other statements
2700/// referencing that label occur, this operation may complete
2701/// immediately (updating the statement) or it may queue the
2702/// statement to be back-patched later.
2703void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2704 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2705 if (Label != LabelStmts.end()) {
2706 // We've already seen this label, so set the label of the
2707 // label-address expression and we're done.
2708 S->setLabel(Label->second);
2709 } else {
2710 // We haven't seen this label yet, so add this label-address
2711 // expression to the set of unresolved label-address expressions.
2712 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2713 }
2714}
Douglas Gregord89275b2009-07-06 18:54:52 +00002715
2716
Mike Stump1eb44332009-09-09 15:08:12 +00002717PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00002718 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2719 Reader.CurrentlyLoadingTypeOrDecl = this;
2720}
2721
2722PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2723 if (!Parent) {
2724 // If any identifiers with corresponding top-level declarations have
2725 // been loaded, load those declarations now.
2726 while (!Reader.PendingIdentifierInfos.empty()) {
2727 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2728 Reader.PendingIdentifierInfos.front().DeclIDs,
2729 true);
2730 Reader.PendingIdentifierInfos.pop_front();
2731 }
2732 }
2733
Mike Stump1eb44332009-09-09 15:08:12 +00002734 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00002735}