blob: 141f7c8ab24ca10e95388bc0f85f44a357191a03 [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000021#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000024#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000029#include "clang/Basic/Version.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000030#include "llvm/Bitcode/BitstreamReader.h"
31#include "llvm/Support/Compiler.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000034#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000035#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000036#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000037using namespace clang;
38
39//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000040// PCH reader validator implementation
41//===----------------------------------------------------------------------===//
42
43PCHReaderListener::~PCHReaderListener() {}
44
45bool
46PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
47 const LangOptions &PPLangOpts = PP.getLangOptions();
48#define PARSE_LANGOPT_BENIGN(Option)
49#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
50 if (PPLangOpts.Option != LangOpts.Option) { \
51 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
52 return true; \
53 }
54
55 PARSE_LANGOPT_BENIGN(Trigraphs);
56 PARSE_LANGOPT_BENIGN(BCPLComment);
57 PARSE_LANGOPT_BENIGN(DollarIdents);
58 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
59 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
60 PARSE_LANGOPT_BENIGN(ImplicitInt);
61 PARSE_LANGOPT_BENIGN(Digraphs);
62 PARSE_LANGOPT_BENIGN(HexFloats);
63 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
64 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
65 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
66 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
67 PARSE_LANGOPT_BENIGN(CXXOperatorName);
68 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
69 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
70 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
71 PARSE_LANGOPT_BENIGN(PascalStrings);
72 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000073 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000074 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000075 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000076 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
77 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
78 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
79 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump1eb44332009-09-09 15:08:12 +000080 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000081 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000082 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000083 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
84 PARSE_LANGOPT_BENIGN(EmitAllDecls);
85 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
86 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump1eb44332009-09-09 15:08:12 +000087 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000088 diag::warn_pch_heinous_extensions);
89 // FIXME: Most of the options below are benign if the macro wasn't
90 // used. Unfortunately, this means that a PCH compiled without
91 // optimization can't be used with optimization turned on, even
92 // though the only thing that changes is whether __OPTIMIZE__ was
93 // defined... but if __OPTIMIZE__ never showed up in the header, it
94 // doesn't matter. We could consider making this some special kind
95 // of check.
96 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
97 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
98 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
99 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
100 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
101 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
102 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
103 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
104 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000105 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000106 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
107 return true;
108 }
109 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000110 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
111 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000112 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000113 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000114 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000115#undef PARSE_LANGOPT_IRRELEVANT
116#undef PARSE_LANGOPT_BENIGN
117
118 return false;
119}
120
121bool PCHValidator::ReadTargetTriple(const std::string &Triple) {
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000122 if (Triple != PP.getTargetInfo().getTriple().getTriple()) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000123 Reader.Diag(diag::warn_pch_target_triple)
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000124 << Triple << PP.getTargetInfo().getTriple().getTriple();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000125 return true;
126 }
127 return false;
128}
129
130/// \brief Split the given string into a vector of lines, eliminating
131/// any empty lines in the process.
132///
133/// \param Str the string to split.
134/// \param Len the length of Str.
135/// \param KeepEmptyLines true if empty lines should be included
136/// \returns a vector of lines, with the line endings removed
137static std::vector<std::string> splitLines(const char *Str, unsigned Len,
138 bool KeepEmptyLines = false) {
139 std::vector<std::string> Lines;
140 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
141 unsigned LineEnd = LineStart;
142 while (LineEnd < Len && Str[LineEnd] != '\n')
143 ++LineEnd;
144 if (LineStart != LineEnd || KeepEmptyLines)
145 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
146 LineStart = LineEnd;
147 }
148 return Lines;
149}
150
151/// \brief Determine whether the string Haystack starts with the
152/// substring Needle.
153static bool startsWith(const std::string &Haystack, const char *Needle) {
154 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
155 if (I == N)
156 return false;
157 if (Haystack[I] != Needle[I])
158 return false;
159 }
160
161 return true;
162}
163
164/// \brief Determine whether the string Haystack starts with the
165/// substring Needle.
166static inline bool startsWith(const std::string &Haystack,
167 const std::string &Needle) {
168 return startsWith(Haystack, Needle.c_str());
169}
170
Mike Stump1eb44332009-09-09 15:08:12 +0000171bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000172 unsigned PCHPredefLen,
173 FileID PCHBufferID,
174 std::string &SuggestedPredefines) {
175 const char *Predef = PP.getPredefines().c_str();
176 unsigned PredefLen = PP.getPredefines().size();
177
178 // If the two predefines buffers compare equal, we're done!
Mike Stump1eb44332009-09-09 15:08:12 +0000179 if (PredefLen == PCHPredefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000180 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
181 return false;
182
183 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000185 // The predefines buffers are different. Determine what the
186 // differences are, and whether they require us to reject the PCH
187 // file.
188 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
189 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
190
Mike Stump1eb44332009-09-09 15:08:12 +0000191 // Sort both sets of predefined buffer lines, since
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000192 std::sort(CmdLineLines.begin(), CmdLineLines.end());
193 std::sort(PCHLines.begin(), PCHLines.end());
194
195 // Determine which predefines that where used to build the PCH file
196 // are missing from the command line.
197 std::vector<std::string> MissingPredefines;
198 std::set_difference(PCHLines.begin(), PCHLines.end(),
199 CmdLineLines.begin(), CmdLineLines.end(),
200 std::back_inserter(MissingPredefines));
201
202 bool MissingDefines = false;
203 bool ConflictingDefines = false;
204 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
205 const std::string &Missing = MissingPredefines[I];
206 if (!startsWith(Missing, "#define ") != 0) {
207 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
208 return true;
209 }
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000211 // This is a macro definition. Determine the name of the macro
212 // we're defining.
213 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000214 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000215 = Missing.find_first_of("( \n\r", StartOfMacroName);
216 assert(EndOfMacroName != std::string::npos &&
217 "Couldn't find the end of the macro name");
218 std::string MacroName = Missing.substr(StartOfMacroName,
219 EndOfMacroName - StartOfMacroName);
220
221 // Determine whether this macro was given a different definition
222 // on the command line.
223 std::string MacroDefStart = "#define " + MacroName;
224 std::string::size_type MacroDefLen = MacroDefStart.size();
225 std::vector<std::string>::iterator ConflictPos
226 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
227 MacroDefStart);
228 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
229 if (!startsWith(*ConflictPos, MacroDefStart)) {
230 // Different macro; we're done.
231 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000232 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000233 }
Mike Stump1eb44332009-09-09 15:08:12 +0000234
235 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000236 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000237 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000238 (*ConflictPos)[MacroDefLen] != '(')
239 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000241 // We found a conflicting macro definition.
242 break;
243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000245 if (ConflictPos != CmdLineLines.end()) {
246 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
247 << MacroName;
248
249 // Show the definition of this macro within the PCH file.
250 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
251 unsigned Offset = MissingDef - PCHPredef;
252 SourceLocation PCHMissingLoc
253 = SourceMgr.getLocForStartOfFile(PCHBufferID)
254 .getFileLocWithOffset(Offset);
255 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
256 << MacroName;
257
258 ConflictingDefines = true;
259 continue;
260 }
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000262 // If the macro doesn't conflict, then we'll just pick up the
263 // macro definition from the PCH file. Warn the user that they
264 // made a mistake.
265 if (ConflictingDefines)
266 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000268 if (!MissingDefines) {
269 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
270 MissingDefines = true;
271 }
272
273 // Show the definition of this macro within the PCH file.
274 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
275 unsigned Offset = MissingDef - PCHPredef;
276 SourceLocation PCHMissingLoc
277 = SourceMgr.getLocForStartOfFile(PCHBufferID)
278 .getFileLocWithOffset(Offset);
279 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
280 }
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000282 if (ConflictingDefines)
283 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000285 // Determine what predefines were introduced based on command-line
286 // parameters that were not present when building the PCH
287 // file. Extra #defines are okay, so long as the identifiers being
288 // defined were not used within the precompiled header.
289 std::vector<std::string> ExtraPredefines;
290 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
291 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000292 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000293 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
294 const std::string &Extra = ExtraPredefines[I];
295 if (!startsWith(Extra, "#define ") != 0) {
296 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
297 return true;
298 }
299
300 // This is an extra macro definition. Determine the name of the
301 // macro we're defining.
302 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000303 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000304 = Extra.find_first_of("( \n\r", StartOfMacroName);
305 assert(EndOfMacroName != std::string::npos &&
306 "Couldn't find the end of the macro name");
307 std::string MacroName = Extra.substr(StartOfMacroName,
308 EndOfMacroName - StartOfMacroName);
309
310 // Check whether this name was used somewhere in the PCH file. If
311 // so, defining it as a macro could change behavior, so we reject
312 // the PCH file.
313 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
314 MacroName.c_str() + MacroName.size())) {
315 Reader.Diag(diag::warn_macro_name_used_in_pch)
316 << II;
317 return true;
318 }
319
320 // Add this definition to the suggested predefines buffer.
321 SuggestedPredefines += Extra;
322 SuggestedPredefines += '\n';
323 }
324
325 // If we get here, it's because the predefines buffer had compatible
326 // contents. Accept the PCH file.
327 return false;
328}
329
330void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
331 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
332}
333
334void PCHValidator::ReadCounter(unsigned Value) {
335 PP.setCounterValue(Value);
336}
337
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000338//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000339// PCH reader implementation
340//===----------------------------------------------------------------------===//
341
Mike Stump1eb44332009-09-09 15:08:12 +0000342PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
343 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000344 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
345 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregor52e71082009-10-16 18:18:30 +0000346 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000347 IdentifierTableData(0), IdentifierLookupTable(0),
348 IdentifierOffsets(0),
349 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
350 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000351 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000352 NumStatHits(0), NumStatMisses(0),
353 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000354 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000355 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000356 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000357 RelocatablePCH = false;
358}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000359
360PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000361 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000362 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregor52e71082009-10-16 18:18:30 +0000363 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000364 IdentifierTableData(0), IdentifierLookupTable(0),
365 IdentifierOffsets(0),
366 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
367 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000368 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000369 NumStatHits(0), NumStatMisses(0),
370 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000371 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000372 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000373 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000374 RelocatablePCH = false;
375}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000376
377PCHReader::~PCHReader() {}
378
Chris Lattnerda930612009-04-27 05:58:23 +0000379Expr *PCHReader::ReadDeclExpr() {
380 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
381}
382
383Expr *PCHReader::ReadTypeExpr() {
Chris Lattner52e97d12009-04-27 05:41:06 +0000384 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000385}
386
387
Douglas Gregor668c1a42009-04-21 22:25:48 +0000388namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000389class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
390 PCHReader &Reader;
391
392public:
393 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
394
395 typedef Selector external_key_type;
396 typedef external_key_type internal_key_type;
397
398 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000400 static bool EqualKey(const internal_key_type& a,
401 const internal_key_type& b) {
402 return a == b;
403 }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000405 static unsigned ComputeHash(Selector Sel) {
406 unsigned N = Sel.getNumArgs();
407 if (N == 0)
408 ++N;
409 unsigned R = 5381;
410 for (unsigned I = 0; I != N; ++I)
411 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
412 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
413 return R;
414 }
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000416 // This hopefully will just get inlined and removed by the optimizer.
417 static const internal_key_type&
418 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000420 static std::pair<unsigned, unsigned>
421 ReadKeyDataLength(const unsigned char*& d) {
422 using namespace clang::io;
423 unsigned KeyLen = ReadUnalignedLE16(d);
424 unsigned DataLen = ReadUnalignedLE16(d);
425 return std::make_pair(KeyLen, DataLen);
426 }
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Douglas Gregor83941df2009-04-25 17:48:32 +0000428 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000429 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000430 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000431 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000432 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000433 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
434 if (N == 0)
435 return SelTable.getNullarySelector(FirstII);
436 else if (N == 1)
437 return SelTable.getUnarySelector(FirstII);
438
439 llvm::SmallVector<IdentifierInfo *, 16> Args;
440 Args.push_back(FirstII);
441 for (unsigned I = 1; I != N; ++I)
442 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
443
Douglas Gregor75fdb232009-05-22 22:45:36 +0000444 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000445 }
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000447 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
448 using namespace clang::io;
449 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
450 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
451
452 data_type Result;
453
454 // Load instance methods
455 ObjCMethodList *Prev = 0;
456 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000457 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000458 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
459 if (!Result.first.Method) {
460 // This is the first method, which is the easy case.
461 Result.first.Method = Method;
462 Prev = &Result.first;
463 continue;
464 }
465
466 Prev->Next = new ObjCMethodList(Method, 0);
467 Prev = Prev->Next;
468 }
469
470 // Load factory methods
471 Prev = 0;
472 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000473 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000474 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
475 if (!Result.second.Method) {
476 // This is the first method, which is the easy case.
477 Result.second.Method = Method;
478 Prev = &Result.second;
479 continue;
480 }
481
482 Prev->Next = new ObjCMethodList(Method, 0);
483 Prev = Prev->Next;
484 }
485
486 return Result;
487 }
488};
Mike Stump1eb44332009-09-09 15:08:12 +0000489
490} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000491
492/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000493typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000494 PCHMethodPoolLookupTable;
495
496namespace {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000497class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
498 PCHReader &Reader;
499
500 // If we know the IdentifierInfo in advance, it is here and we will
501 // not build a new one. Used when deserializing information about an
502 // identifier that was constructed before the PCH file was read.
503 IdentifierInfo *KnownII;
504
505public:
506 typedef IdentifierInfo * data_type;
507
508 typedef const std::pair<const char*, unsigned> external_key_type;
509
510 typedef external_key_type internal_key_type;
511
Mike Stump1eb44332009-09-09 15:08:12 +0000512 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000513 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Douglas Gregor668c1a42009-04-21 22:25:48 +0000515 static bool EqualKey(const internal_key_type& a,
516 const internal_key_type& b) {
517 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
518 : false;
519 }
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Douglas Gregor668c1a42009-04-21 22:25:48 +0000521 static unsigned ComputeHash(const internal_key_type& a) {
522 return BernsteinHash(a.first, a.second);
523 }
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Douglas Gregor668c1a42009-04-21 22:25:48 +0000525 // This hopefully will just get inlined and removed by the optimizer.
526 static const internal_key_type&
527 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Douglas Gregor668c1a42009-04-21 22:25:48 +0000529 static std::pair<unsigned, unsigned>
530 ReadKeyDataLength(const unsigned char*& d) {
531 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000532 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000533 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000534 return std::make_pair(KeyLen, DataLen);
535 }
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Douglas Gregor668c1a42009-04-21 22:25:48 +0000537 static std::pair<const char*, unsigned>
538 ReadKey(const unsigned char* d, unsigned n) {
539 assert(n >= 2 && d[n-1] == '\0');
540 return std::make_pair((const char*) d, n-1);
541 }
Mike Stump1eb44332009-09-09 15:08:12 +0000542
543 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000544 const unsigned char* d,
545 unsigned DataLen) {
546 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000547 pch::IdentID ID = ReadUnalignedLE32(d);
548 bool IsInteresting = ID & 0x01;
549
550 // Wipe out the "is interesting" bit.
551 ID = ID >> 1;
552
553 if (!IsInteresting) {
554 // For unintersting identifiers, just build the IdentifierInfo
555 // and associate it with the persistent ID.
556 IdentifierInfo *II = KnownII;
557 if (!II)
558 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
559 k.first, k.first + k.second);
560 Reader.SetIdentifierInfo(ID, II);
561 return II;
562 }
563
Douglas Gregor5998da52009-04-28 21:32:13 +0000564 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000565 bool CPlusPlusOperatorKeyword = Bits & 0x01;
566 Bits >>= 1;
567 bool Poisoned = Bits & 0x01;
568 Bits >>= 1;
569 bool ExtensionToken = Bits & 0x01;
570 Bits >>= 1;
571 bool hasMacroDefinition = Bits & 0x01;
572 Bits >>= 1;
573 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
574 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Douglas Gregor2deaea32009-04-22 18:49:13 +0000576 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000577 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000578
579 // Build the IdentifierInfo itself and link the identifier ID with
580 // the new IdentifierInfo.
581 IdentifierInfo *II = KnownII;
582 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000583 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
584 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000585 Reader.SetIdentifierInfo(ID, II);
586
Douglas Gregor2deaea32009-04-22 18:49:13 +0000587 // Set or check the various bits in the IdentifierInfo structure.
588 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000589 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000590 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000591 "Incorrect extension token flag");
592 (void)ExtensionToken;
593 II->setIsPoisoned(Poisoned);
594 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
595 "Incorrect C++ operator keyword flag");
596 (void)CPlusPlusOperatorKeyword;
597
Douglas Gregor37e26842009-04-21 23:56:24 +0000598 // If this identifier is a macro, deserialize the macro
599 // definition.
600 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000601 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000602 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000603 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000604 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000605
606 // Read all of the declarations visible at global scope with this
607 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000608 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000609 if (DataLen > 0) {
610 llvm::SmallVector<uint32_t, 4> DeclIDs;
611 for (; DataLen > 0; DataLen -= 4)
612 DeclIDs.push_back(ReadUnalignedLE32(d));
613 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000614 }
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Douglas Gregor668c1a42009-04-21 22:25:48 +0000616 return II;
617 }
618};
Mike Stump1eb44332009-09-09 15:08:12 +0000619
620} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000621
622/// \brief The on-disk hash table used to contain information about
623/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000624typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000625 PCHIdentifierLookupTable;
626
Douglas Gregora02b1472009-04-28 21:53:25 +0000627bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000628 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
629 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000630 return true;
631}
632
Douglas Gregore1d918e2009-04-10 23:10:45 +0000633/// \brief Check the contents of the predefines buffer against the
634/// contents of the predefines buffer used to build the PCH file.
635///
636/// The contents of the two predefines buffers should be the same. If
637/// not, then some command-line option changed the preprocessor state
638/// and we must reject the PCH file.
639///
640/// \param PCHPredef The start of the predefines buffer in the PCH
641/// file.
642///
643/// \param PCHPredefLen The length of the predefines buffer in the PCH
644/// file.
645///
646/// \param PCHBufferID The FileID for the PCH predefines buffer.
647///
648/// \returns true if there was a mismatch (in which case the PCH file
649/// should be ignored), or false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +0000650bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000651 unsigned PCHPredefLen,
652 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000653 if (Listener)
654 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
655 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000656 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000657}
658
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000659//===----------------------------------------------------------------------===//
660// Source Manager Deserialization
661//===----------------------------------------------------------------------===//
662
Douglas Gregorbd945002009-04-13 16:31:14 +0000663/// \brief Read the line table in the source manager block.
664/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000665bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000666 unsigned Idx = 0;
667 LineTableInfo &LineTable = SourceMgr.getLineTable();
668
669 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000670 std::map<int, int> FileIDs;
671 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000672 // Extract the file name
673 unsigned FilenameLen = Record[Idx++];
674 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
675 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000676 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000677 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000678 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000679 }
680
681 // Parse the line entries
682 std::vector<LineEntry> Entries;
683 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000684 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000685
686 // Extract the line entries
687 unsigned NumEntries = Record[Idx++];
688 Entries.clear();
689 Entries.reserve(NumEntries);
690 for (unsigned I = 0; I != NumEntries; ++I) {
691 unsigned FileOffset = Record[Idx++];
692 unsigned LineNo = Record[Idx++];
693 int FilenameID = Record[Idx++];
Mike Stump1eb44332009-09-09 15:08:12 +0000694 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000695 = (SrcMgr::CharacteristicKind)Record[Idx++];
696 unsigned IncludeOffset = Record[Idx++];
697 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
698 FileKind, IncludeOffset));
699 }
700 LineTable.AddEntry(FID, Entries);
701 }
702
703 return false;
704}
705
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000706namespace {
707
708class VISIBILITY_HIDDEN PCHStatData {
709public:
710 const bool hasStat;
711 const ino_t ino;
712 const dev_t dev;
713 const mode_t mode;
714 const time_t mtime;
715 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000717 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000718 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
719
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000720 PCHStatData()
721 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
722};
723
724class VISIBILITY_HIDDEN PCHStatLookupTrait {
725 public:
726 typedef const char *external_key_type;
727 typedef const char *internal_key_type;
728
729 typedef PCHStatData data_type;
730
731 static unsigned ComputeHash(const char *path) {
732 return BernsteinHash(path);
733 }
734
735 static internal_key_type GetInternalKey(const char *path) { return path; }
736
737 static bool EqualKey(internal_key_type a, internal_key_type b) {
738 return strcmp(a, b) == 0;
739 }
740
741 static std::pair<unsigned, unsigned>
742 ReadKeyDataLength(const unsigned char*& d) {
743 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
744 unsigned DataLen = (unsigned) *d++;
745 return std::make_pair(KeyLen + 1, DataLen);
746 }
747
748 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
749 return (const char *)d;
750 }
751
752 static data_type ReadData(const internal_key_type, const unsigned char *d,
753 unsigned /*DataLen*/) {
754 using namespace clang::io;
755
756 if (*d++ == 1)
757 return data_type();
758
759 ino_t ino = (ino_t) ReadUnalignedLE32(d);
760 dev_t dev = (dev_t) ReadUnalignedLE32(d);
761 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000762 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000763 off_t size = (off_t) ReadUnalignedLE64(d);
764 return data_type(ino, dev, mode, mtime, size);
765 }
766};
767
768/// \brief stat() cache for precompiled headers.
769///
770/// This cache is very similar to the stat cache used by pretokenized
771/// headers.
772class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
773 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
774 CacheTy *Cache;
775
776 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000777public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000778 PCHStatCache(const unsigned char *Buckets,
779 const unsigned char *Base,
780 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000781 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000782 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
783 Cache = CacheTy::Create(Buckets, Base);
784 }
785
786 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000788 int stat(const char *path, struct stat *buf) {
789 // Do the lookup for the file's data in the PCH file.
790 CacheTy::iterator I = Cache->find(path);
791
792 // If we don't get a hit in the PCH file just forward to 'stat'.
793 if (I == Cache->end()) {
794 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000795 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000796 }
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000798 ++NumStatHits;
799 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000801 if (!Data.hasStat)
802 return 1;
803
804 buf->st_ino = Data.ino;
805 buf->st_dev = Data.dev;
806 buf->st_mtime = Data.mtime;
807 buf->st_mode = Data.mode;
808 buf->st_size = Data.size;
809 return 0;
810 }
811};
812} // end anonymous namespace
813
814
Douglas Gregor14f79002009-04-10 03:52:48 +0000815/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000816PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000817 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000818
819 // Set the source-location entry cursor to the current position in
820 // the stream. This cursor will be used to read the contents of the
821 // source manager block initially, and then lazily read
822 // source-location entries as needed.
823 SLocEntryCursor = Stream;
824
825 // The stream itself is going to skip over the source manager block.
826 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000827 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000828 return Failure;
829 }
830
831 // Enter the source manager block.
832 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000833 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000834 return Failure;
835 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000836
Douglas Gregor14f79002009-04-10 03:52:48 +0000837 RecordData Record;
838 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000839 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000840 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000841 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000842 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000843 return Failure;
844 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000845 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000846 }
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Douglas Gregor14f79002009-04-10 03:52:48 +0000848 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
849 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000850 SLocEntryCursor.ReadSubBlockID();
851 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000852 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000853 return Failure;
854 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000855 continue;
856 }
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Douglas Gregor14f79002009-04-10 03:52:48 +0000858 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000859 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000860 continue;
861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregor14f79002009-04-10 03:52:48 +0000863 // Read a record.
864 const char *BlobStart;
865 unsigned BlobLen;
866 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000867 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000868 default: // Default behavior: ignore.
869 break;
870
Chris Lattner2c78b872009-04-14 23:22:57 +0000871 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000872 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000873 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000874 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000875
876 case pch::SM_HEADER_FILE_INFO: {
877 HeaderFileInfo HFI;
878 HFI.isImport = Record[0];
879 HFI.DirInfo = Record[1];
880 HFI.NumIncludes = Record[2];
881 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000882 if (Listener)
883 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000884 break;
885 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000886
887 case pch::SM_SLOC_FILE_ENTRY:
888 case pch::SM_SLOC_BUFFER_ENTRY:
889 case pch::SM_SLOC_INSTANTIATION_ENTRY:
890 // Once we hit one of the source location entries, we're done.
891 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000892 }
893 }
894}
895
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000896/// \brief Read in the source location entry with the given ID.
897PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
898 if (ID == 0)
899 return Success;
900
901 if (ID > TotalNumSLocEntries) {
902 Error("source location entry ID out-of-range for PCH file");
903 return Failure;
904 }
905
906 ++NumSLocEntriesRead;
907 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
908 unsigned Code = SLocEntryCursor.ReadCode();
909 if (Code == llvm::bitc::END_BLOCK ||
910 Code == llvm::bitc::ENTER_SUBBLOCK ||
911 Code == llvm::bitc::DEFINE_ABBREV) {
912 Error("incorrectly-formatted source location entry in PCH file");
913 return Failure;
914 }
915
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000916 RecordData Record;
917 const char *BlobStart;
918 unsigned BlobLen;
919 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
920 default:
921 Error("incorrectly-formatted source location entry in PCH file");
922 return Failure;
923
924 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000925 std::string Filename(BlobStart, BlobStart + BlobLen);
926 MaybeAddSystemRootToFilename(Filename);
927 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000928 if (File == 0) {
929 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000930 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000931 ErrorStr += "' referenced by PCH file";
932 Error(ErrorStr.c_str());
933 return Failure;
934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000936 FileID FID = SourceMgr.createFileID(File,
937 SourceLocation::getFromRawEncoding(Record[1]),
938 (SrcMgr::CharacteristicKind)Record[2],
939 ID, Record[0]);
940 if (Record[3])
941 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
942 .setHasLineDirectives();
943
944 break;
945 }
946
947 case pch::SM_SLOC_BUFFER_ENTRY: {
948 const char *Name = BlobStart;
949 unsigned Offset = Record[0];
950 unsigned Code = SLocEntryCursor.ReadCode();
951 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000952 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000953 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
954 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
955 (void)RecCode;
956 llvm::MemoryBuffer *Buffer
Mike Stump1eb44332009-09-09 15:08:12 +0000957 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000958 BlobStart + BlobLen - 1,
959 Name);
960 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Douglas Gregor92b059e2009-04-28 20:33:11 +0000962 if (strcmp(Name, "<built-in>") == 0) {
963 PCHPredefinesBufferID = BufferID;
964 PCHPredefines = BlobStart;
965 PCHPredefinesLen = BlobLen - 1;
966 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000967
968 break;
969 }
970
971 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +0000972 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000973 = SourceLocation::getFromRawEncoding(Record[1]);
974 SourceMgr.createInstantiationLoc(SpellingLoc,
975 SourceLocation::getFromRawEncoding(Record[2]),
976 SourceLocation::getFromRawEncoding(Record[3]),
977 Record[4],
978 ID,
979 Record[0]);
980 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000981 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000982 }
983
984 return Success;
985}
986
Chris Lattner6367f6d2009-04-27 01:05:14 +0000987/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
988/// specified cursor. Read the abbreviations that are at the top of the block
989/// and then leave the cursor pointing into the block.
990bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
991 unsigned BlockID) {
992 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000993 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000994 return Failure;
995 }
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Chris Lattner6367f6d2009-04-27 01:05:14 +0000997 while (true) {
998 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Chris Lattner6367f6d2009-04-27 01:05:14 +00001000 // We expect all abbrevs to be at the start of the block.
1001 if (Code != llvm::bitc::DEFINE_ABBREV)
1002 return false;
1003 Cursor.ReadAbbrevRecord();
1004 }
1005}
1006
Douglas Gregor37e26842009-04-21 23:56:24 +00001007void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001008 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Douglas Gregor37e26842009-04-21 23:56:24 +00001010 // Keep track of where we are in the stream, then jump back there
1011 // after reading this macro.
1012 SavedStreamPosition SavedPosition(Stream);
1013
1014 Stream.JumpToBit(Offset);
1015 RecordData Record;
1016 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1017 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Douglas Gregor37e26842009-04-21 23:56:24 +00001019 while (true) {
1020 unsigned Code = Stream.ReadCode();
1021 switch (Code) {
1022 case llvm::bitc::END_BLOCK:
1023 return;
1024
1025 case llvm::bitc::ENTER_SUBBLOCK:
1026 // No known subblocks, always skip them.
1027 Stream.ReadSubBlockID();
1028 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001029 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001030 return;
1031 }
1032 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Douglas Gregor37e26842009-04-21 23:56:24 +00001034 case llvm::bitc::DEFINE_ABBREV:
1035 Stream.ReadAbbrevRecord();
1036 continue;
1037 default: break;
1038 }
1039
1040 // Read a record.
1041 Record.clear();
1042 pch::PreprocessorRecordTypes RecType =
1043 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1044 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001045 case pch::PP_MACRO_OBJECT_LIKE:
1046 case pch::PP_MACRO_FUNCTION_LIKE: {
1047 // If we already have a macro, that means that we've hit the end
1048 // of the definition of the macro we were looking for. We're
1049 // done.
1050 if (Macro)
1051 return;
1052
1053 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1054 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001055 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001056 return;
1057 }
1058 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1059 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001061 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001062 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Douglas Gregor37e26842009-04-21 23:56:24 +00001064 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1065 // Decode function-like macro info.
1066 bool isC99VarArgs = Record[3];
1067 bool isGNUVarArgs = Record[4];
1068 MacroArgs.clear();
1069 unsigned NumArgs = Record[5];
1070 for (unsigned i = 0; i != NumArgs; ++i)
1071 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1072
1073 // Install function-like macro info.
1074 MI->setIsFunctionLike();
1075 if (isC99VarArgs) MI->setIsC99Varargs();
1076 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001077 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001078 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001079 }
1080
1081 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001082 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001083
1084 // Remember that we saw this macro last so that we add the tokens that
1085 // form its body to it.
1086 Macro = MI;
1087 ++NumMacrosRead;
1088 break;
1089 }
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Douglas Gregor37e26842009-04-21 23:56:24 +00001091 case pch::PP_TOKEN: {
1092 // If we see a TOKEN before a PP_MACRO_*, then the file is
1093 // erroneous, just pretend we didn't see this.
1094 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Douglas Gregor37e26842009-04-21 23:56:24 +00001096 Token Tok;
1097 Tok.startToken();
1098 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1099 Tok.setLength(Record[1]);
1100 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1101 Tok.setIdentifierInfo(II);
1102 Tok.setKind((tok::TokenKind)Record[3]);
1103 Tok.setFlag((Token::TokenFlags)Record[4]);
1104 Macro->AddTokenToBody(Tok);
1105 break;
1106 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001107 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001108 }
1109}
1110
Douglas Gregore650c8c2009-07-07 00:12:59 +00001111/// \brief If we are loading a relocatable PCH file, and the filename is
1112/// not an absolute path, add the system root to the beginning of the file
1113/// name.
1114void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1115 // If this is not a relocatable PCH file, there's nothing to do.
1116 if (!RelocatablePCH)
1117 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Douglas Gregore650c8c2009-07-07 00:12:59 +00001119 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1120 return;
1121
1122 std::string FIXME = Filename;
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Douglas Gregore650c8c2009-07-07 00:12:59 +00001124 if (isysroot == 0) {
1125 // If no system root was given, default to '/'
1126 Filename.insert(Filename.begin(), '/');
1127 return;
1128 }
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Douglas Gregore650c8c2009-07-07 00:12:59 +00001130 unsigned Length = strlen(isysroot);
1131 if (isysroot[Length - 1] != '/')
1132 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Douglas Gregore650c8c2009-07-07 00:12:59 +00001134 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1135}
1136
Mike Stump1eb44332009-09-09 15:08:12 +00001137PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001138PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001139 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001140 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001141 return Failure;
1142 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001143
1144 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001145 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001146 while (!Stream.AtEndOfStream()) {
1147 unsigned Code = Stream.ReadCode();
1148 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001149 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001150 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001151 return Failure;
1152 }
Chris Lattner7356a312009-04-11 21:15:38 +00001153
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001154 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001155 }
1156
1157 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1158 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001159 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1160 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001161 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001162 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001163 return Failure;
1164 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001165 break;
1166
Chris Lattner6367f6d2009-04-27 01:05:14 +00001167 case pch::DECLS_BLOCK_ID:
1168 // We lazily load the decls block, but we want to set up the
1169 // DeclsCursor cursor to point into it. Clone our current bitcode
1170 // cursor to it, enter the block and read the abbrevs in that block.
1171 // With the main cursor, we just skip over it.
1172 DeclsCursor = Stream;
1173 if (Stream.SkipBlock() || // Skip with the main cursor.
1174 // Read the abbrevs.
1175 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001176 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001177 return Failure;
1178 }
1179 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Chris Lattner7356a312009-04-11 21:15:38 +00001181 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001182 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001183 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001184 return Failure;
1185 }
1186 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001187
Douglas Gregor14f79002009-04-10 03:52:48 +00001188 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001189 switch (ReadSourceManagerBlock()) {
1190 case Success:
1191 break;
1192
1193 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001194 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001195 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001196
1197 case IgnorePCH:
1198 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001199 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001200 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001201 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001202 continue;
1203 }
1204
1205 if (Code == llvm::bitc::DEFINE_ABBREV) {
1206 Stream.ReadAbbrevRecord();
1207 continue;
1208 }
1209
1210 // Read and process a record.
1211 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001212 const char *BlobStart = 0;
1213 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001214 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001215 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001216 default: // Default behavior: ignore.
1217 break;
1218
1219 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001220 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001221 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001222 return Failure;
1223 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001224 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001225 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001226 break;
1227
1228 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001229 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001230 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001231 return Failure;
1232 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001233 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001234 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001235 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001236
1237 case pch::LANGUAGE_OPTIONS:
1238 if (ParseLanguageOptions(Record))
1239 return IgnorePCH;
1240 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001241
Douglas Gregorab41e632009-04-27 22:23:34 +00001242 case pch::METADATA: {
1243 if (Record[0] != pch::VERSION_MAJOR) {
1244 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1245 : diag::warn_pch_version_too_new);
1246 return IgnorePCH;
1247 }
1248
Douglas Gregore650c8c2009-07-07 00:12:59 +00001249 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001250 if (Listener) {
1251 std::string TargetTriple(BlobStart, BlobLen);
1252 if (Listener->ReadTargetTriple(TargetTriple))
1253 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001254 }
1255 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001256 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001257
1258 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001259 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001260 if (Record[0]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001261 IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001262 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001263 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001264 (const unsigned char *)IdentifierTableData,
Douglas Gregor668c1a42009-04-21 22:25:48 +00001265 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001266 if (PP)
1267 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001268 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001269 break;
1270
1271 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001272 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001273 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001274 return Failure;
1275 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001276 IdentifierOffsets = (const uint32_t *)BlobStart;
1277 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001278 if (PP)
1279 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001280 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001281
1282 case pch::EXTERNAL_DEFINITIONS:
1283 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001284 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001285 return Failure;
1286 }
1287 ExternalDefinitions.swap(Record);
1288 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001289
Douglas Gregorad1de002009-04-18 05:55:16 +00001290 case pch::SPECIAL_TYPES:
1291 SpecialTypes.swap(Record);
1292 break;
1293
Douglas Gregor3e1af842009-04-17 22:13:46 +00001294 case pch::STATISTICS:
1295 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001296 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001297 TotalLexicalDeclContexts = Record[2];
1298 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001299 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001300
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001301 case pch::TENTATIVE_DEFINITIONS:
1302 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001303 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001304 return Failure;
1305 }
1306 TentativeDefinitions.swap(Record);
1307 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001308
1309 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1310 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001311 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001312 return Failure;
1313 }
1314 LocallyScopedExternalDecls.swap(Record);
1315 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001316
Douglas Gregor83941df2009-04-25 17:48:32 +00001317 case pch::SELECTOR_OFFSETS:
1318 SelectorOffsets = (const uint32_t *)BlobStart;
1319 TotalNumSelectors = Record[0];
1320 SelectorsLoaded.resize(TotalNumSelectors);
1321 break;
1322
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001323 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001324 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1325 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001326 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001327 = PCHMethodPoolLookupTable::Create(
1328 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001329 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001330 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001331 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001332 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001333
1334 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001335 if (!Record.empty() && Listener)
1336 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001337 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001338
1339 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001340 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001341 TotalNumSLocEntries = Record[0];
Douglas Gregor445e23e2009-10-05 21:07:28 +00001342 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001343 break;
1344
1345 case pch::SOURCE_LOCATION_PRELOADS:
1346 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1347 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1348 if (Result != Success)
1349 return Result;
1350 }
1351 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001352
Douglas Gregor52e71082009-10-16 18:18:30 +00001353 case pch::STAT_CACHE: {
1354 PCHStatCache *MyStatCache =
1355 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1356 (const unsigned char *)BlobStart,
1357 NumStatHits, NumStatMisses);
1358 FileMgr.addStatCache(MyStatCache);
1359 StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001360 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001361 }
1362
Douglas Gregorb81c1702009-04-27 20:06:05 +00001363 case pch::EXT_VECTOR_DECLS:
1364 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001365 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001366 return Failure;
1367 }
1368 ExtVectorDecls.swap(Record);
1369 break;
1370
Douglas Gregorb64c1932009-05-12 01:31:05 +00001371 case pch::ORIGINAL_FILE_NAME:
1372 OriginalFileName.assign(BlobStart, BlobLen);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001373 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001374 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Douglas Gregor2e222532009-07-02 17:08:52 +00001376 case pch::COMMENT_RANGES:
1377 Comments = (SourceRange *)BlobStart;
1378 NumComments = BlobLen / sizeof(SourceRange);
1379 break;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001380
1381 case pch::SVN_BRANCH_REVISION: {
1382 unsigned CurRevision = getClangSubversionRevision();
1383 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1384 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1385 : diag::warn_pch_version_too_new);
1386 return IgnorePCH;
1387 }
1388
1389 const char *CurBranch = getClangSubversionPath();
1390 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1391 std::string PCHBranch(BlobStart, BlobLen);
1392 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1393 return IgnorePCH;
1394 }
1395 break;
1396 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001397 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001398 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001399 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001400 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001401}
1402
Douglas Gregore1d918e2009-04-10 23:10:45 +00001403PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001404 // Set the PCH file name.
1405 this->FileName = FileName;
1406
Douglas Gregor2cf26342009-04-09 22:27:44 +00001407 // Open the PCH file.
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001408 //
1409 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001410 std::string ErrStr;
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001411 if (FileName == "-")
1412 Buffer.reset(llvm::MemoryBuffer::getSTDIN());
1413 else
1414 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001415 if (!Buffer) {
1416 Error(ErrStr.c_str());
1417 return IgnorePCH;
1418 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001419
1420 // Initialize the stream
Mike Stump1eb44332009-09-09 15:08:12 +00001421 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001422 (const unsigned char *)Buffer->getBufferEnd());
1423 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001424
1425 // Sniff for the signature.
1426 if (Stream.Read(8) != 'C' ||
1427 Stream.Read(8) != 'P' ||
1428 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001429 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001430 Diag(diag::err_not_a_pch_file) << FileName;
1431 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001432 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001433
Douglas Gregor2cf26342009-04-09 22:27:44 +00001434 while (!Stream.AtEndOfStream()) {
1435 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Douglas Gregore1d918e2009-04-10 23:10:45 +00001437 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001438 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001439 return Failure;
1440 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001441
1442 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001443
Douglas Gregor2cf26342009-04-09 22:27:44 +00001444 // We only know the PCH subblock ID.
1445 switch (BlockID) {
1446 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001447 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001448 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001449 return Failure;
1450 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001451 break;
1452 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001453 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001454 case Success:
1455 break;
1456
1457 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001458 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001459
1460 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001461 // FIXME: We could consider reading through to the end of this
1462 // PCH block, skipping subblocks, to see if there are other
1463 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001464
1465 // Clear out any preallocated source location entries, so that
1466 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001467 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001468
1469 // Remove the stat cache.
Douglas Gregor52e71082009-10-16 18:18:30 +00001470 if (StatCache)
1471 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001472
Douglas Gregore1d918e2009-04-10 23:10:45 +00001473 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001474 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001475 break;
1476 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001477 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001478 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001479 return Failure;
1480 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001481 break;
1482 }
Mike Stump1eb44332009-09-09 15:08:12 +00001483 }
1484
Douglas Gregor92b059e2009-04-28 20:33:11 +00001485 // Check the predefines buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001486 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
Douglas Gregor92b059e2009-04-28 20:33:11 +00001487 PCHPredefinesBufferID))
1488 return IgnorePCH;
Mike Stump1eb44332009-09-09 15:08:12 +00001489
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001490 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001491 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001492 // PCH file is read, so there may be some identifiers that were
1493 // loaded into the IdentifierTable before we intercepted the
1494 // creation of identifiers. Iterate through the list of known
1495 // identifiers and determine whether we have to establish
1496 // preprocessor definitions or top-level identifier declaration
1497 // chains for those identifiers.
1498 //
1499 // We copy the IdentifierInfo pointers to a small vector first,
1500 // since de-serializing declarations or macro definitions can add
1501 // new entries into the identifier table, invalidating the
1502 // iterators.
1503 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1504 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1505 IdEnd = PP->getIdentifierTable().end();
1506 Id != IdEnd; ++Id)
1507 Identifiers.push_back(Id->second);
Mike Stump1eb44332009-09-09 15:08:12 +00001508 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001509 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1510 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1511 IdentifierInfo *II = Identifiers[I];
1512 // Look in the on-disk hash table for an entry for
1513 PCHIdentifierLookupTrait Info(*this, II);
1514 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1515 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1516 if (Pos == IdTable->end())
1517 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001519 // Dereferencing the iterator has the effect of populating the
1520 // IdentifierInfo node with the various declarations it needs.
1521 (void)*Pos;
1522 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001523 }
1524
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001525 if (Context)
1526 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001527
Douglas Gregor668c1a42009-04-21 22:25:48 +00001528 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001529}
1530
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001531void PCHReader::InitializeContext(ASTContext &Ctx) {
1532 Context = &Ctx;
1533 assert(Context && "Passed null context!");
1534
1535 assert(PP && "Forgot to set Preprocessor ?");
1536 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1537 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001539 // Load the translation unit declaration
1540 ReadDeclRecord(DeclOffsets[0], 0);
1541
1542 // Load the special types.
1543 Context->setBuiltinVaListType(
1544 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1545 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1546 Context->setObjCIdType(GetType(Id));
1547 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1548 Context->setObjCSelType(GetType(Sel));
1549 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1550 Context->setObjCProtoType(GetType(Proto));
1551 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1552 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001553
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001554 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1555 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001556 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001557 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1558 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001559 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1560 QualType FileType = GetType(File);
1561 assert(!FileType.isNull() && "FILE type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001562 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001563 Context->setFILEDecl(Typedef->getDecl());
1564 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001565 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001566 assert(Tag && "Invalid FILE type in PCH file");
1567 Context->setFILEDecl(Tag->getDecl());
1568 }
1569 }
Mike Stump782fa302009-07-28 02:25:19 +00001570 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1571 QualType Jmp_bufType = GetType(Jmp_buf);
1572 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001573 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001574 Context->setjmp_bufDecl(Typedef->getDecl());
1575 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001576 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001577 assert(Tag && "Invalid jmp_bug type in PCH file");
1578 Context->setjmp_bufDecl(Tag->getDecl());
1579 }
1580 }
1581 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1582 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1583 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001584 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001585 Context->setsigjmp_bufDecl(Typedef->getDecl());
1586 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001587 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001588 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1589 Context->setsigjmp_bufDecl(Tag->getDecl());
1590 }
1591 }
Mike Stump1eb44332009-09-09 15:08:12 +00001592 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001593 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1594 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001595 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001596 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1597 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001598}
1599
Douglas Gregorb64c1932009-05-12 01:31:05 +00001600/// \brief Retrieve the name of the original source file name
1601/// directly from the PCH file, without actually loading the PCH
1602/// file.
1603std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1604 // Open the PCH file.
1605 std::string ErrStr;
1606 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1607 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1608 if (!Buffer) {
1609 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1610 return std::string();
1611 }
1612
1613 // Initialize the stream
1614 llvm::BitstreamReader StreamFile;
1615 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00001616 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00001617 (const unsigned char *)Buffer->getBufferEnd());
1618 Stream.init(StreamFile);
1619
1620 // Sniff for the signature.
1621 if (Stream.Read(8) != 'C' ||
1622 Stream.Read(8) != 'P' ||
1623 Stream.Read(8) != 'C' ||
1624 Stream.Read(8) != 'H') {
Mike Stump1eb44332009-09-09 15:08:12 +00001625 fprintf(stderr,
Douglas Gregorb64c1932009-05-12 01:31:05 +00001626 "error: '%s' does not appear to be a precompiled header file\n",
1627 PCHFileName.c_str());
1628 return std::string();
1629 }
1630
1631 RecordData Record;
1632 while (!Stream.AtEndOfStream()) {
1633 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Douglas Gregorb64c1932009-05-12 01:31:05 +00001635 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1636 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Douglas Gregorb64c1932009-05-12 01:31:05 +00001638 // We only know the PCH subblock ID.
1639 switch (BlockID) {
1640 case pch::PCH_BLOCK_ID:
1641 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1642 fprintf(stderr, "error: malformed block record in PCH file\n");
1643 return std::string();
1644 }
1645 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Douglas Gregorb64c1932009-05-12 01:31:05 +00001647 default:
1648 if (Stream.SkipBlock()) {
1649 fprintf(stderr, "error: malformed block record in PCH file\n");
1650 return std::string();
1651 }
1652 break;
1653 }
1654 continue;
1655 }
1656
1657 if (Code == llvm::bitc::END_BLOCK) {
1658 if (Stream.ReadBlockEnd()) {
1659 fprintf(stderr, "error: error at end of module block in PCH file\n");
1660 return std::string();
1661 }
1662 continue;
1663 }
1664
1665 if (Code == llvm::bitc::DEFINE_ABBREV) {
1666 Stream.ReadAbbrevRecord();
1667 continue;
1668 }
1669
1670 Record.clear();
1671 const char *BlobStart = 0;
1672 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001673 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00001674 == pch::ORIGINAL_FILE_NAME)
1675 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001676 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00001677
1678 return std::string();
1679}
1680
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001681/// \brief Parse the record that corresponds to a LangOptions data
1682/// structure.
1683///
1684/// This routine compares the language options used to generate the
1685/// PCH file against the language options set for the current
1686/// compilation. For each option, we classify differences between the
1687/// two compiler states as either "benign" or "important". Benign
1688/// differences don't matter, and we accept them without complaint
1689/// (and without modifying the language options). Differences between
1690/// the states for important options cause the PCH file to be
1691/// unusable, so we emit a warning and return true to indicate that
1692/// there was an error.
1693///
1694/// \returns true if the PCH file is unacceptable, false otherwise.
1695bool PCHReader::ParseLanguageOptions(
1696 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001697 if (Listener) {
1698 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001700 #define PARSE_LANGOPT(Option) \
1701 LangOpts.Option = Record[Idx]; \
1702 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001704 unsigned Idx = 0;
1705 PARSE_LANGOPT(Trigraphs);
1706 PARSE_LANGOPT(BCPLComment);
1707 PARSE_LANGOPT(DollarIdents);
1708 PARSE_LANGOPT(AsmPreprocessor);
1709 PARSE_LANGOPT(GNUMode);
1710 PARSE_LANGOPT(ImplicitInt);
1711 PARSE_LANGOPT(Digraphs);
1712 PARSE_LANGOPT(HexFloats);
1713 PARSE_LANGOPT(C99);
1714 PARSE_LANGOPT(Microsoft);
1715 PARSE_LANGOPT(CPlusPlus);
1716 PARSE_LANGOPT(CPlusPlus0x);
1717 PARSE_LANGOPT(CXXOperatorNames);
1718 PARSE_LANGOPT(ObjC1);
1719 PARSE_LANGOPT(ObjC2);
1720 PARSE_LANGOPT(ObjCNonFragileABI);
1721 PARSE_LANGOPT(PascalStrings);
1722 PARSE_LANGOPT(WritableStrings);
1723 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001724 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001725 PARSE_LANGOPT(Exceptions);
1726 PARSE_LANGOPT(NeXTRuntime);
1727 PARSE_LANGOPT(Freestanding);
1728 PARSE_LANGOPT(NoBuiltin);
1729 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00001730 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001731 PARSE_LANGOPT(Blocks);
1732 PARSE_LANGOPT(EmitAllDecls);
1733 PARSE_LANGOPT(MathErrno);
1734 PARSE_LANGOPT(OverflowChecking);
1735 PARSE_LANGOPT(HeinousExtensions);
1736 PARSE_LANGOPT(Optimize);
1737 PARSE_LANGOPT(OptimizeSize);
1738 PARSE_LANGOPT(Static);
1739 PARSE_LANGOPT(PICLevel);
1740 PARSE_LANGOPT(GNUInline);
1741 PARSE_LANGOPT(NoInline);
1742 PARSE_LANGOPT(AccessControl);
1743 PARSE_LANGOPT(CharIsSigned);
1744 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1745 ++Idx;
1746 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1747 ++Idx;
Daniel Dunbarab8e2812009-09-21 04:16:19 +00001748 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1749 Record[Idx]);
1750 ++Idx;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001751 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001752 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001753 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001754
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001755 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001756 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001757
1758 return false;
1759}
1760
Douglas Gregor2e222532009-07-02 17:08:52 +00001761void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1762 Comments.resize(NumComments);
1763 std::copy(this->Comments, this->Comments + NumComments,
1764 Comments.begin());
1765}
1766
Douglas Gregor2cf26342009-04-09 22:27:44 +00001767/// \brief Read and return the type at the given offset.
1768///
1769/// This routine actually reads the record corresponding to the type
1770/// at the given offset in the bitstream. It is a helper routine for
1771/// GetType, which deals with reading type IDs.
1772QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001773 // Keep track of where we are in the stream, then jump back there
1774 // after reading this type.
1775 SavedStreamPosition SavedPosition(Stream);
1776
Douglas Gregord89275b2009-07-06 18:54:52 +00001777 // Note that we are loading a type record.
1778 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Douglas Gregor2cf26342009-04-09 22:27:44 +00001780 Stream.JumpToBit(Offset);
1781 RecordData Record;
1782 unsigned Code = Stream.ReadCode();
1783 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001784 case pch::TYPE_EXT_QUAL: {
John McCall0953e762009-09-24 19:53:00 +00001785 assert(Record.size() == 2 &&
Douglas Gregor6d473962009-04-15 22:00:08 +00001786 "Incorrect encoding of extended qualifier type");
1787 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00001788 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1789 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00001790 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001791
Douglas Gregor2cf26342009-04-09 22:27:44 +00001792 case pch::TYPE_FIXED_WIDTH_INT: {
1793 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001794 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001795 }
1796
1797 case pch::TYPE_COMPLEX: {
1798 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1799 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001800 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001801 }
1802
1803 case pch::TYPE_POINTER: {
1804 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1805 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001806 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001807 }
1808
1809 case pch::TYPE_BLOCK_POINTER: {
1810 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1811 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001812 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001813 }
1814
1815 case pch::TYPE_LVALUE_REFERENCE: {
1816 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1817 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001818 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001819 }
1820
1821 case pch::TYPE_RVALUE_REFERENCE: {
1822 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1823 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001824 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001825 }
1826
1827 case pch::TYPE_MEMBER_POINTER: {
1828 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1829 QualType PointeeType = GetType(Record[0]);
1830 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001831 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001832 }
1833
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001834 case pch::TYPE_CONSTANT_ARRAY: {
1835 QualType ElementType = GetType(Record[0]);
1836 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1837 unsigned IndexTypeQuals = Record[2];
1838 unsigned Idx = 3;
1839 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001840 return Context->getConstantArrayType(ElementType, Size,
1841 ASM, IndexTypeQuals);
1842 }
1843
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001844 case pch::TYPE_INCOMPLETE_ARRAY: {
1845 QualType ElementType = GetType(Record[0]);
1846 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1847 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001848 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001849 }
1850
1851 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001852 QualType ElementType = GetType(Record[0]);
1853 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1854 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001855 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1856 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001857 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001858 ASM, IndexTypeQuals,
1859 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001860 }
1861
1862 case pch::TYPE_VECTOR: {
1863 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001864 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001865 return QualType();
1866 }
1867
1868 QualType ElementType = GetType(Record[0]);
1869 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001870 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001871 }
1872
1873 case pch::TYPE_EXT_VECTOR: {
1874 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001875 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001876 return QualType();
1877 }
1878
1879 QualType ElementType = GetType(Record[0]);
1880 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001881 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001882 }
1883
1884 case pch::TYPE_FUNCTION_NO_PROTO: {
1885 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001886 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001887 return QualType();
1888 }
1889 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001890 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001891 }
1892
1893 case pch::TYPE_FUNCTION_PROTO: {
1894 QualType ResultType = GetType(Record[0]);
1895 unsigned Idx = 1;
1896 unsigned NumParams = Record[Idx++];
1897 llvm::SmallVector<QualType, 16> ParamTypes;
1898 for (unsigned I = 0; I != NumParams; ++I)
1899 ParamTypes.push_back(GetType(Record[Idx++]));
1900 bool isVariadic = Record[Idx++];
1901 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001902 bool hasExceptionSpec = Record[Idx++];
1903 bool hasAnyExceptionSpec = Record[Idx++];
1904 unsigned NumExceptions = Record[Idx++];
1905 llvm::SmallVector<QualType, 2> Exceptions;
1906 for (unsigned I = 0; I != NumExceptions; ++I)
1907 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001908 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001909 isVariadic, Quals, hasExceptionSpec,
1910 hasAnyExceptionSpec, NumExceptions,
1911 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001912 }
1913
1914 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001915 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001916 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001917
1918 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001919 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001920
1921 case pch::TYPE_TYPEOF: {
1922 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001923 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001924 return QualType();
1925 }
1926 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001927 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001928 }
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Anders Carlsson395b4752009-06-24 19:06:50 +00001930 case pch::TYPE_DECLTYPE:
1931 return Context->getDecltypeType(ReadTypeExpr());
1932
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001933 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001934 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001935 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001936
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001937 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001938 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001939 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001940
John McCall7da24312009-09-05 00:15:47 +00001941 case pch::TYPE_ELABORATED: {
1942 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1943 unsigned Tag = Record[1];
1944 return Context->getElaboratedType(GetType(Record[0]),
1945 (ElaboratedType::TagKind) Tag);
1946 }
1947
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001948 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001949 unsigned Idx = 0;
1950 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1951 unsigned NumProtos = Record[Idx++];
1952 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1953 for (unsigned I = 0; I != NumProtos; ++I)
1954 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001955 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001956 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001957
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001958 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001959 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00001960 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001961 unsigned NumProtos = Record[Idx++];
1962 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1963 for (unsigned I = 0; I != NumProtos; ++I)
1964 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00001965 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001966 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00001967
1968 case pch::TYPE_OBJC_PROTOCOL_LIST: {
1969 unsigned Idx = 0;
1970 QualType OIT = GetType(Record[Idx++]);
1971 unsigned NumProtos = Record[Idx++];
1972 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1973 for (unsigned I = 0; I != NumProtos; ++I)
1974 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1975 return Context->getObjCProtocolListType(OIT, Protos.data(), NumProtos);
1976 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001977 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001978 // Suppress a GCC warning
1979 return QualType();
1980}
1981
Douglas Gregor2cf26342009-04-09 22:27:44 +00001982
Douglas Gregor8038d512009-04-10 17:25:41 +00001983QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00001984 unsigned FastQuals = ID & Qualifiers::FastMask;
1985 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001986
1987 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1988 QualType T;
1989 switch ((pch::PredefinedTypeIDs)Index) {
1990 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001991 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1992 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001993
1994 case pch::PREDEF_TYPE_CHAR_U_ID:
1995 case pch::PREDEF_TYPE_CHAR_S_ID:
1996 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001997 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001998 break;
1999
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002000 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2001 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2002 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2003 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2004 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002005 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002006 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2007 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2008 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2009 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2010 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2011 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002012 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002013 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2014 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2015 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2016 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2017 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002018 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002019 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2020 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002021 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2022 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002023 }
2024
2025 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002026 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002027 }
2028
2029 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002030 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall0953e762009-09-24 19:53:00 +00002031 if (TypesLoaded[Index].isNull())
2032 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump1eb44332009-09-09 15:08:12 +00002033
John McCall0953e762009-09-24 19:53:00 +00002034 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002035}
2036
Douglas Gregor8038d512009-04-10 17:25:41 +00002037Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002038 if (ID == 0)
2039 return 0;
2040
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002041 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002042 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002043 return 0;
2044 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002045
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002046 unsigned Index = ID - 1;
2047 if (!DeclsLoaded[Index])
2048 ReadDeclRecord(DeclOffsets[Index], Index);
2049
2050 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002051}
2052
Chris Lattner887e2b32009-04-27 05:46:25 +00002053/// \brief Resolve the offset of a statement into a statement.
2054///
2055/// This operation will read a new statement from the external
2056/// source each time it is called, and is meant to be used via a
2057/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2058Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002059 // Since we know tha this statement is part of a decl, make sure to use the
2060 // decl cursor to read it.
2061 DeclsCursor.JumpToBit(Offset);
2062 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002063}
2064
Douglas Gregor2cf26342009-04-09 22:27:44 +00002065bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002066 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002067 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002068 "DeclContext has no lexical decls in storage");
2069 uint64_t Offset = DeclContextOffsets[DC].first;
2070 assert(Offset && "DeclContext has no lexical decls in storage");
2071
Douglas Gregor0b748912009-04-14 21:18:50 +00002072 // Keep track of where we are in the stream, then jump back there
2073 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002074 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002075
Douglas Gregor2cf26342009-04-09 22:27:44 +00002076 // Load the record containing all of the declarations lexically in
2077 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002078 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002079 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002080 unsigned Code = DeclsCursor.ReadCode();
2081 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002082 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002083 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2084
2085 // Load all of the declaration IDs
2086 Decls.clear();
2087 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002088 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002089 return false;
2090}
2091
2092bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002093 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002094 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002095 "DeclContext has no visible decls in storage");
2096 uint64_t Offset = DeclContextOffsets[DC].second;
2097 assert(Offset && "DeclContext has no visible decls in storage");
2098
Douglas Gregor0b748912009-04-14 21:18:50 +00002099 // Keep track of where we are in the stream, then jump back there
2100 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002101 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002102
Douglas Gregor2cf26342009-04-09 22:27:44 +00002103 // Load the record containing all of the declarations visible in
2104 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002105 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002106 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002107 unsigned Code = DeclsCursor.ReadCode();
2108 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002109 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002110 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2111 if (Record.size() == 0)
Mike Stump1eb44332009-09-09 15:08:12 +00002112 return false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002113
2114 Decls.clear();
2115
2116 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002117 while (Idx < Record.size()) {
2118 Decls.push_back(VisibleDeclaration());
2119 Decls.back().Name = ReadDeclarationName(Record, Idx);
2120
Douglas Gregor2cf26342009-04-09 22:27:44 +00002121 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002122 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002123 LoadedDecls.reserve(Size);
2124 for (unsigned I = 0; I < Size; ++I)
2125 LoadedDecls.push_back(Record[Idx++]);
2126 }
2127
Douglas Gregor25123082009-04-22 22:34:57 +00002128 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002129 return false;
2130}
2131
Douglas Gregorfdd01722009-04-14 00:24:19 +00002132void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002133 this->Consumer = Consumer;
2134
Douglas Gregorfdd01722009-04-14 00:24:19 +00002135 if (!Consumer)
2136 return;
2137
2138 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002139 // Force deserialization of this decl, which will cause it to be passed to
2140 // the consumer (or queued).
2141 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002142 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002143
2144 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2145 DeclGroupRef DG(InterestingDecls[I]);
2146 Consumer->HandleTopLevelDecl(DG);
2147 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002148}
2149
Douglas Gregor2cf26342009-04-09 22:27:44 +00002150void PCHReader::PrintStats() {
2151 std::fprintf(stderr, "*** PCH Statistics:\n");
2152
Mike Stump1eb44332009-09-09 15:08:12 +00002153 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002154 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002155 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002156 unsigned NumDeclsLoaded
2157 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2158 (Decl *)0);
2159 unsigned NumIdentifiersLoaded
2160 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2161 IdentifiersLoaded.end(),
2162 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002163 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002164 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2165 SelectorsLoaded.end(),
2166 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002167
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002168 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2169 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002170 if (TotalNumSLocEntries)
2171 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2172 NumSLocEntriesRead, TotalNumSLocEntries,
2173 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002174 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002175 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002176 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2177 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2178 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002179 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002180 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2181 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002182 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002183 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002184 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2185 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002186 if (TotalNumSelectors)
2187 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2188 NumSelectorsLoaded, TotalNumSelectors,
2189 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2190 if (TotalNumStatements)
2191 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2192 NumStatementsRead, TotalNumStatements,
2193 ((float)NumStatementsRead/TotalNumStatements * 100));
2194 if (TotalNumMacros)
2195 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2196 NumMacrosRead, TotalNumMacros,
2197 ((float)NumMacrosRead/TotalNumMacros * 100));
2198 if (TotalLexicalDeclContexts)
2199 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2200 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2201 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2202 * 100));
2203 if (TotalVisibleDeclContexts)
2204 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2205 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2206 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2207 * 100));
2208 if (TotalSelectorsInMethodPool) {
2209 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2210 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2211 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2212 * 100));
2213 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2214 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002215 std::fprintf(stderr, "\n");
2216}
2217
Douglas Gregor668c1a42009-04-21 22:25:48 +00002218void PCHReader::InitializeSema(Sema &S) {
2219 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002220 S.ExternalSource = this;
2221
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002222 // Makes sure any declarations that were deserialized "too early"
2223 // still get added to the identifier's declaration chains.
2224 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2225 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2226 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002227 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002228 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002229
2230 // If there were any tentative definitions, deserialize them and add
2231 // them to Sema's table of tentative definitions.
2232 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2233 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2234 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner63d65f82009-09-08 18:19:27 +00002235 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002236 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002237
2238 // If there were any locally-scoped external declarations,
2239 // deserialize them and add them to Sema's table of locally-scoped
2240 // external declarations.
2241 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2242 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2243 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2244 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002245
2246 // If there were any ext_vector type declarations, deserialize them
2247 // and add them to Sema's vector of such declarations.
2248 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2249 SemaObj->ExtVectorDecls.push_back(
2250 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002251}
2252
2253IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2254 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00002255 PCHIdentifierLookupTable *IdTable
Douglas Gregor668c1a42009-04-21 22:25:48 +00002256 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2257 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2258 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2259 if (Pos == IdTable->end())
2260 return 0;
2261
2262 // Dereferencing the iterator has the effect of building the
2263 // IdentifierInfo node and populating it with the various
2264 // declarations it needs.
2265 return *Pos;
2266}
2267
Mike Stump1eb44332009-09-09 15:08:12 +00002268std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002269PCHReader::ReadMethodPool(Selector Sel) {
2270 if (!MethodPoolLookupTable)
2271 return std::pair<ObjCMethodList, ObjCMethodList>();
2272
2273 // Try to find this selector within our on-disk hash table.
2274 PCHMethodPoolLookupTable *PoolTable
2275 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2276 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002277 if (Pos == PoolTable->end()) {
2278 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002279 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002280 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002281
Douglas Gregor83941df2009-04-25 17:48:32 +00002282 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002283 return *Pos;
2284}
2285
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002286void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002287 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002288 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002289 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002290}
2291
Douglas Gregord89275b2009-07-06 18:54:52 +00002292/// \brief Set the globally-visible declarations associated with the given
2293/// identifier.
2294///
2295/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00002296/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00002297/// them.
2298///
2299/// \param II an IdentifierInfo that refers to one or more globally-visible
2300/// declarations.
2301///
2302/// \param DeclIDs the set of declaration IDs with the name @p II that are
2303/// visible at global scope.
2304///
2305/// \param Nonrecursive should be true to indicate that the caller knows that
2306/// this call is non-recursive, and therefore the globally-visible declarations
2307/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00002308void
2309PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00002310 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2311 bool Nonrecursive) {
2312 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2313 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2314 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2315 PII.II = II;
2316 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2317 PII.DeclIDs.push_back(DeclIDs[I]);
2318 return;
2319 }
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Douglas Gregord89275b2009-07-06 18:54:52 +00002321 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2322 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2323 if (SemaObj) {
2324 // Introduce this declaration into the translation-unit scope
2325 // and add it to the declaration chain for this identifier, so
2326 // that (unqualified) name lookup will find it.
2327 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2328 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2329 } else {
2330 // Queue this declaration so that it will be added to the
2331 // translation unit scope and identifier's declaration chain
2332 // once a Sema object is known.
2333 PreloadedDecls.push_back(D);
2334 }
2335 }
2336}
2337
Chris Lattner7356a312009-04-11 21:15:38 +00002338IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002339 if (ID == 0)
2340 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002342 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002343 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002344 return 0;
2345 }
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002347 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002348 if (!IdentifiersLoaded[ID - 1]) {
2349 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002350 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002351
Douglas Gregor02fc7512009-04-28 20:01:51 +00002352 // All of the strings in the PCH file are preceded by a 16-bit
2353 // length. Extract that 16-bit length to avoid having to execute
2354 // strlen().
2355 const char *StrLenPtr = Str - 2;
2356 unsigned StrLen = (((unsigned) StrLenPtr[0])
2357 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002358 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002359 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002360 }
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002362 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002363}
2364
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002365void PCHReader::ReadSLocEntry(unsigned ID) {
2366 ReadSLocEntryRecord(ID);
2367}
2368
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002369Selector PCHReader::DecodeSelector(unsigned ID) {
2370 if (ID == 0)
2371 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Douglas Gregora02b1472009-04-28 21:53:25 +00002373 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002374 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002375
2376 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002377 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002378 return Selector();
2379 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002380
2381 unsigned Index = ID - 1;
2382 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2383 // Load this selector from the selector table.
2384 // FIXME: endianness portability issues with SelectorOffsets table
2385 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002386 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00002387 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2388 }
2389
2390 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002391}
2392
Mike Stump1eb44332009-09-09 15:08:12 +00002393DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00002394PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2395 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2396 switch (Kind) {
2397 case DeclarationName::Identifier:
2398 return DeclarationName(GetIdentifierInfo(Record, Idx));
2399
2400 case DeclarationName::ObjCZeroArgSelector:
2401 case DeclarationName::ObjCOneArgSelector:
2402 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002403 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002404
2405 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002406 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002407 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002408
2409 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002410 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002411 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002412
2413 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002414 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002415 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002416
2417 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002418 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002419 (OverloadedOperatorKind)Record[Idx++]);
2420
2421 case DeclarationName::CXXUsingDirective:
2422 return DeclarationName::getUsingDirectiveName();
2423 }
2424
2425 // Required to silence GCC warning
2426 return DeclarationName();
2427}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002428
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002429/// \brief Read an integral value
2430llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2431 unsigned BitWidth = Record[Idx++];
2432 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2433 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2434 Idx += NumWords;
2435 return Result;
2436}
2437
2438/// \brief Read a signed integral value
2439llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2440 bool isUnsigned = Record[Idx++];
2441 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2442}
2443
Douglas Gregor17fc2232009-04-14 21:55:33 +00002444/// \brief Read a floating-point value
2445llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002446 return llvm::APFloat(ReadAPInt(Record, Idx));
2447}
2448
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002449// \brief Read a string
2450std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2451 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002452 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002453 Idx += Len;
2454 return Result;
2455}
2456
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002457DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002458 return Diag(SourceLocation(), DiagID);
2459}
2460
2461DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002462 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002463}
Douglas Gregor025452f2009-04-17 00:04:06 +00002464
Douglas Gregor668c1a42009-04-21 22:25:48 +00002465/// \brief Retrieve the identifier table associated with the
2466/// preprocessor.
2467IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002468 assert(PP && "Forgot to set Preprocessor ?");
2469 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002470}
2471
Douglas Gregor025452f2009-04-17 00:04:06 +00002472/// \brief Record that the given ID maps to the given switch-case
2473/// statement.
2474void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2475 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2476 SwitchCaseStmts[ID] = SC;
2477}
2478
2479/// \brief Retrieve the switch-case statement with the given ID.
2480SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2481 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2482 return SwitchCaseStmts[ID];
2483}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002484
2485/// \brief Record that the given label statement has been
2486/// deserialized and has the given ID.
2487void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00002488 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002489 "Deserialized label twice");
2490 LabelStmts[ID] = S;
2491
2492 // If we've already seen any goto statements that point to this
2493 // label, resolve them now.
2494 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2495 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2496 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2497 Goto->second->setLabel(S);
2498 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002499
2500 // If we've already seen any address-label statements that point to
2501 // this label, resolve them now.
2502 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00002503 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002504 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002505 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002506 AddrLabel != AddrLabels.second; ++AddrLabel)
2507 AddrLabel->second->setLabel(S);
2508 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002509}
2510
2511/// \brief Set the label of the given statement to the label
2512/// identified by ID.
2513///
2514/// Depending on the order in which the label and other statements
2515/// referencing that label occur, this operation may complete
2516/// immediately (updating the statement) or it may queue the
2517/// statement to be back-patched later.
2518void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2519 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2520 if (Label != LabelStmts.end()) {
2521 // We've already seen this label, so set the label of the goto and
2522 // we're done.
2523 S->setLabel(Label->second);
2524 } else {
2525 // We haven't seen this label yet, so add this goto to the set of
2526 // unresolved goto statements.
2527 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2528 }
2529}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002530
2531/// \brief Set the label of the given expression to the label
2532/// identified by ID.
2533///
2534/// Depending on the order in which the label and other statements
2535/// referencing that label occur, this operation may complete
2536/// immediately (updating the statement) or it may queue the
2537/// statement to be back-patched later.
2538void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2539 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2540 if (Label != LabelStmts.end()) {
2541 // We've already seen this label, so set the label of the
2542 // label-address expression and we're done.
2543 S->setLabel(Label->second);
2544 } else {
2545 // We haven't seen this label yet, so add this label-address
2546 // expression to the set of unresolved label-address expressions.
2547 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2548 }
2549}
Douglas Gregord89275b2009-07-06 18:54:52 +00002550
2551
Mike Stump1eb44332009-09-09 15:08:12 +00002552PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00002553 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2554 Reader.CurrentlyLoadingTypeOrDecl = this;
2555}
2556
2557PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2558 if (!Parent) {
2559 // If any identifiers with corresponding top-level declarations have
2560 // been loaded, load those declarations now.
2561 while (!Reader.PendingIdentifierInfos.empty()) {
2562 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2563 Reader.PendingIdentifierInfos.front().DeclIDs,
2564 true);
2565 Reader.PendingIdentifierInfos.pop_front();
2566 }
2567 }
2568
Mike Stump1eb44332009-09-09 15:08:12 +00002569 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00002570}