blob: ec9834894fb6730c50f4f87e3cc5a5f1b576391b [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"
Daniel Dunbarc7162932009-11-11 23:58:53 +000016#include "clang/Frontend/Utils.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000017#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000018#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000022#include "clang/AST/TypeLocVisitor.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000023#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000024#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000025#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000029#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000030#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000031#include "clang/Basic/Version.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000032#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include "llvm/Support/MemoryBuffer.h"
John McCall833ca992009-10-29 08:12:44 +000035#include "llvm/Support/ErrorHandling.h"
Daniel Dunbard5b21972009-11-18 19:50:41 +000036#include "llvm/System/Path.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000037#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000038#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000039#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000040#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000041using namespace clang;
42
43//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000044// PCH reader validator implementation
45//===----------------------------------------------------------------------===//
46
47PCHReaderListener::~PCHReaderListener() {}
48
49bool
50PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
51 const LangOptions &PPLangOpts = PP.getLangOptions();
52#define PARSE_LANGOPT_BENIGN(Option)
53#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
54 if (PPLangOpts.Option != LangOpts.Option) { \
55 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
56 return true; \
57 }
58
59 PARSE_LANGOPT_BENIGN(Trigraphs);
60 PARSE_LANGOPT_BENIGN(BCPLComment);
61 PARSE_LANGOPT_BENIGN(DollarIdents);
62 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
63 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
64 PARSE_LANGOPT_BENIGN(ImplicitInt);
65 PARSE_LANGOPT_BENIGN(Digraphs);
66 PARSE_LANGOPT_BENIGN(HexFloats);
67 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
68 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
69 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
70 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
71 PARSE_LANGOPT_BENIGN(CXXOperatorName);
72 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
73 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
74 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
75 PARSE_LANGOPT_BENIGN(PascalStrings);
76 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000077 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000078 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000079 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000080 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
81 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
82 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
83 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump1eb44332009-09-09 15:08:12 +000084 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000085 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000086 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000087 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
88 PARSE_LANGOPT_BENIGN(EmitAllDecls);
89 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
90 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump1eb44332009-09-09 15:08:12 +000091 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000092 diag::warn_pch_heinous_extensions);
93 // FIXME: Most of the options below are benign if the macro wasn't
94 // used. Unfortunately, this means that a PCH compiled without
95 // optimization can't be used with optimization turned on, even
96 // though the only thing that changes is whether __OPTIMIZE__ was
97 // defined... but if __OPTIMIZE__ never showed up in the header, it
98 // doesn't matter. We could consider making this some special kind
99 // of check.
100 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
101 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
102 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
103 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
104 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
105 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
106 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
107 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsona6fda122009-11-05 20:14:16 +0000108 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000109 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000110 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000111 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
112 return true;
113 }
114 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000115 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
116 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000117 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000118 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000119 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000120#undef PARSE_LANGOPT_IRRELEVANT
121#undef PARSE_LANGOPT_BENIGN
122
123 return false;
124}
125
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000126bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
127 if (Triple == PP.getTargetInfo().getTriple().str())
128 return false;
129
130 Reader.Diag(diag::warn_pch_target_triple)
131 << Triple << PP.getTargetInfo().getTriple().str();
132 return true;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000133}
134
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000135bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000136 FileID PCHBufferID,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000137 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000138 std::string &SuggestedPredefines) {
Daniel Dunbarc7162932009-11-11 23:58:53 +0000139 // We are in the context of an implicit include, so the predefines buffer will
140 // have a #include entry for the PCH file itself (as normalized by the
141 // preprocessor initialization). Find it and skip over it in the checking
142 // below.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000143 llvm::SmallString<256> PCHInclude;
144 PCHInclude += "#include \"";
Daniel Dunbarc7162932009-11-11 23:58:53 +0000145 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000146 PCHInclude += "\"\n";
147 std::pair<llvm::StringRef,llvm::StringRef> Split =
148 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
149 llvm::StringRef Left = Split.first, Right = Split.second;
150 assert(Left != PP.getPredefines() && "Missing PCH include entry!");
151
152 // If the predefines is equal to the joined left and right halves, we're done!
153 if (Left.size() + Right.size() == PCHPredef.size() &&
154 PCHPredef.startswith(Left) && PCHPredef.endswith(Right))
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000155 return false;
156
157 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000158
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000159 // The predefines buffers are different. Determine what the differences are,
160 // and whether they require us to reject the PCH file.
Daniel Dunbare6750492009-11-13 16:46:11 +0000161 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
162 PCHPredef.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
163
164 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
165 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
166 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000167
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000168 // Sort both sets of predefined buffer lines, since we allow some extra
169 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000170 std::sort(CmdLineLines.begin(), CmdLineLines.end());
171 std::sort(PCHLines.begin(), PCHLines.end());
172
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000173 // Determine which predefines that were used to build the PCH file are missing
174 // from the command line.
175 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000176 std::set_difference(PCHLines.begin(), PCHLines.end(),
177 CmdLineLines.begin(), CmdLineLines.end(),
178 std::back_inserter(MissingPredefines));
179
180 bool MissingDefines = false;
181 bool ConflictingDefines = false;
182 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000183 llvm::StringRef Missing = MissingPredefines[I];
184 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000185 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
186 return true;
187 }
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000189 // This is a macro definition. Determine the name of the macro we're
190 // defining.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000191 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000192 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000193 = Missing.find_first_of("( \n\r", StartOfMacroName);
194 assert(EndOfMacroName != std::string::npos &&
195 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000196 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000197
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000198 // Determine whether this macro was given a different definition on the
199 // command line.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000200 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000201 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbare6750492009-11-13 16:46:11 +0000202 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000203 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
204 MacroDefStart);
205 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000206 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000207 // Different macro; we're done.
208 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000209 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000210 }
Mike Stump1eb44332009-09-09 15:08:12 +0000211
212 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000213 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000214 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000215 (*ConflictPos)[MacroDefLen] != '(')
216 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000218 // We found a conflicting macro definition.
219 break;
220 }
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000222 if (ConflictPos != CmdLineLines.end()) {
223 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
224 << MacroName;
225
226 // Show the definition of this macro within the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000227 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
228 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
229 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
230 .getFileLocWithOffset(Offset);
231 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000232
233 ConflictingDefines = true;
234 continue;
235 }
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000237 // If the macro doesn't conflict, then we'll just pick up the macro
238 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000239 if (ConflictingDefines)
240 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000242 if (!MissingDefines) {
243 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
244 MissingDefines = true;
245 }
246
247 // Show the definition of this macro within the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000248 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
249 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
250 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000251 .getFileLocWithOffset(Offset);
252 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
253 }
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000255 if (ConflictingDefines)
256 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000258 // Determine what predefines were introduced based on command-line
259 // parameters that were not present when building the PCH
260 // file. Extra #defines are okay, so long as the identifiers being
261 // defined were not used within the precompiled header.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000262 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000263 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
264 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000265 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000266 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000267 llvm::StringRef &Extra = ExtraPredefines[I];
268 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000269 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
270 return true;
271 }
272
273 // This is an extra macro definition. Determine the name of the
274 // macro we're defining.
275 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000276 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000277 = Extra.find_first_of("( \n\r", StartOfMacroName);
278 assert(EndOfMacroName != std::string::npos &&
279 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000280 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000281
282 // Check whether this name was used somewhere in the PCH file. If
283 // so, defining it as a macro could change behavior, so we reject
284 // the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000285 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar4fda42e2009-11-11 00:52:00 +0000286 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000287 return true;
288 }
289
290 // Add this definition to the suggested predefines buffer.
291 SuggestedPredefines += Extra;
292 SuggestedPredefines += '\n';
293 }
294
295 // If we get here, it's because the predefines buffer had compatible
296 // contents. Accept the PCH file.
297 return false;
298}
299
300void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
301 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
302}
303
304void PCHValidator::ReadCounter(unsigned Value) {
305 PP.setCounterValue(Value);
306}
307
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000308//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000309// PCH reader implementation
310//===----------------------------------------------------------------------===//
311
Mike Stump1eb44332009-09-09 15:08:12 +0000312PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
313 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000314 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
315 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregor52e71082009-10-16 18:18:30 +0000316 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000317 IdentifierTableData(0), IdentifierLookupTable(0),
318 IdentifierOffsets(0),
319 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
320 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000321 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000322 NumStatHits(0), NumStatMisses(0),
323 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000324 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000325 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000326 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000327 RelocatablePCH = false;
328}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000329
330PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000331 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000332 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregor52e71082009-10-16 18:18:30 +0000333 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000334 IdentifierTableData(0), IdentifierLookupTable(0),
335 IdentifierOffsets(0),
336 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
337 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000338 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000339 NumStatHits(0), NumStatMisses(0),
340 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000341 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000342 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000343 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000344 RelocatablePCH = false;
345}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000346
347PCHReader::~PCHReader() {}
348
Chris Lattnerda930612009-04-27 05:58:23 +0000349Expr *PCHReader::ReadDeclExpr() {
350 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
351}
352
353Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor61d60ee2009-10-17 00:13:19 +0000354 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000355}
356
357
Douglas Gregor668c1a42009-04-21 22:25:48 +0000358namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000359class PCHMethodPoolLookupTrait {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000360 PCHReader &Reader;
361
362public:
363 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
364
365 typedef Selector external_key_type;
366 typedef external_key_type internal_key_type;
367
368 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000370 static bool EqualKey(const internal_key_type& a,
371 const internal_key_type& b) {
372 return a == b;
373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000375 static unsigned ComputeHash(Selector Sel) {
376 unsigned N = Sel.getNumArgs();
377 if (N == 0)
378 ++N;
379 unsigned R = 5381;
380 for (unsigned I = 0; I != N; ++I)
381 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000382 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000383 return R;
384 }
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000386 // This hopefully will just get inlined and removed by the optimizer.
387 static const internal_key_type&
388 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000390 static std::pair<unsigned, unsigned>
391 ReadKeyDataLength(const unsigned char*& d) {
392 using namespace clang::io;
393 unsigned KeyLen = ReadUnalignedLE16(d);
394 unsigned DataLen = ReadUnalignedLE16(d);
395 return std::make_pair(KeyLen, DataLen);
396 }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Douglas Gregor83941df2009-04-25 17:48:32 +0000398 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000399 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000400 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000401 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000402 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000403 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
404 if (N == 0)
405 return SelTable.getNullarySelector(FirstII);
406 else if (N == 1)
407 return SelTable.getUnarySelector(FirstII);
408
409 llvm::SmallVector<IdentifierInfo *, 16> Args;
410 Args.push_back(FirstII);
411 for (unsigned I = 1; I != N; ++I)
412 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
413
Douglas Gregor75fdb232009-05-22 22:45:36 +0000414 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000415 }
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000417 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
418 using namespace clang::io;
419 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
420 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
421
422 data_type Result;
423
424 // Load instance methods
425 ObjCMethodList *Prev = 0;
426 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000427 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000428 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
429 if (!Result.first.Method) {
430 // This is the first method, which is the easy case.
431 Result.first.Method = Method;
432 Prev = &Result.first;
433 continue;
434 }
435
436 Prev->Next = new ObjCMethodList(Method, 0);
437 Prev = Prev->Next;
438 }
439
440 // Load factory methods
441 Prev = 0;
442 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000443 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000444 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
445 if (!Result.second.Method) {
446 // This is the first method, which is the easy case.
447 Result.second.Method = Method;
448 Prev = &Result.second;
449 continue;
450 }
451
452 Prev->Next = new ObjCMethodList(Method, 0);
453 Prev = Prev->Next;
454 }
455
456 return Result;
457 }
458};
Mike Stump1eb44332009-09-09 15:08:12 +0000459
460} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000461
462/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000463typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000464 PCHMethodPoolLookupTable;
465
466namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000467class PCHIdentifierLookupTrait {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000468 PCHReader &Reader;
469
470 // If we know the IdentifierInfo in advance, it is here and we will
471 // not build a new one. Used when deserializing information about an
472 // identifier that was constructed before the PCH file was read.
473 IdentifierInfo *KnownII;
474
475public:
476 typedef IdentifierInfo * data_type;
477
478 typedef const std::pair<const char*, unsigned> external_key_type;
479
480 typedef external_key_type internal_key_type;
481
Mike Stump1eb44332009-09-09 15:08:12 +0000482 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000483 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregor668c1a42009-04-21 22:25:48 +0000485 static bool EqualKey(const internal_key_type& a,
486 const internal_key_type& b) {
487 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
488 : false;
489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Douglas Gregor668c1a42009-04-21 22:25:48 +0000491 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000492 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000493 }
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Douglas Gregor668c1a42009-04-21 22:25:48 +0000495 // This hopefully will just get inlined and removed by the optimizer.
496 static const internal_key_type&
497 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Douglas Gregor668c1a42009-04-21 22:25:48 +0000499 static std::pair<unsigned, unsigned>
500 ReadKeyDataLength(const unsigned char*& d) {
501 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000502 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000503 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000504 return std::make_pair(KeyLen, DataLen);
505 }
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregor668c1a42009-04-21 22:25:48 +0000507 static std::pair<const char*, unsigned>
508 ReadKey(const unsigned char* d, unsigned n) {
509 assert(n >= 2 && d[n-1] == '\0');
510 return std::make_pair((const char*) d, n-1);
511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
513 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000514 const unsigned char* d,
515 unsigned DataLen) {
516 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000517 pch::IdentID ID = ReadUnalignedLE32(d);
518 bool IsInteresting = ID & 0x01;
519
520 // Wipe out the "is interesting" bit.
521 ID = ID >> 1;
522
523 if (!IsInteresting) {
524 // For unintersting identifiers, just build the IdentifierInfo
525 // and associate it with the persistent ID.
526 IdentifierInfo *II = KnownII;
527 if (!II)
528 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
529 k.first, k.first + k.second);
530 Reader.SetIdentifierInfo(ID, II);
531 return II;
532 }
533
Douglas Gregor5998da52009-04-28 21:32:13 +0000534 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000535 bool CPlusPlusOperatorKeyword = Bits & 0x01;
536 Bits >>= 1;
537 bool Poisoned = Bits & 0x01;
538 Bits >>= 1;
539 bool ExtensionToken = Bits & 0x01;
540 Bits >>= 1;
541 bool hasMacroDefinition = Bits & 0x01;
542 Bits >>= 1;
543 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
544 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Douglas Gregor2deaea32009-04-22 18:49:13 +0000546 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000547 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000548
549 // Build the IdentifierInfo itself and link the identifier ID with
550 // the new IdentifierInfo.
551 IdentifierInfo *II = KnownII;
552 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000553 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
554 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000555 Reader.SetIdentifierInfo(ID, II);
556
Douglas Gregor2deaea32009-04-22 18:49:13 +0000557 // Set or check the various bits in the IdentifierInfo structure.
558 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000559 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000560 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000561 "Incorrect extension token flag");
562 (void)ExtensionToken;
563 II->setIsPoisoned(Poisoned);
564 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
565 "Incorrect C++ operator keyword flag");
566 (void)CPlusPlusOperatorKeyword;
567
Douglas Gregor37e26842009-04-21 23:56:24 +0000568 // If this identifier is a macro, deserialize the macro
569 // definition.
570 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000571 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000572 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000573 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000574 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000575
576 // Read all of the declarations visible at global scope with this
577 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000578 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000579 if (DataLen > 0) {
580 llvm::SmallVector<uint32_t, 4> DeclIDs;
581 for (; DataLen > 0; DataLen -= 4)
582 DeclIDs.push_back(ReadUnalignedLE32(d));
583 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000584 }
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Douglas Gregor668c1a42009-04-21 22:25:48 +0000586 return II;
587 }
588};
Mike Stump1eb44332009-09-09 15:08:12 +0000589
590} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000591
592/// \brief The on-disk hash table used to contain information about
593/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000594typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000595 PCHIdentifierLookupTable;
596
Douglas Gregora02b1472009-04-28 21:53:25 +0000597bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000598 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
599 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000600 return true;
601}
602
Douglas Gregore1d918e2009-04-10 23:10:45 +0000603/// \brief Check the contents of the predefines buffer against the
604/// contents of the predefines buffer used to build the PCH file.
605///
606/// The contents of the two predefines buffers should be the same. If
607/// not, then some command-line option changed the preprocessor state
608/// and we must reject the PCH file.
609///
610/// \param PCHPredef The start of the predefines buffer in the PCH
611/// file.
612///
613/// \param PCHPredefLen The length of the predefines buffer in the PCH
614/// file.
615///
616/// \param PCHBufferID The FileID for the PCH predefines buffer.
617///
618/// \returns true if there was a mismatch (in which case the PCH file
619/// should be ignored), or false otherwise.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000620bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000621 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000622 if (Listener)
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000623 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000624 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000625 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000626 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000627}
628
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000629//===----------------------------------------------------------------------===//
630// Source Manager Deserialization
631//===----------------------------------------------------------------------===//
632
Douglas Gregorbd945002009-04-13 16:31:14 +0000633/// \brief Read the line table in the source manager block.
634/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000635bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000636 unsigned Idx = 0;
637 LineTableInfo &LineTable = SourceMgr.getLineTable();
638
639 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000640 std::map<int, int> FileIDs;
641 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000642 // Extract the file name
643 unsigned FilenameLen = Record[Idx++];
644 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
645 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000646 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000647 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000648 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000649 }
650
651 // Parse the line entries
652 std::vector<LineEntry> Entries;
653 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000654 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000655
656 // Extract the line entries
657 unsigned NumEntries = Record[Idx++];
658 Entries.clear();
659 Entries.reserve(NumEntries);
660 for (unsigned I = 0; I != NumEntries; ++I) {
661 unsigned FileOffset = Record[Idx++];
662 unsigned LineNo = Record[Idx++];
663 int FilenameID = Record[Idx++];
Mike Stump1eb44332009-09-09 15:08:12 +0000664 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000665 = (SrcMgr::CharacteristicKind)Record[Idx++];
666 unsigned IncludeOffset = Record[Idx++];
667 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
668 FileKind, IncludeOffset));
669 }
670 LineTable.AddEntry(FID, Entries);
671 }
672
673 return false;
674}
675
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000676namespace {
677
Benjamin Kramerbd218282009-11-28 10:07:24 +0000678class PCHStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000679public:
680 const bool hasStat;
681 const ino_t ino;
682 const dev_t dev;
683 const mode_t mode;
684 const time_t mtime;
685 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000687 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000688 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
689
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000690 PCHStatData()
691 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
692};
693
Benjamin Kramerbd218282009-11-28 10:07:24 +0000694class PCHStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000695 public:
696 typedef const char *external_key_type;
697 typedef const char *internal_key_type;
698
699 typedef PCHStatData data_type;
700
701 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000702 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000703 }
704
705 static internal_key_type GetInternalKey(const char *path) { return path; }
706
707 static bool EqualKey(internal_key_type a, internal_key_type b) {
708 return strcmp(a, b) == 0;
709 }
710
711 static std::pair<unsigned, unsigned>
712 ReadKeyDataLength(const unsigned char*& d) {
713 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
714 unsigned DataLen = (unsigned) *d++;
715 return std::make_pair(KeyLen + 1, DataLen);
716 }
717
718 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
719 return (const char *)d;
720 }
721
722 static data_type ReadData(const internal_key_type, const unsigned char *d,
723 unsigned /*DataLen*/) {
724 using namespace clang::io;
725
726 if (*d++ == 1)
727 return data_type();
728
729 ino_t ino = (ino_t) ReadUnalignedLE32(d);
730 dev_t dev = (dev_t) ReadUnalignedLE32(d);
731 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000732 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000733 off_t size = (off_t) ReadUnalignedLE64(d);
734 return data_type(ino, dev, mode, mtime, size);
735 }
736};
737
738/// \brief stat() cache for precompiled headers.
739///
740/// This cache is very similar to the stat cache used by pretokenized
741/// headers.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000742class PCHStatCache : public StatSysCallCache {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000743 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
744 CacheTy *Cache;
745
746 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000747public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000748 PCHStatCache(const unsigned char *Buckets,
749 const unsigned char *Base,
750 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000751 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000752 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
753 Cache = CacheTy::Create(Buckets, Base);
754 }
755
756 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000758 int stat(const char *path, struct stat *buf) {
759 // Do the lookup for the file's data in the PCH file.
760 CacheTy::iterator I = Cache->find(path);
761
762 // If we don't get a hit in the PCH file just forward to 'stat'.
763 if (I == Cache->end()) {
764 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000765 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000768 ++NumStatHits;
769 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000771 if (!Data.hasStat)
772 return 1;
773
774 buf->st_ino = Data.ino;
775 buf->st_dev = Data.dev;
776 buf->st_mtime = Data.mtime;
777 buf->st_mode = Data.mode;
778 buf->st_size = Data.size;
779 return 0;
780 }
781};
782} // end anonymous namespace
783
784
Douglas Gregor14f79002009-04-10 03:52:48 +0000785/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000786PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000787 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000788
789 // Set the source-location entry cursor to the current position in
790 // the stream. This cursor will be used to read the contents of the
791 // source manager block initially, and then lazily read
792 // source-location entries as needed.
793 SLocEntryCursor = Stream;
794
795 // The stream itself is going to skip over the source manager block.
796 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000797 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000798 return Failure;
799 }
800
801 // Enter the source manager block.
802 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000803 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000804 return Failure;
805 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000806
Douglas Gregor14f79002009-04-10 03:52:48 +0000807 RecordData Record;
808 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000809 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000810 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000811 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000812 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000813 return Failure;
814 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000815 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000816 }
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Douglas Gregor14f79002009-04-10 03:52:48 +0000818 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
819 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000820 SLocEntryCursor.ReadSubBlockID();
821 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000822 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000823 return Failure;
824 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000825 continue;
826 }
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Douglas Gregor14f79002009-04-10 03:52:48 +0000828 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000829 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000830 continue;
831 }
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Douglas Gregor14f79002009-04-10 03:52:48 +0000833 // Read a record.
834 const char *BlobStart;
835 unsigned BlobLen;
836 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000837 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000838 default: // Default behavior: ignore.
839 break;
840
Chris Lattner2c78b872009-04-14 23:22:57 +0000841 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000842 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000843 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000844 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000845
846 case pch::SM_HEADER_FILE_INFO: {
847 HeaderFileInfo HFI;
848 HFI.isImport = Record[0];
849 HFI.DirInfo = Record[1];
850 HFI.NumIncludes = Record[2];
851 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000852 if (Listener)
853 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000854 break;
855 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000856
857 case pch::SM_SLOC_FILE_ENTRY:
858 case pch::SM_SLOC_BUFFER_ENTRY:
859 case pch::SM_SLOC_INSTANTIATION_ENTRY:
860 // Once we hit one of the source location entries, we're done.
861 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000862 }
863 }
864}
865
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000866/// \brief Read in the source location entry with the given ID.
867PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
868 if (ID == 0)
869 return Success;
870
871 if (ID > TotalNumSLocEntries) {
872 Error("source location entry ID out-of-range for PCH file");
873 return Failure;
874 }
875
876 ++NumSLocEntriesRead;
877 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
878 unsigned Code = SLocEntryCursor.ReadCode();
879 if (Code == llvm::bitc::END_BLOCK ||
880 Code == llvm::bitc::ENTER_SUBBLOCK ||
881 Code == llvm::bitc::DEFINE_ABBREV) {
882 Error("incorrectly-formatted source location entry in PCH file");
883 return Failure;
884 }
885
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000886 RecordData Record;
887 const char *BlobStart;
888 unsigned BlobLen;
889 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
890 default:
891 Error("incorrectly-formatted source location entry in PCH file");
892 return Failure;
893
894 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000895 std::string Filename(BlobStart, BlobStart + BlobLen);
896 MaybeAddSystemRootToFilename(Filename);
897 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000898 if (File == 0) {
899 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000900 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000901 ErrorStr += "' referenced by PCH file";
902 Error(ErrorStr.c_str());
903 return Failure;
904 }
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000906 FileID FID = SourceMgr.createFileID(File,
907 SourceLocation::getFromRawEncoding(Record[1]),
908 (SrcMgr::CharacteristicKind)Record[2],
909 ID, Record[0]);
910 if (Record[3])
911 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
912 .setHasLineDirectives();
913
914 break;
915 }
916
917 case pch::SM_SLOC_BUFFER_ENTRY: {
918 const char *Name = BlobStart;
919 unsigned Offset = Record[0];
920 unsigned Code = SLocEntryCursor.ReadCode();
921 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000922 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000923 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
924 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
925 (void)RecCode;
926 llvm::MemoryBuffer *Buffer
Mike Stump1eb44332009-09-09 15:08:12 +0000927 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000928 BlobStart + BlobLen - 1,
929 Name);
930 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Douglas Gregor92b059e2009-04-28 20:33:11 +0000932 if (strcmp(Name, "<built-in>") == 0) {
933 PCHPredefinesBufferID = BufferID;
934 PCHPredefines = BlobStart;
935 PCHPredefinesLen = BlobLen - 1;
936 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000937
938 break;
939 }
940
941 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +0000942 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000943 = SourceLocation::getFromRawEncoding(Record[1]);
944 SourceMgr.createInstantiationLoc(SpellingLoc,
945 SourceLocation::getFromRawEncoding(Record[2]),
946 SourceLocation::getFromRawEncoding(Record[3]),
947 Record[4],
948 ID,
949 Record[0]);
950 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000951 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000952 }
953
954 return Success;
955}
956
Chris Lattner6367f6d2009-04-27 01:05:14 +0000957/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
958/// specified cursor. Read the abbreviations that are at the top of the block
959/// and then leave the cursor pointing into the block.
960bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
961 unsigned BlockID) {
962 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000963 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000964 return Failure;
965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Chris Lattner6367f6d2009-04-27 01:05:14 +0000967 while (true) {
968 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattner6367f6d2009-04-27 01:05:14 +0000970 // We expect all abbrevs to be at the start of the block.
971 if (Code != llvm::bitc::DEFINE_ABBREV)
972 return false;
973 Cursor.ReadAbbrevRecord();
974 }
975}
976
Douglas Gregor37e26842009-04-21 23:56:24 +0000977void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000978 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Douglas Gregor37e26842009-04-21 23:56:24 +0000980 // Keep track of where we are in the stream, then jump back there
981 // after reading this macro.
982 SavedStreamPosition SavedPosition(Stream);
983
984 Stream.JumpToBit(Offset);
985 RecordData Record;
986 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
987 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Douglas Gregor37e26842009-04-21 23:56:24 +0000989 while (true) {
990 unsigned Code = Stream.ReadCode();
991 switch (Code) {
992 case llvm::bitc::END_BLOCK:
993 return;
994
995 case llvm::bitc::ENTER_SUBBLOCK:
996 // No known subblocks, always skip them.
997 Stream.ReadSubBlockID();
998 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000999 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001000 return;
1001 }
1002 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Douglas Gregor37e26842009-04-21 23:56:24 +00001004 case llvm::bitc::DEFINE_ABBREV:
1005 Stream.ReadAbbrevRecord();
1006 continue;
1007 default: break;
1008 }
1009
1010 // Read a record.
1011 Record.clear();
1012 pch::PreprocessorRecordTypes RecType =
1013 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1014 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001015 case pch::PP_MACRO_OBJECT_LIKE:
1016 case pch::PP_MACRO_FUNCTION_LIKE: {
1017 // If we already have a macro, that means that we've hit the end
1018 // of the definition of the macro we were looking for. We're
1019 // done.
1020 if (Macro)
1021 return;
1022
1023 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1024 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001025 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001026 return;
1027 }
1028 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1029 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001031 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001032 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Douglas Gregor37e26842009-04-21 23:56:24 +00001034 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1035 // Decode function-like macro info.
1036 bool isC99VarArgs = Record[3];
1037 bool isGNUVarArgs = Record[4];
1038 MacroArgs.clear();
1039 unsigned NumArgs = Record[5];
1040 for (unsigned i = 0; i != NumArgs; ++i)
1041 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1042
1043 // Install function-like macro info.
1044 MI->setIsFunctionLike();
1045 if (isC99VarArgs) MI->setIsC99Varargs();
1046 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001047 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001048 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001049 }
1050
1051 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001052 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001053
1054 // Remember that we saw this macro last so that we add the tokens that
1055 // form its body to it.
1056 Macro = MI;
1057 ++NumMacrosRead;
1058 break;
1059 }
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Douglas Gregor37e26842009-04-21 23:56:24 +00001061 case pch::PP_TOKEN: {
1062 // If we see a TOKEN before a PP_MACRO_*, then the file is
1063 // erroneous, just pretend we didn't see this.
1064 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregor37e26842009-04-21 23:56:24 +00001066 Token Tok;
1067 Tok.startToken();
1068 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1069 Tok.setLength(Record[1]);
1070 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1071 Tok.setIdentifierInfo(II);
1072 Tok.setKind((tok::TokenKind)Record[3]);
1073 Tok.setFlag((Token::TokenFlags)Record[4]);
1074 Macro->AddTokenToBody(Tok);
1075 break;
1076 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001077 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001078 }
1079}
1080
Douglas Gregore650c8c2009-07-07 00:12:59 +00001081/// \brief If we are loading a relocatable PCH file, and the filename is
1082/// not an absolute path, add the system root to the beginning of the file
1083/// name.
1084void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1085 // If this is not a relocatable PCH file, there's nothing to do.
1086 if (!RelocatablePCH)
1087 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Daniel Dunbard5b21972009-11-18 19:50:41 +00001089 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001090 return;
1091
Douglas Gregore650c8c2009-07-07 00:12:59 +00001092 if (isysroot == 0) {
1093 // If no system root was given, default to '/'
1094 Filename.insert(Filename.begin(), '/');
1095 return;
1096 }
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Douglas Gregore650c8c2009-07-07 00:12:59 +00001098 unsigned Length = strlen(isysroot);
1099 if (isysroot[Length - 1] != '/')
1100 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Douglas Gregore650c8c2009-07-07 00:12:59 +00001102 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1103}
1104
Mike Stump1eb44332009-09-09 15:08:12 +00001105PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001106PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001107 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001108 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001109 return Failure;
1110 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001111
1112 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001113 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001114 while (!Stream.AtEndOfStream()) {
1115 unsigned Code = Stream.ReadCode();
1116 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001117 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001118 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001119 return Failure;
1120 }
Chris Lattner7356a312009-04-11 21:15:38 +00001121
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001122 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001123 }
1124
1125 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1126 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001127 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001128 // We lazily load the decls block, but we want to set up the
1129 // DeclsCursor cursor to point into it. Clone our current bitcode
1130 // cursor to it, enter the block and read the abbrevs in that block.
1131 // With the main cursor, we just skip over it.
1132 DeclsCursor = Stream;
1133 if (Stream.SkipBlock() || // Skip with the main cursor.
1134 // Read the abbrevs.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001135 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001136 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001137 return Failure;
1138 }
1139 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Chris Lattner7356a312009-04-11 21:15:38 +00001141 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001142 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001143 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001144 return Failure;
1145 }
1146 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001147
Douglas Gregor14f79002009-04-10 03:52:48 +00001148 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001149 switch (ReadSourceManagerBlock()) {
1150 case Success:
1151 break;
1152
1153 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001154 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001155 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001156
1157 case IgnorePCH:
1158 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001159 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001160 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001161 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001162 continue;
1163 }
1164
1165 if (Code == llvm::bitc::DEFINE_ABBREV) {
1166 Stream.ReadAbbrevRecord();
1167 continue;
1168 }
1169
1170 // Read and process a record.
1171 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001172 const char *BlobStart = 0;
1173 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001174 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001175 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001176 default: // Default behavior: ignore.
1177 break;
1178
1179 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001180 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001181 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001182 return Failure;
1183 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001184 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001185 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001186 break;
1187
1188 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001189 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001190 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001191 return Failure;
1192 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001193 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001194 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001195 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001196
1197 case pch::LANGUAGE_OPTIONS:
1198 if (ParseLanguageOptions(Record))
1199 return IgnorePCH;
1200 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001201
Douglas Gregorab41e632009-04-27 22:23:34 +00001202 case pch::METADATA: {
1203 if (Record[0] != pch::VERSION_MAJOR) {
1204 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1205 : diag::warn_pch_version_too_new);
1206 return IgnorePCH;
1207 }
1208
Douglas Gregore650c8c2009-07-07 00:12:59 +00001209 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001210 if (Listener) {
1211 std::string TargetTriple(BlobStart, BlobLen);
1212 if (Listener->ReadTargetTriple(TargetTriple))
1213 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001214 }
1215 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001216 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001217
1218 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001219 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001220 if (Record[0]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001221 IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001222 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001223 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001224 (const unsigned char *)IdentifierTableData,
Douglas Gregor668c1a42009-04-21 22:25:48 +00001225 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001226 if (PP)
1227 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001228 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001229 break;
1230
1231 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001232 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001233 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001234 return Failure;
1235 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001236 IdentifierOffsets = (const uint32_t *)BlobStart;
1237 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001238 if (PP)
1239 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001240 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001241
1242 case pch::EXTERNAL_DEFINITIONS:
1243 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001244 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001245 return Failure;
1246 }
1247 ExternalDefinitions.swap(Record);
1248 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001249
Douglas Gregorad1de002009-04-18 05:55:16 +00001250 case pch::SPECIAL_TYPES:
1251 SpecialTypes.swap(Record);
1252 break;
1253
Douglas Gregor3e1af842009-04-17 22:13:46 +00001254 case pch::STATISTICS:
1255 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001256 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001257 TotalLexicalDeclContexts = Record[2];
1258 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001259 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001260
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001261 case pch::TENTATIVE_DEFINITIONS:
1262 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001263 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001264 return Failure;
1265 }
1266 TentativeDefinitions.swap(Record);
1267 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001268
1269 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1270 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001271 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001272 return Failure;
1273 }
1274 LocallyScopedExternalDecls.swap(Record);
1275 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001276
Douglas Gregor83941df2009-04-25 17:48:32 +00001277 case pch::SELECTOR_OFFSETS:
1278 SelectorOffsets = (const uint32_t *)BlobStart;
1279 TotalNumSelectors = Record[0];
1280 SelectorsLoaded.resize(TotalNumSelectors);
1281 break;
1282
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001283 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001284 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1285 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001286 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001287 = PCHMethodPoolLookupTable::Create(
1288 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001289 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001290 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001291 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001292 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001293
1294 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001295 if (!Record.empty() && Listener)
1296 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001297 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001298
1299 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001300 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001301 TotalNumSLocEntries = Record[0];
Douglas Gregor445e23e2009-10-05 21:07:28 +00001302 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001303 break;
1304
1305 case pch::SOURCE_LOCATION_PRELOADS:
1306 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1307 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1308 if (Result != Success)
1309 return Result;
1310 }
1311 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001312
Douglas Gregor52e71082009-10-16 18:18:30 +00001313 case pch::STAT_CACHE: {
1314 PCHStatCache *MyStatCache =
1315 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1316 (const unsigned char *)BlobStart,
1317 NumStatHits, NumStatMisses);
1318 FileMgr.addStatCache(MyStatCache);
1319 StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001320 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001321 }
1322
Douglas Gregorb81c1702009-04-27 20:06:05 +00001323 case pch::EXT_VECTOR_DECLS:
1324 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001325 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001326 return Failure;
1327 }
1328 ExtVectorDecls.swap(Record);
1329 break;
1330
Douglas Gregorb64c1932009-05-12 01:31:05 +00001331 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001332 ActualOriginalFileName.assign(BlobStart, BlobLen);
1333 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001334 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001335 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Douglas Gregor2e222532009-07-02 17:08:52 +00001337 case pch::COMMENT_RANGES:
1338 Comments = (SourceRange *)BlobStart;
1339 NumComments = BlobLen / sizeof(SourceRange);
1340 break;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001341
1342 case pch::SVN_BRANCH_REVISION: {
1343 unsigned CurRevision = getClangSubversionRevision();
1344 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1345 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1346 : diag::warn_pch_version_too_new);
1347 return IgnorePCH;
1348 }
1349
1350 const char *CurBranch = getClangSubversionPath();
1351 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1352 std::string PCHBranch(BlobStart, BlobLen);
1353 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1354 return IgnorePCH;
1355 }
1356 break;
1357 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001358 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001359 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001360 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001361 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001362}
1363
Douglas Gregore1d918e2009-04-10 23:10:45 +00001364PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001365 // Set the PCH file name.
1366 this->FileName = FileName;
1367
Douglas Gregor2cf26342009-04-09 22:27:44 +00001368 // Open the PCH file.
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001369 //
1370 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001371 std::string ErrStr;
Daniel Dunbar731ad8f2009-11-10 00:46:19 +00001372 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001373 if (!Buffer) {
1374 Error(ErrStr.c_str());
1375 return IgnorePCH;
1376 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001377
1378 // Initialize the stream
Mike Stump1eb44332009-09-09 15:08:12 +00001379 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001380 (const unsigned char *)Buffer->getBufferEnd());
1381 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001382
1383 // Sniff for the signature.
1384 if (Stream.Read(8) != 'C' ||
1385 Stream.Read(8) != 'P' ||
1386 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001387 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001388 Diag(diag::err_not_a_pch_file) << FileName;
1389 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001390 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001391
Douglas Gregor2cf26342009-04-09 22:27:44 +00001392 while (!Stream.AtEndOfStream()) {
1393 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Douglas Gregore1d918e2009-04-10 23:10:45 +00001395 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001396 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001397 return Failure;
1398 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001399
1400 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001401
Douglas Gregor2cf26342009-04-09 22:27:44 +00001402 // We only know the PCH subblock ID.
1403 switch (BlockID) {
1404 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001405 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001406 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001407 return Failure;
1408 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001409 break;
1410 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001411 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001412 case Success:
1413 break;
1414
1415 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001416 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001417
1418 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001419 // FIXME: We could consider reading through to the end of this
1420 // PCH block, skipping subblocks, to see if there are other
1421 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001422
1423 // Clear out any preallocated source location entries, so that
1424 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001425 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001426
1427 // Remove the stat cache.
Douglas Gregor52e71082009-10-16 18:18:30 +00001428 if (StatCache)
1429 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001430
Douglas Gregore1d918e2009-04-10 23:10:45 +00001431 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001432 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001433 break;
1434 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001435 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001436 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001437 return Failure;
1438 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001439 break;
1440 }
Mike Stump1eb44332009-09-09 15:08:12 +00001441 }
1442
Douglas Gregor92b059e2009-04-28 20:33:11 +00001443 // Check the predefines buffer.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +00001444 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregor92b059e2009-04-28 20:33:11 +00001445 PCHPredefinesBufferID))
1446 return IgnorePCH;
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001448 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001449 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001450 // PCH file is read, so there may be some identifiers that were
1451 // loaded into the IdentifierTable before we intercepted the
1452 // creation of identifiers. Iterate through the list of known
1453 // identifiers and determine whether we have to establish
1454 // preprocessor definitions or top-level identifier declaration
1455 // chains for those identifiers.
1456 //
1457 // We copy the IdentifierInfo pointers to a small vector first,
1458 // since de-serializing declarations or macro definitions can add
1459 // new entries into the identifier table, invalidating the
1460 // iterators.
1461 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1462 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1463 IdEnd = PP->getIdentifierTable().end();
1464 Id != IdEnd; ++Id)
1465 Identifiers.push_back(Id->second);
Mike Stump1eb44332009-09-09 15:08:12 +00001466 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001467 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1468 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1469 IdentifierInfo *II = Identifiers[I];
1470 // Look in the on-disk hash table for an entry for
1471 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbare013d682009-10-18 20:26:12 +00001472 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001473 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1474 if (Pos == IdTable->end())
1475 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001477 // Dereferencing the iterator has the effect of populating the
1478 // IdentifierInfo node with the various declarations it needs.
1479 (void)*Pos;
1480 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001481 }
1482
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001483 if (Context)
1484 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001485
Douglas Gregor668c1a42009-04-21 22:25:48 +00001486 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001487}
1488
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001489void PCHReader::InitializeContext(ASTContext &Ctx) {
1490 Context = &Ctx;
1491 assert(Context && "Passed null context!");
1492
1493 assert(PP && "Forgot to set Preprocessor ?");
1494 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1495 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001497 // Load the translation unit declaration
1498 ReadDeclRecord(DeclOffsets[0], 0);
1499
1500 // Load the special types.
1501 Context->setBuiltinVaListType(
1502 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1503 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1504 Context->setObjCIdType(GetType(Id));
1505 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1506 Context->setObjCSelType(GetType(Sel));
1507 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1508 Context->setObjCProtoType(GetType(Proto));
1509 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1510 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001511
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001512 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1513 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001514 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001515 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1516 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001517 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1518 QualType FileType = GetType(File);
1519 assert(!FileType.isNull() && "FILE type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001520 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001521 Context->setFILEDecl(Typedef->getDecl());
1522 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001523 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001524 assert(Tag && "Invalid FILE type in PCH file");
1525 Context->setFILEDecl(Tag->getDecl());
1526 }
1527 }
Mike Stump782fa302009-07-28 02:25:19 +00001528 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1529 QualType Jmp_bufType = GetType(Jmp_buf);
1530 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001531 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001532 Context->setjmp_bufDecl(Typedef->getDecl());
1533 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001534 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001535 assert(Tag && "Invalid jmp_bug type in PCH file");
1536 Context->setjmp_bufDecl(Tag->getDecl());
1537 }
1538 }
1539 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1540 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1541 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001542 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001543 Context->setsigjmp_bufDecl(Typedef->getDecl());
1544 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001545 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001546 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1547 Context->setsigjmp_bufDecl(Tag->getDecl());
1548 }
1549 }
Mike Stump1eb44332009-09-09 15:08:12 +00001550 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001551 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1552 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001553 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001554 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1555 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001556#if 0
1557 // FIXME. Accommodate for this in several PCH/Index tests
1558 if (unsigned ObjCSelRedef
1559 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00001560 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001561#endif
Mike Stumpadaaad32009-10-20 02:12:22 +00001562 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1563 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00001564 if (unsigned String
1565 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1566 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001567}
1568
Douglas Gregorb64c1932009-05-12 01:31:05 +00001569/// \brief Retrieve the name of the original source file name
1570/// directly from the PCH file, without actually loading the PCH
1571/// file.
1572std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1573 // Open the PCH file.
1574 std::string ErrStr;
1575 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1576 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1577 if (!Buffer) {
1578 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1579 return std::string();
1580 }
1581
1582 // Initialize the stream
1583 llvm::BitstreamReader StreamFile;
1584 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00001585 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00001586 (const unsigned char *)Buffer->getBufferEnd());
1587 Stream.init(StreamFile);
1588
1589 // Sniff for the signature.
1590 if (Stream.Read(8) != 'C' ||
1591 Stream.Read(8) != 'P' ||
1592 Stream.Read(8) != 'C' ||
1593 Stream.Read(8) != 'H') {
Mike Stump1eb44332009-09-09 15:08:12 +00001594 fprintf(stderr,
Douglas Gregorb64c1932009-05-12 01:31:05 +00001595 "error: '%s' does not appear to be a precompiled header file\n",
1596 PCHFileName.c_str());
1597 return std::string();
1598 }
1599
1600 RecordData Record;
1601 while (!Stream.AtEndOfStream()) {
1602 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Douglas Gregorb64c1932009-05-12 01:31:05 +00001604 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1605 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Douglas Gregorb64c1932009-05-12 01:31:05 +00001607 // We only know the PCH subblock ID.
1608 switch (BlockID) {
1609 case pch::PCH_BLOCK_ID:
1610 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1611 fprintf(stderr, "error: malformed block record in PCH file\n");
1612 return std::string();
1613 }
1614 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Douglas Gregorb64c1932009-05-12 01:31:05 +00001616 default:
1617 if (Stream.SkipBlock()) {
1618 fprintf(stderr, "error: malformed block record in PCH file\n");
1619 return std::string();
1620 }
1621 break;
1622 }
1623 continue;
1624 }
1625
1626 if (Code == llvm::bitc::END_BLOCK) {
1627 if (Stream.ReadBlockEnd()) {
1628 fprintf(stderr, "error: error at end of module block in PCH file\n");
1629 return std::string();
1630 }
1631 continue;
1632 }
1633
1634 if (Code == llvm::bitc::DEFINE_ABBREV) {
1635 Stream.ReadAbbrevRecord();
1636 continue;
1637 }
1638
1639 Record.clear();
1640 const char *BlobStart = 0;
1641 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001642 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00001643 == pch::ORIGINAL_FILE_NAME)
1644 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001645 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00001646
1647 return std::string();
1648}
1649
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001650/// \brief Parse the record that corresponds to a LangOptions data
1651/// structure.
1652///
1653/// This routine compares the language options used to generate the
1654/// PCH file against the language options set for the current
1655/// compilation. For each option, we classify differences between the
1656/// two compiler states as either "benign" or "important". Benign
1657/// differences don't matter, and we accept them without complaint
1658/// (and without modifying the language options). Differences between
1659/// the states for important options cause the PCH file to be
1660/// unusable, so we emit a warning and return true to indicate that
1661/// there was an error.
1662///
1663/// \returns true if the PCH file is unacceptable, false otherwise.
1664bool PCHReader::ParseLanguageOptions(
1665 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001666 if (Listener) {
1667 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001669 #define PARSE_LANGOPT(Option) \
1670 LangOpts.Option = Record[Idx]; \
1671 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001673 unsigned Idx = 0;
1674 PARSE_LANGOPT(Trigraphs);
1675 PARSE_LANGOPT(BCPLComment);
1676 PARSE_LANGOPT(DollarIdents);
1677 PARSE_LANGOPT(AsmPreprocessor);
1678 PARSE_LANGOPT(GNUMode);
1679 PARSE_LANGOPT(ImplicitInt);
1680 PARSE_LANGOPT(Digraphs);
1681 PARSE_LANGOPT(HexFloats);
1682 PARSE_LANGOPT(C99);
1683 PARSE_LANGOPT(Microsoft);
1684 PARSE_LANGOPT(CPlusPlus);
1685 PARSE_LANGOPT(CPlusPlus0x);
1686 PARSE_LANGOPT(CXXOperatorNames);
1687 PARSE_LANGOPT(ObjC1);
1688 PARSE_LANGOPT(ObjC2);
1689 PARSE_LANGOPT(ObjCNonFragileABI);
1690 PARSE_LANGOPT(PascalStrings);
1691 PARSE_LANGOPT(WritableStrings);
1692 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001693 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001694 PARSE_LANGOPT(Exceptions);
1695 PARSE_LANGOPT(NeXTRuntime);
1696 PARSE_LANGOPT(Freestanding);
1697 PARSE_LANGOPT(NoBuiltin);
1698 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00001699 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001700 PARSE_LANGOPT(Blocks);
1701 PARSE_LANGOPT(EmitAllDecls);
1702 PARSE_LANGOPT(MathErrno);
1703 PARSE_LANGOPT(OverflowChecking);
1704 PARSE_LANGOPT(HeinousExtensions);
1705 PARSE_LANGOPT(Optimize);
1706 PARSE_LANGOPT(OptimizeSize);
1707 PARSE_LANGOPT(Static);
1708 PARSE_LANGOPT(PICLevel);
1709 PARSE_LANGOPT(GNUInline);
1710 PARSE_LANGOPT(NoInline);
1711 PARSE_LANGOPT(AccessControl);
1712 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00001713 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001714 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1715 ++Idx;
1716 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1717 ++Idx;
Daniel Dunbarab8e2812009-09-21 04:16:19 +00001718 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1719 Record[Idx]);
1720 ++Idx;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001721 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001722 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001723 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001724
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001725 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001726 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001727
1728 return false;
1729}
1730
Douglas Gregor2e222532009-07-02 17:08:52 +00001731void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1732 Comments.resize(NumComments);
1733 std::copy(this->Comments, this->Comments + NumComments,
1734 Comments.begin());
1735}
1736
Douglas Gregor2cf26342009-04-09 22:27:44 +00001737/// \brief Read and return the type at the given offset.
1738///
1739/// This routine actually reads the record corresponding to the type
1740/// at the given offset in the bitstream. It is a helper routine for
1741/// GetType, which deals with reading type IDs.
1742QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001743 // Keep track of where we are in the stream, then jump back there
1744 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001745 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001746
Douglas Gregord89275b2009-07-06 18:54:52 +00001747 // Note that we are loading a type record.
1748 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001750 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001751 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001752 unsigned Code = DeclsCursor.ReadCode();
1753 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001754 case pch::TYPE_EXT_QUAL: {
John McCall0953e762009-09-24 19:53:00 +00001755 assert(Record.size() == 2 &&
Douglas Gregor6d473962009-04-15 22:00:08 +00001756 "Incorrect encoding of extended qualifier type");
1757 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00001758 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1759 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00001760 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001761
Douglas Gregor2cf26342009-04-09 22:27:44 +00001762 case pch::TYPE_FIXED_WIDTH_INT: {
1763 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001764 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001765 }
1766
1767 case pch::TYPE_COMPLEX: {
1768 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1769 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001770 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001771 }
1772
1773 case pch::TYPE_POINTER: {
1774 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1775 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001776 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001777 }
1778
1779 case pch::TYPE_BLOCK_POINTER: {
1780 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1781 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001782 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001783 }
1784
1785 case pch::TYPE_LVALUE_REFERENCE: {
1786 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1787 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001788 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001789 }
1790
1791 case pch::TYPE_RVALUE_REFERENCE: {
1792 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1793 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001794 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001795 }
1796
1797 case pch::TYPE_MEMBER_POINTER: {
1798 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1799 QualType PointeeType = GetType(Record[0]);
1800 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001801 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001802 }
1803
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001804 case pch::TYPE_CONSTANT_ARRAY: {
1805 QualType ElementType = GetType(Record[0]);
1806 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1807 unsigned IndexTypeQuals = Record[2];
1808 unsigned Idx = 3;
1809 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001810 return Context->getConstantArrayType(ElementType, Size,
1811 ASM, IndexTypeQuals);
1812 }
1813
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001814 case pch::TYPE_INCOMPLETE_ARRAY: {
1815 QualType ElementType = GetType(Record[0]);
1816 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1817 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001818 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001819 }
1820
1821 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001822 QualType ElementType = GetType(Record[0]);
1823 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1824 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001825 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1826 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001827 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001828 ASM, IndexTypeQuals,
1829 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001830 }
1831
1832 case pch::TYPE_VECTOR: {
1833 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001834 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001835 return QualType();
1836 }
1837
1838 QualType ElementType = GetType(Record[0]);
1839 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001840 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001841 }
1842
1843 case pch::TYPE_EXT_VECTOR: {
1844 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001845 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001846 return QualType();
1847 }
1848
1849 QualType ElementType = GetType(Record[0]);
1850 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001851 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001852 }
1853
1854 case pch::TYPE_FUNCTION_NO_PROTO: {
1855 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001856 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001857 return QualType();
1858 }
1859 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001860 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001861 }
1862
1863 case pch::TYPE_FUNCTION_PROTO: {
1864 QualType ResultType = GetType(Record[0]);
1865 unsigned Idx = 1;
1866 unsigned NumParams = Record[Idx++];
1867 llvm::SmallVector<QualType, 16> ParamTypes;
1868 for (unsigned I = 0; I != NumParams; ++I)
1869 ParamTypes.push_back(GetType(Record[Idx++]));
1870 bool isVariadic = Record[Idx++];
1871 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001872 bool hasExceptionSpec = Record[Idx++];
1873 bool hasAnyExceptionSpec = Record[Idx++];
1874 unsigned NumExceptions = Record[Idx++];
1875 llvm::SmallVector<QualType, 2> Exceptions;
1876 for (unsigned I = 0; I != NumExceptions; ++I)
1877 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001878 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001879 isVariadic, Quals, hasExceptionSpec,
1880 hasAnyExceptionSpec, NumExceptions,
1881 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001882 }
1883
1884 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001885 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001886 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001887
1888 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001889 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001890
1891 case pch::TYPE_TYPEOF: {
1892 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001893 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001894 return QualType();
1895 }
1896 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001897 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001898 }
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Anders Carlsson395b4752009-06-24 19:06:50 +00001900 case pch::TYPE_DECLTYPE:
1901 return Context->getDecltypeType(ReadTypeExpr());
1902
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001903 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001904 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001905 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001906
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001907 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001908 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001909 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001910
John McCall7da24312009-09-05 00:15:47 +00001911 case pch::TYPE_ELABORATED: {
1912 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1913 unsigned Tag = Record[1];
1914 return Context->getElaboratedType(GetType(Record[0]),
1915 (ElaboratedType::TagKind) Tag);
1916 }
1917
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001918 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001919 unsigned Idx = 0;
1920 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1921 unsigned NumProtos = Record[Idx++];
1922 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1923 for (unsigned I = 0; I != NumProtos; ++I)
1924 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001925 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001926 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001927
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001928 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001929 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00001930 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001931 unsigned NumProtos = Record[Idx++];
1932 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1933 for (unsigned I = 0; I != NumProtos; ++I)
1934 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00001935 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001936 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00001937
John McCall49a832b2009-10-18 09:09:24 +00001938 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
1939 unsigned Idx = 0;
1940 QualType Parm = GetType(Record[Idx++]);
1941 QualType Replacement = GetType(Record[Idx++]);
1942 return
1943 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
1944 Replacement);
1945 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001946 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001947 // Suppress a GCC warning
1948 return QualType();
1949}
1950
John McCalla1ee0c52009-10-16 21:56:05 +00001951namespace {
1952
1953class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
1954 PCHReader &Reader;
1955 const PCHReader::RecordData &Record;
1956 unsigned &Idx;
1957
1958public:
1959 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
1960 unsigned &Idx)
1961 : Reader(Reader), Record(Record), Idx(Idx) { }
1962
John McCall51bd8032009-10-18 01:05:36 +00001963 // We want compile-time assurance that we've enumerated all of
1964 // these, so unfortunately we have to declare them first, then
1965 // define them out-of-line.
1966#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00001967#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00001968 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00001969#include "clang/AST/TypeLocNodes.def"
1970
John McCall51bd8032009-10-18 01:05:36 +00001971 void VisitFunctionTypeLoc(FunctionTypeLoc);
1972 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00001973};
1974
1975}
1976
John McCall51bd8032009-10-18 01:05:36 +00001977void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00001978 // nothing to do
1979}
John McCall51bd8032009-10-18 01:05:36 +00001980void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1981 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001982}
John McCall51bd8032009-10-18 01:05:36 +00001983void TypeLocReader::VisitFixedWidthIntTypeLoc(FixedWidthIntTypeLoc TL) {
1984 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001985}
John McCall51bd8032009-10-18 01:05:36 +00001986void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
1987 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001988}
John McCall51bd8032009-10-18 01:05:36 +00001989void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
1990 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001991}
John McCall51bd8032009-10-18 01:05:36 +00001992void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1993 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001994}
John McCall51bd8032009-10-18 01:05:36 +00001995void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1996 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001997}
John McCall51bd8032009-10-18 01:05:36 +00001998void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1999 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002000}
John McCall51bd8032009-10-18 01:05:36 +00002001void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2002 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002003}
John McCall51bd8032009-10-18 01:05:36 +00002004void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2005 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2006 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002007 if (Record[Idx++])
John McCall51bd8032009-10-18 01:05:36 +00002008 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002009 else
John McCall51bd8032009-10-18 01:05:36 +00002010 TL.setSizeExpr(0);
2011}
2012void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2013 VisitArrayTypeLoc(TL);
2014}
2015void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2016 VisitArrayTypeLoc(TL);
2017}
2018void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2019 VisitArrayTypeLoc(TL);
2020}
2021void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2022 DependentSizedArrayTypeLoc TL) {
2023 VisitArrayTypeLoc(TL);
2024}
2025void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2026 DependentSizedExtVectorTypeLoc TL) {
2027 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2028}
2029void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2030 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2031}
2032void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2033 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2034}
2035void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2036 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2037 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2038 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002039 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002040 }
2041}
2042void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2043 VisitFunctionTypeLoc(TL);
2044}
2045void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2046 VisitFunctionTypeLoc(TL);
2047}
2048void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2049 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2050}
2051void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2052 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2053}
2054void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2055 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2056}
2057void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2058 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2059}
2060void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2061 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2062}
2063void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2064 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2065}
2066void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2067 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2068}
2069void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2070 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2071}
John McCall49a832b2009-10-18 09:09:24 +00002072void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2073 SubstTemplateTypeParmTypeLoc TL) {
2074 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2075}
John McCall51bd8032009-10-18 01:05:36 +00002076void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2077 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002078 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2079 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2080 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2081 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2082 TL.setArgLocInfo(i,
2083 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2084 Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002085}
2086void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2087 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2088}
2089void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2090 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2091}
2092void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2093 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002094 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2095 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2096 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2097 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002098}
John McCall54e14c42009-10-22 22:37:11 +00002099void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2100 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2101 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2102 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2103 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2104 TL.setHasProtocolsAsWritten(Record[Idx++]);
2105 if (TL.hasProtocolsAsWritten())
2106 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2107 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2108}
John McCalla1ee0c52009-10-16 21:56:05 +00002109
2110DeclaratorInfo *PCHReader::GetDeclaratorInfo(const RecordData &Record,
2111 unsigned &Idx) {
2112 QualType InfoTy = GetType(Record[Idx++]);
2113 if (InfoTy.isNull())
2114 return 0;
2115
2116 DeclaratorInfo *DInfo = getContext()->CreateDeclaratorInfo(InfoTy);
2117 TypeLocReader TLR(*this, Record, Idx);
2118 for (TypeLoc TL = DInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2119 TLR.Visit(TL);
2120 return DInfo;
2121}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002122
Douglas Gregor8038d512009-04-10 17:25:41 +00002123QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002124 unsigned FastQuals = ID & Qualifiers::FastMask;
2125 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002126
2127 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2128 QualType T;
2129 switch ((pch::PredefinedTypeIDs)Index) {
2130 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002131 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2132 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002133
2134 case pch::PREDEF_TYPE_CHAR_U_ID:
2135 case pch::PREDEF_TYPE_CHAR_S_ID:
2136 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002137 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002138 break;
2139
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002140 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2141 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2142 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2143 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2144 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002145 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002146 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2147 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2148 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2149 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2150 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2151 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002152 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002153 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2154 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2155 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2156 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2157 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002158 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002159 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2160 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002161 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2162 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002163 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002164 }
2165
2166 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002167 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002168 }
2169
2170 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002171 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall0953e762009-09-24 19:53:00 +00002172 if (TypesLoaded[Index].isNull())
2173 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump1eb44332009-09-09 15:08:12 +00002174
John McCall0953e762009-09-24 19:53:00 +00002175 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002176}
2177
John McCall833ca992009-10-29 08:12:44 +00002178TemplateArgumentLocInfo
2179PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2180 const RecordData &Record,
2181 unsigned &Index) {
2182 switch (Kind) {
2183 case TemplateArgument::Expression:
2184 return ReadDeclExpr();
2185 case TemplateArgument::Type:
2186 return GetDeclaratorInfo(Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002187 case TemplateArgument::Template: {
2188 SourceLocation
2189 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2190 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2191 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2192 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2193 TemplateNameLoc);
2194 }
John McCall833ca992009-10-29 08:12:44 +00002195 case TemplateArgument::Null:
2196 case TemplateArgument::Integral:
2197 case TemplateArgument::Declaration:
2198 case TemplateArgument::Pack:
2199 return TemplateArgumentLocInfo();
2200 }
2201 llvm::llvm_unreachable("unexpected template argument loc");
2202 return TemplateArgumentLocInfo();
2203}
2204
Douglas Gregor8038d512009-04-10 17:25:41 +00002205Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002206 if (ID == 0)
2207 return 0;
2208
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002209 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002210 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002211 return 0;
2212 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002213
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002214 unsigned Index = ID - 1;
2215 if (!DeclsLoaded[Index])
2216 ReadDeclRecord(DeclOffsets[Index], Index);
2217
2218 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002219}
2220
Chris Lattner887e2b32009-04-27 05:46:25 +00002221/// \brief Resolve the offset of a statement into a statement.
2222///
2223/// This operation will read a new statement from the external
2224/// source each time it is called, and is meant to be used via a
2225/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2226Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002227 // Since we know tha this statement is part of a decl, make sure to use the
2228 // decl cursor to read it.
2229 DeclsCursor.JumpToBit(Offset);
2230 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002231}
2232
Douglas Gregor2cf26342009-04-09 22:27:44 +00002233bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002234 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002235 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002236 "DeclContext has no lexical decls in storage");
2237 uint64_t Offset = DeclContextOffsets[DC].first;
2238 assert(Offset && "DeclContext has no lexical decls in storage");
2239
Douglas Gregor0b748912009-04-14 21:18:50 +00002240 // Keep track of where we are in the stream, then jump back there
2241 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002242 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002243
Douglas Gregor2cf26342009-04-09 22:27:44 +00002244 // Load the record containing all of the declarations lexically in
2245 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002246 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002247 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002248 unsigned Code = DeclsCursor.ReadCode();
2249 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002250 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002251 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2252
2253 // Load all of the declaration IDs
2254 Decls.clear();
2255 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002256 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002257 return false;
2258}
2259
2260bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002261 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002262 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002263 "DeclContext has no visible decls in storage");
2264 uint64_t Offset = DeclContextOffsets[DC].second;
2265 assert(Offset && "DeclContext has no visible decls in storage");
2266
Douglas Gregor0b748912009-04-14 21:18:50 +00002267 // Keep track of where we are in the stream, then jump back there
2268 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002269 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002270
Douglas Gregor2cf26342009-04-09 22:27:44 +00002271 // Load the record containing all of the declarations visible in
2272 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002273 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002274 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002275 unsigned Code = DeclsCursor.ReadCode();
2276 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002277 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002278 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2279 if (Record.size() == 0)
Mike Stump1eb44332009-09-09 15:08:12 +00002280 return false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002281
2282 Decls.clear();
2283
2284 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002285 while (Idx < Record.size()) {
2286 Decls.push_back(VisibleDeclaration());
2287 Decls.back().Name = ReadDeclarationName(Record, Idx);
2288
Douglas Gregor2cf26342009-04-09 22:27:44 +00002289 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002290 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002291 LoadedDecls.reserve(Size);
2292 for (unsigned I = 0; I < Size; ++I)
2293 LoadedDecls.push_back(Record[Idx++]);
2294 }
2295
Douglas Gregor25123082009-04-22 22:34:57 +00002296 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002297 return false;
2298}
2299
Douglas Gregorfdd01722009-04-14 00:24:19 +00002300void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002301 this->Consumer = Consumer;
2302
Douglas Gregorfdd01722009-04-14 00:24:19 +00002303 if (!Consumer)
2304 return;
2305
2306 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002307 // Force deserialization of this decl, which will cause it to be passed to
2308 // the consumer (or queued).
2309 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002310 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002311
2312 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2313 DeclGroupRef DG(InterestingDecls[I]);
2314 Consumer->HandleTopLevelDecl(DG);
2315 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002316}
2317
Douglas Gregor2cf26342009-04-09 22:27:44 +00002318void PCHReader::PrintStats() {
2319 std::fprintf(stderr, "*** PCH Statistics:\n");
2320
Mike Stump1eb44332009-09-09 15:08:12 +00002321 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002322 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002323 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002324 unsigned NumDeclsLoaded
2325 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2326 (Decl *)0);
2327 unsigned NumIdentifiersLoaded
2328 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2329 IdentifiersLoaded.end(),
2330 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002331 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002332 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2333 SelectorsLoaded.end(),
2334 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002335
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002336 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2337 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002338 if (TotalNumSLocEntries)
2339 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2340 NumSLocEntriesRead, TotalNumSLocEntries,
2341 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002342 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002343 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002344 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2345 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2346 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002347 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002348 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2349 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002350 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002351 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002352 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2353 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002354 if (TotalNumSelectors)
2355 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2356 NumSelectorsLoaded, TotalNumSelectors,
2357 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2358 if (TotalNumStatements)
2359 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2360 NumStatementsRead, TotalNumStatements,
2361 ((float)NumStatementsRead/TotalNumStatements * 100));
2362 if (TotalNumMacros)
2363 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2364 NumMacrosRead, TotalNumMacros,
2365 ((float)NumMacrosRead/TotalNumMacros * 100));
2366 if (TotalLexicalDeclContexts)
2367 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2368 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2369 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2370 * 100));
2371 if (TotalVisibleDeclContexts)
2372 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2373 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2374 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2375 * 100));
2376 if (TotalSelectorsInMethodPool) {
2377 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2378 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2379 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2380 * 100));
2381 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2382 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002383 std::fprintf(stderr, "\n");
2384}
2385
Douglas Gregor668c1a42009-04-21 22:25:48 +00002386void PCHReader::InitializeSema(Sema &S) {
2387 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002388 S.ExternalSource = this;
2389
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002390 // Makes sure any declarations that were deserialized "too early"
2391 // still get added to the identifier's declaration chains.
2392 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2393 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2394 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002395 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002396 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002397
2398 // If there were any tentative definitions, deserialize them and add
2399 // them to Sema's table of tentative definitions.
2400 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2401 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2402 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner63d65f82009-09-08 18:19:27 +00002403 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002404 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002405
2406 // If there were any locally-scoped external declarations,
2407 // deserialize them and add them to Sema's table of locally-scoped
2408 // external declarations.
2409 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2410 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2411 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2412 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002413
2414 // If there were any ext_vector type declarations, deserialize them
2415 // and add them to Sema's vector of such declarations.
2416 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2417 SemaObj->ExtVectorDecls.push_back(
2418 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002419}
2420
2421IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2422 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00002423 PCHIdentifierLookupTable *IdTable
Douglas Gregor668c1a42009-04-21 22:25:48 +00002424 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2425 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2426 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2427 if (Pos == IdTable->end())
2428 return 0;
2429
2430 // Dereferencing the iterator has the effect of building the
2431 // IdentifierInfo node and populating it with the various
2432 // declarations it needs.
2433 return *Pos;
2434}
2435
Mike Stump1eb44332009-09-09 15:08:12 +00002436std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002437PCHReader::ReadMethodPool(Selector Sel) {
2438 if (!MethodPoolLookupTable)
2439 return std::pair<ObjCMethodList, ObjCMethodList>();
2440
2441 // Try to find this selector within our on-disk hash table.
2442 PCHMethodPoolLookupTable *PoolTable
2443 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2444 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002445 if (Pos == PoolTable->end()) {
2446 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002447 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002448 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002449
Douglas Gregor83941df2009-04-25 17:48:32 +00002450 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002451 return *Pos;
2452}
2453
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002454void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002455 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002456 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002457 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002458}
2459
Douglas Gregord89275b2009-07-06 18:54:52 +00002460/// \brief Set the globally-visible declarations associated with the given
2461/// identifier.
2462///
2463/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00002464/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00002465/// them.
2466///
2467/// \param II an IdentifierInfo that refers to one or more globally-visible
2468/// declarations.
2469///
2470/// \param DeclIDs the set of declaration IDs with the name @p II that are
2471/// visible at global scope.
2472///
2473/// \param Nonrecursive should be true to indicate that the caller knows that
2474/// this call is non-recursive, and therefore the globally-visible declarations
2475/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00002476void
2477PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00002478 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2479 bool Nonrecursive) {
2480 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2481 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2482 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2483 PII.II = II;
2484 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2485 PII.DeclIDs.push_back(DeclIDs[I]);
2486 return;
2487 }
Mike Stump1eb44332009-09-09 15:08:12 +00002488
Douglas Gregord89275b2009-07-06 18:54:52 +00002489 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2490 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2491 if (SemaObj) {
2492 // Introduce this declaration into the translation-unit scope
2493 // and add it to the declaration chain for this identifier, so
2494 // that (unqualified) name lookup will find it.
2495 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2496 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2497 } else {
2498 // Queue this declaration so that it will be added to the
2499 // translation unit scope and identifier's declaration chain
2500 // once a Sema object is known.
2501 PreloadedDecls.push_back(D);
2502 }
2503 }
2504}
2505
Chris Lattner7356a312009-04-11 21:15:38 +00002506IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002507 if (ID == 0)
2508 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002510 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002511 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002512 return 0;
2513 }
Mike Stump1eb44332009-09-09 15:08:12 +00002514
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002515 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002516 if (!IdentifiersLoaded[ID - 1]) {
2517 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002518 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002519
Douglas Gregor02fc7512009-04-28 20:01:51 +00002520 // All of the strings in the PCH file are preceded by a 16-bit
2521 // length. Extract that 16-bit length to avoid having to execute
2522 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00002523 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2524 // unsigned integers. This is important to avoid integer overflow when
2525 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00002526 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00002527 unsigned StrLen = (((unsigned) StrLenPtr[0])
2528 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002529 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002530 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002531 }
Mike Stump1eb44332009-09-09 15:08:12 +00002532
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002533 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002534}
2535
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002536void PCHReader::ReadSLocEntry(unsigned ID) {
2537 ReadSLocEntryRecord(ID);
2538}
2539
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002540Selector PCHReader::DecodeSelector(unsigned ID) {
2541 if (ID == 0)
2542 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00002543
Douglas Gregora02b1472009-04-28 21:53:25 +00002544 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002545 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002546
2547 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002548 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002549 return Selector();
2550 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002551
2552 unsigned Index = ID - 1;
2553 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2554 // Load this selector from the selector table.
2555 // FIXME: endianness portability issues with SelectorOffsets table
2556 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002557 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00002558 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2559 }
2560
2561 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002562}
2563
Mike Stump1eb44332009-09-09 15:08:12 +00002564DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00002565PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2566 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2567 switch (Kind) {
2568 case DeclarationName::Identifier:
2569 return DeclarationName(GetIdentifierInfo(Record, Idx));
2570
2571 case DeclarationName::ObjCZeroArgSelector:
2572 case DeclarationName::ObjCOneArgSelector:
2573 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002574 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002575
2576 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002577 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002578 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002579
2580 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002581 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002582 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002583
2584 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002585 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002586 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002587
2588 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002589 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002590 (OverloadedOperatorKind)Record[Idx++]);
2591
2592 case DeclarationName::CXXUsingDirective:
2593 return DeclarationName::getUsingDirectiveName();
2594 }
2595
2596 // Required to silence GCC warning
2597 return DeclarationName();
2598}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002599
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002600/// \brief Read an integral value
2601llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2602 unsigned BitWidth = Record[Idx++];
2603 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2604 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2605 Idx += NumWords;
2606 return Result;
2607}
2608
2609/// \brief Read a signed integral value
2610llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2611 bool isUnsigned = Record[Idx++];
2612 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2613}
2614
Douglas Gregor17fc2232009-04-14 21:55:33 +00002615/// \brief Read a floating-point value
2616llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002617 return llvm::APFloat(ReadAPInt(Record, Idx));
2618}
2619
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002620// \brief Read a string
2621std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2622 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002623 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002624 Idx += Len;
2625 return Result;
2626}
2627
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002628DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002629 return Diag(SourceLocation(), DiagID);
2630}
2631
2632DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002633 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002634}
Douglas Gregor025452f2009-04-17 00:04:06 +00002635
Douglas Gregor668c1a42009-04-21 22:25:48 +00002636/// \brief Retrieve the identifier table associated with the
2637/// preprocessor.
2638IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002639 assert(PP && "Forgot to set Preprocessor ?");
2640 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002641}
2642
Douglas Gregor025452f2009-04-17 00:04:06 +00002643/// \brief Record that the given ID maps to the given switch-case
2644/// statement.
2645void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2646 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2647 SwitchCaseStmts[ID] = SC;
2648}
2649
2650/// \brief Retrieve the switch-case statement with the given ID.
2651SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2652 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2653 return SwitchCaseStmts[ID];
2654}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002655
2656/// \brief Record that the given label statement has been
2657/// deserialized and has the given ID.
2658void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00002659 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002660 "Deserialized label twice");
2661 LabelStmts[ID] = S;
2662
2663 // If we've already seen any goto statements that point to this
2664 // label, resolve them now.
2665 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2666 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2667 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2668 Goto->second->setLabel(S);
2669 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002670
2671 // If we've already seen any address-label statements that point to
2672 // this label, resolve them now.
2673 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00002674 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002675 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002676 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002677 AddrLabel != AddrLabels.second; ++AddrLabel)
2678 AddrLabel->second->setLabel(S);
2679 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002680}
2681
2682/// \brief Set the label of the given statement to the label
2683/// identified by ID.
2684///
2685/// Depending on the order in which the label and other statements
2686/// referencing that label occur, this operation may complete
2687/// immediately (updating the statement) or it may queue the
2688/// statement to be back-patched later.
2689void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2690 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2691 if (Label != LabelStmts.end()) {
2692 // We've already seen this label, so set the label of the goto and
2693 // we're done.
2694 S->setLabel(Label->second);
2695 } else {
2696 // We haven't seen this label yet, so add this goto to the set of
2697 // unresolved goto statements.
2698 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2699 }
2700}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002701
2702/// \brief Set the label of the given expression to the label
2703/// identified by ID.
2704///
2705/// Depending on the order in which the label and other statements
2706/// referencing that label occur, this operation may complete
2707/// immediately (updating the statement) or it may queue the
2708/// statement to be back-patched later.
2709void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2710 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2711 if (Label != LabelStmts.end()) {
2712 // We've already seen this label, so set the label of the
2713 // label-address expression and we're done.
2714 S->setLabel(Label->second);
2715 } else {
2716 // We haven't seen this label yet, so add this label-address
2717 // expression to the set of unresolved label-address expressions.
2718 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2719 }
2720}
Douglas Gregord89275b2009-07-06 18:54:52 +00002721
2722
Mike Stump1eb44332009-09-09 15:08:12 +00002723PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00002724 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2725 Reader.CurrentlyLoadingTypeOrDecl = this;
2726}
2727
2728PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2729 if (!Parent) {
2730 // If any identifiers with corresponding top-level declarations have
2731 // been loaded, load those declarations now.
2732 while (!Reader.PendingIdentifierInfos.empty()) {
2733 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2734 Reader.PendingIdentifierInfos.front().DeclIDs,
2735 true);
2736 Reader.PendingIdentifierInfos.pop_front();
2737 }
2738 }
2739
Mike Stump1eb44332009-09-09 15:08:12 +00002740 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00002741}