blob: bed94037060646aef68882a1a2bd25aa769ce22c [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 Gregor6a5a23f2010-03-19 21:51:54 +000024#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000026#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000027#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000028#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000029#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000030#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000031#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000032#include "clang/Basic/Version.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000033#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000035#include "llvm/Support/MemoryBuffer.h"
John McCall833ca992009-10-29 08:12:44 +000036#include "llvm/Support/ErrorHandling.h"
Daniel Dunbard5b21972009-11-18 19:50:41 +000037#include "llvm/System/Path.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000038#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000039#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000040#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000041#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000042using namespace clang;
43
44//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000045// PCH reader validator implementation
46//===----------------------------------------------------------------------===//
47
48PCHReaderListener::~PCHReaderListener() {}
49
50bool
51PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
52 const LangOptions &PPLangOpts = PP.getLangOptions();
53#define PARSE_LANGOPT_BENIGN(Option)
54#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
55 if (PPLangOpts.Option != LangOpts.Option) { \
56 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
57 return true; \
58 }
59
60 PARSE_LANGOPT_BENIGN(Trigraphs);
61 PARSE_LANGOPT_BENIGN(BCPLComment);
62 PARSE_LANGOPT_BENIGN(DollarIdents);
63 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
64 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +000065 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000066 PARSE_LANGOPT_BENIGN(ImplicitInt);
67 PARSE_LANGOPT_BENIGN(Digraphs);
68 PARSE_LANGOPT_BENIGN(HexFloats);
69 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
70 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
71 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
72 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
73 PARSE_LANGOPT_BENIGN(CXXOperatorName);
74 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
75 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
76 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
Fariborz Jahanian412e7982010-02-09 19:31:38 +000077 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000078 PARSE_LANGOPT_BENIGN(PascalStrings);
79 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000080 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000081 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000082 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000083 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +000084 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000085 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
86 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
87 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump1eb44332009-09-09 15:08:12 +000088 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000089 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000090 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000091 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
92 PARSE_LANGOPT_BENIGN(EmitAllDecls);
93 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
94 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump1eb44332009-09-09 15:08:12 +000095 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000096 diag::warn_pch_heinous_extensions);
97 // FIXME: Most of the options below are benign if the macro wasn't
98 // used. Unfortunately, this means that a PCH compiled without
99 // optimization can't be used with optimization turned on, even
100 // though the only thing that changes is whether __OPTIMIZE__ was
101 // defined... but if __OPTIMIZE__ never showed up in the header, it
102 // doesn't matter. We could consider making this some special kind
103 // of check.
104 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
105 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
106 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
107 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
108 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
109 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
110 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
111 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsona6fda122009-11-05 20:14:16 +0000112 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000113 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000114 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000115 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
116 return true;
117 }
118 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000119 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
120 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000121 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000122 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stump9c276ae2009-12-12 01:27:46 +0000123 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000124 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +0000125#undef PARSE_LANGOPT_IMPORTANT
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000126#undef PARSE_LANGOPT_BENIGN
127
128 return false;
129}
130
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000131bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
132 if (Triple == PP.getTargetInfo().getTriple().str())
133 return false;
134
135 Reader.Diag(diag::warn_pch_target_triple)
136 << Triple << PP.getTargetInfo().getTriple().str();
137 return true;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000138}
139
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000140bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000141 FileID PCHBufferID,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000142 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000143 std::string &SuggestedPredefines) {
Daniel Dunbarc7162932009-11-11 23:58:53 +0000144 // We are in the context of an implicit include, so the predefines buffer will
145 // have a #include entry for the PCH file itself (as normalized by the
146 // preprocessor initialization). Find it and skip over it in the checking
147 // below.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000148 llvm::SmallString<256> PCHInclude;
149 PCHInclude += "#include \"";
Daniel Dunbarc7162932009-11-11 23:58:53 +0000150 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000151 PCHInclude += "\"\n";
152 std::pair<llvm::StringRef,llvm::StringRef> Split =
153 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
154 llvm::StringRef Left = Split.first, Right = Split.second;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000155 if (Left == PP.getPredefines()) {
156 Error("Missing PCH include entry!");
157 return true;
158 }
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000159
160 // If the predefines is equal to the joined left and right halves, we're done!
161 if (Left.size() + Right.size() == PCHPredef.size() &&
162 PCHPredef.startswith(Left) && PCHPredef.endswith(Right))
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000163 return false;
164
165 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000167 // The predefines buffers are different. Determine what the differences are,
168 // and whether they require us to reject the PCH file.
Daniel Dunbare6750492009-11-13 16:46:11 +0000169 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
170 PCHPredef.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
171
172 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
173 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
174 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000175
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000176 // Sort both sets of predefined buffer lines, since we allow some extra
177 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000178 std::sort(CmdLineLines.begin(), CmdLineLines.end());
179 std::sort(PCHLines.begin(), PCHLines.end());
180
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000181 // Determine which predefines that were used to build the PCH file are missing
182 // from the command line.
183 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000184 std::set_difference(PCHLines.begin(), PCHLines.end(),
185 CmdLineLines.begin(), CmdLineLines.end(),
186 std::back_inserter(MissingPredefines));
187
188 bool MissingDefines = false;
189 bool ConflictingDefines = false;
190 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000191 llvm::StringRef Missing = MissingPredefines[I];
192 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000193 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
194 return true;
195 }
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000197 // This is a macro definition. Determine the name of the macro we're
198 // defining.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000199 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000200 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000201 = Missing.find_first_of("( \n\r", StartOfMacroName);
202 assert(EndOfMacroName != std::string::npos &&
203 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000204 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000205
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000206 // Determine whether this macro was given a different definition on the
207 // command line.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000208 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000209 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbare6750492009-11-13 16:46:11 +0000210 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000211 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
212 MacroDefStart);
213 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000214 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000215 // Different macro; we're done.
216 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000217 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000218 }
Mike Stump1eb44332009-09-09 15:08:12 +0000219
220 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000221 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000222 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000223 (*ConflictPos)[MacroDefLen] != '(')
224 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000226 // We found a conflicting macro definition.
227 break;
228 }
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000230 if (ConflictPos != CmdLineLines.end()) {
231 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
232 << MacroName;
233
234 // Show the definition of this macro within the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000235 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
236 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
237 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
238 .getFileLocWithOffset(Offset);
239 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000240
241 ConflictingDefines = true;
242 continue;
243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000245 // If the macro doesn't conflict, then we'll just pick up the macro
246 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000247 if (ConflictingDefines)
248 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000250 if (!MissingDefines) {
251 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
252 MissingDefines = true;
253 }
254
255 // Show the definition of this macro within the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000256 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
257 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
258 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000259 .getFileLocWithOffset(Offset);
260 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
261 }
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000263 if (ConflictingDefines)
264 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000266 // Determine what predefines were introduced based on command-line
267 // parameters that were not present when building the PCH
268 // file. Extra #defines are okay, so long as the identifiers being
269 // defined were not used within the precompiled header.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000270 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000271 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
272 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000273 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000274 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000275 llvm::StringRef &Extra = ExtraPredefines[I];
276 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000277 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
278 return true;
279 }
280
281 // This is an extra macro definition. Determine the name of the
282 // macro we're defining.
283 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000284 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000285 = Extra.find_first_of("( \n\r", StartOfMacroName);
286 assert(EndOfMacroName != std::string::npos &&
287 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000288 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000289
290 // Check whether this name was used somewhere in the PCH file. If
291 // so, defining it as a macro could change behavior, so we reject
292 // the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000293 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar4fda42e2009-11-11 00:52:00 +0000294 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000295 return true;
296 }
297
298 // Add this definition to the suggested predefines buffer.
299 SuggestedPredefines += Extra;
300 SuggestedPredefines += '\n';
301 }
302
303 // If we get here, it's because the predefines buffer had compatible
304 // contents. Accept the PCH file.
305 return false;
306}
307
Douglas Gregor12fab312010-03-16 16:35:32 +0000308void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
309 unsigned ID) {
310 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
311 ++NumHeaderInfos;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000312}
313
314void PCHValidator::ReadCounter(unsigned Value) {
315 PP.setCounterValue(Value);
316}
317
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000318//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000319// PCH reader implementation
320//===----------------------------------------------------------------------===//
321
Mike Stump1eb44332009-09-09 15:08:12 +0000322PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
323 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000324 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
325 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregor52e71082009-10-16 18:18:30 +0000326 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000327 IdentifierTableData(0), IdentifierLookupTable(0),
328 IdentifierOffsets(0),
329 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
330 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000331 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +0000332 NumPreallocatedPreprocessingEntities(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000333 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000334 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000335 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000336 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000337 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000338 RelocatablePCH = false;
339}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000340
341PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000342 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000343 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregor52e71082009-10-16 18:18:30 +0000344 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000345 IdentifierTableData(0), IdentifierLookupTable(0),
346 IdentifierOffsets(0),
347 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
348 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000349 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +0000350 NumPreallocatedPreprocessingEntities(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000351 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000352 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000353 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000354 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000355 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000356 RelocatablePCH = false;
357}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000358
359PCHReader::~PCHReader() {}
360
Chris Lattnerda930612009-04-27 05:58:23 +0000361Expr *PCHReader::ReadDeclExpr() {
362 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
363}
364
365Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor61d60ee2009-10-17 00:13:19 +0000366 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000367}
368
369
Douglas Gregor668c1a42009-04-21 22:25:48 +0000370namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000371class PCHMethodPoolLookupTrait {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000372 PCHReader &Reader;
373
374public:
375 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
376
377 typedef Selector external_key_type;
378 typedef external_key_type internal_key_type;
379
380 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000382 static bool EqualKey(const internal_key_type& a,
383 const internal_key_type& b) {
384 return a == b;
385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000387 static unsigned ComputeHash(Selector Sel) {
388 unsigned N = Sel.getNumArgs();
389 if (N == 0)
390 ++N;
391 unsigned R = 5381;
392 for (unsigned I = 0; I != N; ++I)
393 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000394 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000395 return R;
396 }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000398 // This hopefully will just get inlined and removed by the optimizer.
399 static const internal_key_type&
400 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000402 static std::pair<unsigned, unsigned>
403 ReadKeyDataLength(const unsigned char*& d) {
404 using namespace clang::io;
405 unsigned KeyLen = ReadUnalignedLE16(d);
406 unsigned DataLen = ReadUnalignedLE16(d);
407 return std::make_pair(KeyLen, DataLen);
408 }
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Douglas Gregor83941df2009-04-25 17:48:32 +0000410 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000411 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000412 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000413 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000414 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000415 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
416 if (N == 0)
417 return SelTable.getNullarySelector(FirstII);
418 else if (N == 1)
419 return SelTable.getUnarySelector(FirstII);
420
421 llvm::SmallVector<IdentifierInfo *, 16> Args;
422 Args.push_back(FirstII);
423 for (unsigned I = 1; I != N; ++I)
424 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
425
Douglas Gregor75fdb232009-05-22 22:45:36 +0000426 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000427 }
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000429 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
430 using namespace clang::io;
431 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
432 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
433
434 data_type Result;
435
436 // Load instance methods
437 ObjCMethodList *Prev = 0;
438 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000439 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000440 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
441 if (!Result.first.Method) {
442 // This is the first method, which is the easy case.
443 Result.first.Method = Method;
444 Prev = &Result.first;
445 continue;
446 }
447
Ted Kremenek298ed872010-02-11 00:53:01 +0000448 ObjCMethodList *Mem =
449 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
450 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000451 Prev = Prev->Next;
452 }
453
454 // Load factory methods
455 Prev = 0;
456 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000457 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000458 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
459 if (!Result.second.Method) {
460 // This is the first method, which is the easy case.
461 Result.second.Method = Method;
462 Prev = &Result.second;
463 continue;
464 }
465
Ted Kremenek298ed872010-02-11 00:53:01 +0000466 ObjCMethodList *Mem =
467 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
468 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000469 Prev = Prev->Next;
470 }
471
472 return Result;
473 }
474};
Mike Stump1eb44332009-09-09 15:08:12 +0000475
476} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000477
478/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000479typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000480 PCHMethodPoolLookupTable;
481
482namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000483class PCHIdentifierLookupTrait {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000484 PCHReader &Reader;
485
486 // If we know the IdentifierInfo in advance, it is here and we will
487 // not build a new one. Used when deserializing information about an
488 // identifier that was constructed before the PCH file was read.
489 IdentifierInfo *KnownII;
490
491public:
492 typedef IdentifierInfo * data_type;
493
494 typedef const std::pair<const char*, unsigned> external_key_type;
495
496 typedef external_key_type internal_key_type;
497
Mike Stump1eb44332009-09-09 15:08:12 +0000498 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000499 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregor668c1a42009-04-21 22:25:48 +0000501 static bool EqualKey(const internal_key_type& a,
502 const internal_key_type& b) {
503 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
504 : false;
505 }
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregor668c1a42009-04-21 22:25:48 +0000507 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000508 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000509 }
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Douglas Gregor668c1a42009-04-21 22:25:48 +0000511 // This hopefully will just get inlined and removed by the optimizer.
512 static const internal_key_type&
513 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Douglas Gregor668c1a42009-04-21 22:25:48 +0000515 static std::pair<unsigned, unsigned>
516 ReadKeyDataLength(const unsigned char*& d) {
517 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000518 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000519 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000520 return std::make_pair(KeyLen, DataLen);
521 }
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Douglas Gregor668c1a42009-04-21 22:25:48 +0000523 static std::pair<const char*, unsigned>
524 ReadKey(const unsigned char* d, unsigned n) {
525 assert(n >= 2 && d[n-1] == '\0');
526 return std::make_pair((const char*) d, n-1);
527 }
Mike Stump1eb44332009-09-09 15:08:12 +0000528
529 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000530 const unsigned char* d,
531 unsigned DataLen) {
532 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000533 pch::IdentID ID = ReadUnalignedLE32(d);
534 bool IsInteresting = ID & 0x01;
535
536 // Wipe out the "is interesting" bit.
537 ID = ID >> 1;
538
539 if (!IsInteresting) {
540 // For unintersting identifiers, just build the IdentifierInfo
541 // and associate it with the persistent ID.
542 IdentifierInfo *II = KnownII;
543 if (!II)
544 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
545 k.first, k.first + k.second);
546 Reader.SetIdentifierInfo(ID, II);
547 return II;
548 }
549
Douglas Gregor5998da52009-04-28 21:32:13 +0000550 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000551 bool CPlusPlusOperatorKeyword = Bits & 0x01;
552 Bits >>= 1;
553 bool Poisoned = Bits & 0x01;
554 Bits >>= 1;
555 bool ExtensionToken = Bits & 0x01;
556 Bits >>= 1;
557 bool hasMacroDefinition = Bits & 0x01;
558 Bits >>= 1;
559 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
560 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Douglas Gregor2deaea32009-04-22 18:49:13 +0000562 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000563 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000564
565 // Build the IdentifierInfo itself and link the identifier ID with
566 // the new IdentifierInfo.
567 IdentifierInfo *II = KnownII;
568 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000569 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
570 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000571 Reader.SetIdentifierInfo(ID, II);
572
Douglas Gregor2deaea32009-04-22 18:49:13 +0000573 // Set or check the various bits in the IdentifierInfo structure.
574 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000575 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000576 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000577 "Incorrect extension token flag");
578 (void)ExtensionToken;
579 II->setIsPoisoned(Poisoned);
580 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
581 "Incorrect C++ operator keyword flag");
582 (void)CPlusPlusOperatorKeyword;
583
Douglas Gregor37e26842009-04-21 23:56:24 +0000584 // If this identifier is a macro, deserialize the macro
585 // definition.
586 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000587 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000588 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000589 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000590 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000591
592 // Read all of the declarations visible at global scope with this
593 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000594 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000595 if (DataLen > 0) {
596 llvm::SmallVector<uint32_t, 4> DeclIDs;
597 for (; DataLen > 0; DataLen -= 4)
598 DeclIDs.push_back(ReadUnalignedLE32(d));
599 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000600 }
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Douglas Gregor668c1a42009-04-21 22:25:48 +0000602 return II;
603 }
604};
Mike Stump1eb44332009-09-09 15:08:12 +0000605
606} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000607
608/// \brief The on-disk hash table used to contain information about
609/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000610typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000611 PCHIdentifierLookupTable;
612
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000613void PCHReader::Error(const char *Msg) {
614 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000615}
616
Douglas Gregore1d918e2009-04-10 23:10:45 +0000617/// \brief Check the contents of the predefines buffer against the
618/// contents of the predefines buffer used to build the PCH file.
619///
620/// The contents of the two predefines buffers should be the same. If
621/// not, then some command-line option changed the preprocessor state
622/// and we must reject the PCH file.
623///
624/// \param PCHPredef The start of the predefines buffer in the PCH
625/// file.
626///
627/// \param PCHPredefLen The length of the predefines buffer in the PCH
628/// file.
629///
630/// \param PCHBufferID The FileID for the PCH predefines buffer.
631///
632/// \returns true if there was a mismatch (in which case the PCH file
633/// should be ignored), or false otherwise.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000634bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000635 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000636 if (Listener)
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000637 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000638 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000639 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000640 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000641}
642
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000643//===----------------------------------------------------------------------===//
644// Source Manager Deserialization
645//===----------------------------------------------------------------------===//
646
Douglas Gregorbd945002009-04-13 16:31:14 +0000647/// \brief Read the line table in the source manager block.
648/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000649bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000650 unsigned Idx = 0;
651 LineTableInfo &LineTable = SourceMgr.getLineTable();
652
653 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000654 std::map<int, int> FileIDs;
655 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000656 // Extract the file name
657 unsigned FilenameLen = Record[Idx++];
658 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
659 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000660 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000661 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000662 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000663 }
664
665 // Parse the line entries
666 std::vector<LineEntry> Entries;
667 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000668 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000669
670 // Extract the line entries
671 unsigned NumEntries = Record[Idx++];
672 Entries.clear();
673 Entries.reserve(NumEntries);
674 for (unsigned I = 0; I != NumEntries; ++I) {
675 unsigned FileOffset = Record[Idx++];
676 unsigned LineNo = Record[Idx++];
677 int FilenameID = Record[Idx++];
Mike Stump1eb44332009-09-09 15:08:12 +0000678 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000679 = (SrcMgr::CharacteristicKind)Record[Idx++];
680 unsigned IncludeOffset = Record[Idx++];
681 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
682 FileKind, IncludeOffset));
683 }
684 LineTable.AddEntry(FID, Entries);
685 }
686
687 return false;
688}
689
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000690namespace {
691
Benjamin Kramerbd218282009-11-28 10:07:24 +0000692class PCHStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000693public:
694 const bool hasStat;
695 const ino_t ino;
696 const dev_t dev;
697 const mode_t mode;
698 const time_t mtime;
699 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000701 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000702 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
703
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000704 PCHStatData()
705 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
706};
707
Benjamin Kramerbd218282009-11-28 10:07:24 +0000708class PCHStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000709 public:
710 typedef const char *external_key_type;
711 typedef const char *internal_key_type;
712
713 typedef PCHStatData data_type;
714
715 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000716 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000717 }
718
719 static internal_key_type GetInternalKey(const char *path) { return path; }
720
721 static bool EqualKey(internal_key_type a, internal_key_type b) {
722 return strcmp(a, b) == 0;
723 }
724
725 static std::pair<unsigned, unsigned>
726 ReadKeyDataLength(const unsigned char*& d) {
727 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
728 unsigned DataLen = (unsigned) *d++;
729 return std::make_pair(KeyLen + 1, DataLen);
730 }
731
732 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
733 return (const char *)d;
734 }
735
736 static data_type ReadData(const internal_key_type, const unsigned char *d,
737 unsigned /*DataLen*/) {
738 using namespace clang::io;
739
740 if (*d++ == 1)
741 return data_type();
742
743 ino_t ino = (ino_t) ReadUnalignedLE32(d);
744 dev_t dev = (dev_t) ReadUnalignedLE32(d);
745 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000746 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000747 off_t size = (off_t) ReadUnalignedLE64(d);
748 return data_type(ino, dev, mode, mtime, size);
749 }
750};
751
752/// \brief stat() cache for precompiled headers.
753///
754/// This cache is very similar to the stat cache used by pretokenized
755/// headers.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000756class PCHStatCache : public StatSysCallCache {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000757 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
758 CacheTy *Cache;
759
760 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000761public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000762 PCHStatCache(const unsigned char *Buckets,
763 const unsigned char *Base,
764 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000765 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000766 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
767 Cache = CacheTy::Create(Buckets, Base);
768 }
769
770 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000772 int stat(const char *path, struct stat *buf) {
773 // Do the lookup for the file's data in the PCH file.
774 CacheTy::iterator I = Cache->find(path);
775
776 // If we don't get a hit in the PCH file just forward to 'stat'.
777 if (I == Cache->end()) {
778 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000779 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000780 }
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000782 ++NumStatHits;
783 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000785 if (!Data.hasStat)
786 return 1;
787
788 buf->st_ino = Data.ino;
789 buf->st_dev = Data.dev;
790 buf->st_mtime = Data.mtime;
791 buf->st_mode = Data.mode;
792 buf->st_size = Data.size;
793 return 0;
794 }
795};
796} // end anonymous namespace
797
798
Douglas Gregor14f79002009-04-10 03:52:48 +0000799/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000800PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000801 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000802
803 // Set the source-location entry cursor to the current position in
804 // the stream. This cursor will be used to read the contents of the
805 // source manager block initially, and then lazily read
806 // source-location entries as needed.
807 SLocEntryCursor = Stream;
808
809 // The stream itself is going to skip over the source manager block.
810 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000811 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000812 return Failure;
813 }
814
815 // Enter the source manager block.
816 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000817 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000818 return Failure;
819 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000820
Douglas Gregor14f79002009-04-10 03:52:48 +0000821 RecordData Record;
822 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000823 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000824 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000825 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000826 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000827 return Failure;
828 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000829 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000830 }
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Douglas Gregor14f79002009-04-10 03:52:48 +0000832 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
833 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000834 SLocEntryCursor.ReadSubBlockID();
835 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000836 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000837 return Failure;
838 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000839 continue;
840 }
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Douglas Gregor14f79002009-04-10 03:52:48 +0000842 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000843 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000844 continue;
845 }
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Douglas Gregor14f79002009-04-10 03:52:48 +0000847 // Read a record.
848 const char *BlobStart;
849 unsigned BlobLen;
850 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000851 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000852 default: // Default behavior: ignore.
853 break;
854
Chris Lattner2c78b872009-04-14 23:22:57 +0000855 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000856 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000857 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000858 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000859
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000860 case pch::SM_SLOC_FILE_ENTRY:
861 case pch::SM_SLOC_BUFFER_ENTRY:
862 case pch::SM_SLOC_INSTANTIATION_ENTRY:
863 // Once we hit one of the source location entries, we're done.
864 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000865 }
866 }
867}
868
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000869/// \brief Read in the source location entry with the given ID.
870PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
871 if (ID == 0)
872 return Success;
873
874 if (ID > TotalNumSLocEntries) {
875 Error("source location entry ID out-of-range for PCH file");
876 return Failure;
877 }
878
879 ++NumSLocEntriesRead;
880 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
881 unsigned Code = SLocEntryCursor.ReadCode();
882 if (Code == llvm::bitc::END_BLOCK ||
883 Code == llvm::bitc::ENTER_SUBBLOCK ||
884 Code == llvm::bitc::DEFINE_ABBREV) {
885 Error("incorrectly-formatted source location entry in PCH file");
886 return Failure;
887 }
888
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000889 RecordData Record;
890 const char *BlobStart;
891 unsigned BlobLen;
892 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
893 default:
894 Error("incorrectly-formatted source location entry in PCH file");
895 return Failure;
896
897 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000898 std::string Filename(BlobStart, BlobStart + BlobLen);
899 MaybeAddSystemRootToFilename(Filename);
900 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000901 if (File == 0) {
902 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000903 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000904 ErrorStr += "' referenced by PCH file";
905 Error(ErrorStr.c_str());
906 return Failure;
907 }
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Douglas Gregor2d52be52010-03-21 22:49:54 +0000909 if (Record.size() < 10) {
Ted Kremenek1857f622010-03-18 21:23:05 +0000910 Error("source location entry is incorrect");
911 return Failure;
912 }
913
Douglas Gregor9f692a02010-04-09 15:54:22 +0000914 if ((off_t)Record[4] != File->getSize()
915#if !defined(LLVM_ON_WIN32)
916 // In our regression testing, the Windows file system seems to
917 // have inconsistent modification times that sometimes
918 // erroneously trigger this error-handling path.
919 || (time_t)Record[5] != File->getModificationTime()
920#endif
921 ) {
Douglas Gregor2d52be52010-03-21 22:49:54 +0000922 Diag(diag::err_fe_pch_file_modified)
923 << Filename;
924 return Failure;
925 }
926
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000927 FileID FID = SourceMgr.createFileID(File,
928 SourceLocation::getFromRawEncoding(Record[1]),
929 (SrcMgr::CharacteristicKind)Record[2],
930 ID, Record[0]);
931 if (Record[3])
932 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
933 .setHasLineDirectives();
934
Douglas Gregor12fab312010-03-16 16:35:32 +0000935 // Reconstruct header-search information for this file.
936 HeaderFileInfo HFI;
Douglas Gregor2d52be52010-03-21 22:49:54 +0000937 HFI.isImport = Record[6];
938 HFI.DirInfo = Record[7];
939 HFI.NumIncludes = Record[8];
940 HFI.ControllingMacroID = Record[9];
Douglas Gregor12fab312010-03-16 16:35:32 +0000941 if (Listener)
942 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000943 break;
944 }
945
946 case pch::SM_SLOC_BUFFER_ENTRY: {
947 const char *Name = BlobStart;
948 unsigned Offset = Record[0];
949 unsigned Code = SLocEntryCursor.ReadCode();
950 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000951 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000952 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000953
954 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
955 Error("PCH record has invalid code");
956 return Failure;
957 }
958
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000959 llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +0000960 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
961 Name);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000962 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Douglas Gregor92b059e2009-04-28 20:33:11 +0000964 if (strcmp(Name, "<built-in>") == 0) {
965 PCHPredefinesBufferID = BufferID;
966 PCHPredefines = BlobStart;
967 PCHPredefinesLen = BlobLen - 1;
968 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000969
970 break;
971 }
972
973 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +0000974 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000975 = SourceLocation::getFromRawEncoding(Record[1]);
976 SourceMgr.createInstantiationLoc(SpellingLoc,
977 SourceLocation::getFromRawEncoding(Record[2]),
978 SourceLocation::getFromRawEncoding(Record[3]),
979 Record[4],
980 ID,
981 Record[0]);
982 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000983 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000984 }
985
986 return Success;
987}
988
Chris Lattner6367f6d2009-04-27 01:05:14 +0000989/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
990/// specified cursor. Read the abbreviations that are at the top of the block
991/// and then leave the cursor pointing into the block.
992bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
993 unsigned BlockID) {
994 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000995 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000996 return Failure;
997 }
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner6367f6d2009-04-27 01:05:14 +0000999 while (true) {
1000 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chris Lattner6367f6d2009-04-27 01:05:14 +00001002 // We expect all abbrevs to be at the start of the block.
1003 if (Code != llvm::bitc::DEFINE_ABBREV)
1004 return false;
1005 Cursor.ReadAbbrevRecord();
1006 }
1007}
1008
Douglas Gregor37e26842009-04-21 23:56:24 +00001009void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001010 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Douglas Gregor37e26842009-04-21 23:56:24 +00001012 // Keep track of where we are in the stream, then jump back there
1013 // after reading this macro.
1014 SavedStreamPosition SavedPosition(Stream);
1015
1016 Stream.JumpToBit(Offset);
1017 RecordData Record;
1018 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1019 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Douglas Gregor37e26842009-04-21 23:56:24 +00001021 while (true) {
1022 unsigned Code = Stream.ReadCode();
1023 switch (Code) {
1024 case llvm::bitc::END_BLOCK:
1025 return;
1026
1027 case llvm::bitc::ENTER_SUBBLOCK:
1028 // No known subblocks, always skip them.
1029 Stream.ReadSubBlockID();
1030 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001031 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001032 return;
1033 }
1034 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Douglas Gregor37e26842009-04-21 23:56:24 +00001036 case llvm::bitc::DEFINE_ABBREV:
1037 Stream.ReadAbbrevRecord();
1038 continue;
1039 default: break;
1040 }
1041
1042 // Read a record.
1043 Record.clear();
1044 pch::PreprocessorRecordTypes RecType =
1045 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1046 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001047 case pch::PP_MACRO_OBJECT_LIKE:
1048 case pch::PP_MACRO_FUNCTION_LIKE: {
1049 // If we already have a macro, that means that we've hit the end
1050 // of the definition of the macro we were looking for. We're
1051 // done.
1052 if (Macro)
1053 return;
1054
1055 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1056 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001057 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001058 return;
1059 }
1060 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1061 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001063 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001064 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001066 unsigned NextIndex = 3;
Douglas Gregor37e26842009-04-21 23:56:24 +00001067 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1068 // Decode function-like macro info.
1069 bool isC99VarArgs = Record[3];
1070 bool isGNUVarArgs = Record[4];
1071 MacroArgs.clear();
1072 unsigned NumArgs = Record[5];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001073 NextIndex = 6 + NumArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001074 for (unsigned i = 0; i != NumArgs; ++i)
1075 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1076
1077 // Install function-like macro info.
1078 MI->setIsFunctionLike();
1079 if (isC99VarArgs) MI->setIsC99Varargs();
1080 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001081 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001082 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001083 }
1084
1085 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001086 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001087
1088 // Remember that we saw this macro last so that we add the tokens that
1089 // form its body to it.
1090 Macro = MI;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001091
1092 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1093 // We have a macro definition. Load it now.
1094 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1095 getMacroDefinition(Record[NextIndex]));
1096 }
1097
Douglas Gregor37e26842009-04-21 23:56:24 +00001098 ++NumMacrosRead;
1099 break;
1100 }
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Douglas Gregor37e26842009-04-21 23:56:24 +00001102 case pch::PP_TOKEN: {
1103 // If we see a TOKEN before a PP_MACRO_*, then the file is
1104 // erroneous, just pretend we didn't see this.
1105 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Douglas Gregor37e26842009-04-21 23:56:24 +00001107 Token Tok;
1108 Tok.startToken();
1109 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1110 Tok.setLength(Record[1]);
1111 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1112 Tok.setIdentifierInfo(II);
1113 Tok.setKind((tok::TokenKind)Record[3]);
1114 Tok.setFlag((Token::TokenFlags)Record[4]);
1115 Macro->AddTokenToBody(Tok);
1116 break;
1117 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001118
1119 case pch::PP_MACRO_INSTANTIATION: {
1120 // If we already have a macro, that means that we've hit the end
1121 // of the definition of the macro we were looking for. We're
1122 // done.
1123 if (Macro)
1124 return;
1125
1126 if (!PP->getPreprocessingRecord()) {
1127 Error("missing preprocessing record in PCH file");
1128 return;
1129 }
1130
1131 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1132 if (PPRec.getPreprocessedEntity(Record[0]))
1133 return;
1134
1135 MacroInstantiation *MI
1136 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1137 SourceRange(
1138 SourceLocation::getFromRawEncoding(Record[1]),
1139 SourceLocation::getFromRawEncoding(Record[2])),
1140 getMacroDefinition(Record[4]));
1141 PPRec.SetPreallocatedEntity(Record[0], MI);
1142 return;
1143 }
1144
1145 case pch::PP_MACRO_DEFINITION: {
1146 // If we already have a macro, that means that we've hit the end
1147 // of the definition of the macro we were looking for. We're
1148 // done.
1149 if (Macro)
1150 return;
1151
1152 if (!PP->getPreprocessingRecord()) {
1153 Error("missing preprocessing record in PCH file");
1154 return;
1155 }
1156
1157 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1158 if (PPRec.getPreprocessedEntity(Record[0]))
1159 return;
1160
1161 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1162 Error("out-of-bounds macro definition record");
1163 return;
1164 }
1165
1166 MacroDefinition *MD
1167 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1168 SourceLocation::getFromRawEncoding(Record[5]),
1169 SourceRange(
1170 SourceLocation::getFromRawEncoding(Record[2]),
1171 SourceLocation::getFromRawEncoding(Record[3])));
1172 PPRec.SetPreallocatedEntity(Record[0], MD);
1173 MacroDefinitionsLoaded[Record[1]] = MD;
1174 return;
1175 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001176 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001177 }
1178}
1179
Douglas Gregor88a35862010-01-04 19:18:44 +00001180void PCHReader::ReadDefinedMacros() {
1181 // If there was no preprocessor block, do nothing.
1182 if (!MacroCursor.getBitStreamReader())
1183 return;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001184
Douglas Gregor88a35862010-01-04 19:18:44 +00001185 llvm::BitstreamCursor Cursor = MacroCursor;
1186 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1187 Error("malformed preprocessor block record in PCH file");
1188 return;
1189 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001190
Douglas Gregor88a35862010-01-04 19:18:44 +00001191 RecordData Record;
1192 while (true) {
1193 unsigned Code = Cursor.ReadCode();
1194 if (Code == llvm::bitc::END_BLOCK) {
1195 if (Cursor.ReadBlockEnd())
1196 Error("error at end of preprocessor block in PCH file");
1197 return;
1198 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001199
Douglas Gregor88a35862010-01-04 19:18:44 +00001200 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1201 // No known subblocks, always skip them.
1202 Cursor.ReadSubBlockID();
1203 if (Cursor.SkipBlock()) {
1204 Error("malformed block record in PCH file");
1205 return;
1206 }
1207 continue;
1208 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001209
Douglas Gregor88a35862010-01-04 19:18:44 +00001210 if (Code == llvm::bitc::DEFINE_ABBREV) {
1211 Cursor.ReadAbbrevRecord();
1212 continue;
1213 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001214
Douglas Gregor88a35862010-01-04 19:18:44 +00001215 // Read a record.
1216 const char *BlobStart;
1217 unsigned BlobLen;
1218 Record.clear();
1219 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1220 default: // Default behavior: ignore.
1221 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001222
Douglas Gregor88a35862010-01-04 19:18:44 +00001223 case pch::PP_MACRO_OBJECT_LIKE:
1224 case pch::PP_MACRO_FUNCTION_LIKE:
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001225 DecodeIdentifierInfo(Record[0]);
Douglas Gregor88a35862010-01-04 19:18:44 +00001226 break;
1227
1228 case pch::PP_TOKEN:
1229 // Ignore tokens.
1230 break;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001231
1232 case pch::PP_MACRO_INSTANTIATION:
1233 case pch::PP_MACRO_DEFINITION:
1234 // Read the macro record.
1235 ReadMacroRecord(Cursor.GetCurrentBitNo());
1236 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001237 }
1238 }
1239}
1240
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001241MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1242 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1243 return 0;
1244
1245 if (!MacroDefinitionsLoaded[ID])
1246 ReadMacroRecord(MacroDefinitionOffsets[ID]);
1247
1248 return MacroDefinitionsLoaded[ID];
1249}
1250
Douglas Gregore650c8c2009-07-07 00:12:59 +00001251/// \brief If we are loading a relocatable PCH file, and the filename is
1252/// not an absolute path, add the system root to the beginning of the file
1253/// name.
1254void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1255 // If this is not a relocatable PCH file, there's nothing to do.
1256 if (!RelocatablePCH)
1257 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Daniel Dunbard5b21972009-11-18 19:50:41 +00001259 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001260 return;
1261
Douglas Gregore650c8c2009-07-07 00:12:59 +00001262 if (isysroot == 0) {
1263 // If no system root was given, default to '/'
1264 Filename.insert(Filename.begin(), '/');
1265 return;
1266 }
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Douglas Gregore650c8c2009-07-07 00:12:59 +00001268 unsigned Length = strlen(isysroot);
1269 if (isysroot[Length - 1] != '/')
1270 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Douglas Gregore650c8c2009-07-07 00:12:59 +00001272 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1273}
1274
Mike Stump1eb44332009-09-09 15:08:12 +00001275PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001276PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001277 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001278 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001279 return Failure;
1280 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001281
1282 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001283 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001284 while (!Stream.AtEndOfStream()) {
1285 unsigned Code = Stream.ReadCode();
1286 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001287 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001288 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001289 return Failure;
1290 }
Chris Lattner7356a312009-04-11 21:15:38 +00001291
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001292 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001293 }
1294
1295 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1296 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001297 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001298 // We lazily load the decls block, but we want to set up the
1299 // DeclsCursor cursor to point into it. Clone our current bitcode
1300 // cursor to it, enter the block and read the abbrevs in that block.
1301 // With the main cursor, we just skip over it.
1302 DeclsCursor = Stream;
1303 if (Stream.SkipBlock() || // Skip with the main cursor.
1304 // Read the abbrevs.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001305 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001306 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001307 return Failure;
1308 }
1309 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Chris Lattner7356a312009-04-11 21:15:38 +00001311 case pch::PREPROCESSOR_BLOCK_ID:
Douglas Gregor88a35862010-01-04 19:18:44 +00001312 MacroCursor = Stream;
1313 if (PP)
1314 PP->setExternalSource(this);
1315
Chris Lattner7356a312009-04-11 21:15:38 +00001316 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001317 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001318 return Failure;
1319 }
1320 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001321
Douglas Gregor14f79002009-04-10 03:52:48 +00001322 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001323 switch (ReadSourceManagerBlock()) {
1324 case Success:
1325 break;
1326
1327 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001328 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001329 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001330
1331 case IgnorePCH:
1332 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001333 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001334 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001335 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001336 continue;
1337 }
1338
1339 if (Code == llvm::bitc::DEFINE_ABBREV) {
1340 Stream.ReadAbbrevRecord();
1341 continue;
1342 }
1343
1344 // Read and process a record.
1345 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001346 const char *BlobStart = 0;
1347 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001348 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001349 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001350 default: // Default behavior: ignore.
1351 break;
1352
1353 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001354 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001355 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001356 return Failure;
1357 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001358 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001359 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001360 break;
1361
1362 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001363 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001364 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001365 return Failure;
1366 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001367 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001368 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001369 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001370
1371 case pch::LANGUAGE_OPTIONS:
1372 if (ParseLanguageOptions(Record))
1373 return IgnorePCH;
1374 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001375
Douglas Gregorab41e632009-04-27 22:23:34 +00001376 case pch::METADATA: {
1377 if (Record[0] != pch::VERSION_MAJOR) {
1378 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1379 : diag::warn_pch_version_too_new);
1380 return IgnorePCH;
1381 }
1382
Douglas Gregore650c8c2009-07-07 00:12:59 +00001383 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001384 if (Listener) {
1385 std::string TargetTriple(BlobStart, BlobLen);
1386 if (Listener->ReadTargetTriple(TargetTriple))
1387 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001388 }
1389 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001390 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001391
1392 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001393 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001394 if (Record[0]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001395 IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001396 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001397 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001398 (const unsigned char *)IdentifierTableData,
Douglas Gregor668c1a42009-04-21 22:25:48 +00001399 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001400 if (PP)
1401 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001402 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001403 break;
1404
1405 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001406 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001407 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001408 return Failure;
1409 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001410 IdentifierOffsets = (const uint32_t *)BlobStart;
1411 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001412 if (PP)
1413 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001414 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001415
1416 case pch::EXTERNAL_DEFINITIONS:
1417 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001418 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001419 return Failure;
1420 }
1421 ExternalDefinitions.swap(Record);
1422 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001423
Douglas Gregorad1de002009-04-18 05:55:16 +00001424 case pch::SPECIAL_TYPES:
1425 SpecialTypes.swap(Record);
1426 break;
1427
Douglas Gregor3e1af842009-04-17 22:13:46 +00001428 case pch::STATISTICS:
1429 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001430 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001431 TotalLexicalDeclContexts = Record[2];
1432 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001433 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001434
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001435 case pch::TENTATIVE_DEFINITIONS:
1436 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001437 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001438 return Failure;
1439 }
1440 TentativeDefinitions.swap(Record);
1441 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001442
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001443 case pch::UNUSED_STATIC_FUNCS:
1444 if (!UnusedStaticFuncs.empty()) {
1445 Error("duplicate UNUSED_STATIC_FUNCS record in PCH file");
1446 return Failure;
1447 }
1448 UnusedStaticFuncs.swap(Record);
1449 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001450
Douglas Gregor14c22f22009-04-22 22:18:58 +00001451 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1452 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001453 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001454 return Failure;
1455 }
1456 LocallyScopedExternalDecls.swap(Record);
1457 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001458
Douglas Gregor83941df2009-04-25 17:48:32 +00001459 case pch::SELECTOR_OFFSETS:
1460 SelectorOffsets = (const uint32_t *)BlobStart;
1461 TotalNumSelectors = Record[0];
1462 SelectorsLoaded.resize(TotalNumSelectors);
1463 break;
1464
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001465 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001466 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1467 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001468 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001469 = PCHMethodPoolLookupTable::Create(
1470 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001471 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001472 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001473 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001474 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001475
1476 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001477 if (!Record.empty() && Listener)
1478 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001479 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001480
1481 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001482 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001483 TotalNumSLocEntries = Record[0];
Douglas Gregor445e23e2009-10-05 21:07:28 +00001484 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001485 break;
1486
1487 case pch::SOURCE_LOCATION_PRELOADS:
1488 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1489 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1490 if (Result != Success)
1491 return Result;
1492 }
1493 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001494
Douglas Gregor52e71082009-10-16 18:18:30 +00001495 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001496 PCHStatCache *MyStatCache =
Douglas Gregor52e71082009-10-16 18:18:30 +00001497 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1498 (const unsigned char *)BlobStart,
1499 NumStatHits, NumStatMisses);
1500 FileMgr.addStatCache(MyStatCache);
1501 StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001502 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001503 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001504
Douglas Gregorb81c1702009-04-27 20:06:05 +00001505 case pch::EXT_VECTOR_DECLS:
1506 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001507 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001508 return Failure;
1509 }
1510 ExtVectorDecls.swap(Record);
1511 break;
1512
Douglas Gregorb64c1932009-05-12 01:31:05 +00001513 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001514 ActualOriginalFileName.assign(BlobStart, BlobLen);
1515 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001516 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001517 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Ted Kremenek5b4ec632010-01-22 20:59:36 +00001519 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek974be4d2010-02-12 23:31:14 +00001520 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek517e6762010-01-22 20:55:35 +00001521 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Ted Kremenek974be4d2010-02-12 23:31:14 +00001522 if (llvm::StringRef(CurBranch) != PCHBranch) {
Douglas Gregor445e23e2009-10-05 21:07:28 +00001523 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1524 return IgnorePCH;
1525 }
1526 break;
1527 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001528
1529 case pch::MACRO_DEFINITION_OFFSETS:
1530 MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1531 if (PP) {
1532 if (!PP->getPreprocessingRecord())
1533 PP->createPreprocessingRecord();
1534 PP->getPreprocessingRecord()->SetExternalSource(*this, Record[0]);
1535 } else {
1536 NumPreallocatedPreprocessingEntities = Record[0];
1537 }
1538
1539 MacroDefinitionsLoaded.resize(Record[1]);
1540 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001541 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001542 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001543 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001544 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001545}
1546
Douglas Gregore1d918e2009-04-10 23:10:45 +00001547PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001548 // Set the PCH file name.
1549 this->FileName = FileName;
1550
Douglas Gregor2cf26342009-04-09 22:27:44 +00001551 // Open the PCH file.
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001552 //
1553 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001554 std::string ErrStr;
Daniel Dunbar731ad8f2009-11-10 00:46:19 +00001555 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001556 if (!Buffer) {
1557 Error(ErrStr.c_str());
1558 return IgnorePCH;
1559 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001560
1561 // Initialize the stream
Mike Stump1eb44332009-09-09 15:08:12 +00001562 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001563 (const unsigned char *)Buffer->getBufferEnd());
1564 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001565
1566 // Sniff for the signature.
1567 if (Stream.Read(8) != 'C' ||
1568 Stream.Read(8) != 'P' ||
1569 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001570 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001571 Diag(diag::err_not_a_pch_file) << FileName;
1572 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001573 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001574
Douglas Gregor2cf26342009-04-09 22:27:44 +00001575 while (!Stream.AtEndOfStream()) {
1576 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Douglas Gregore1d918e2009-04-10 23:10:45 +00001578 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001579 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001580 return Failure;
1581 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001582
1583 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001584
Douglas Gregor2cf26342009-04-09 22:27:44 +00001585 // We only know the PCH subblock ID.
1586 switch (BlockID) {
1587 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001588 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001589 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001590 return Failure;
1591 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001592 break;
1593 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001594 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001595 case Success:
1596 break;
1597
1598 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001599 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001600
1601 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001602 // FIXME: We could consider reading through to the end of this
1603 // PCH block, skipping subblocks, to see if there are other
1604 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001605
1606 // Clear out any preallocated source location entries, so that
1607 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001608 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001609
1610 // Remove the stat cache.
Douglas Gregor52e71082009-10-16 18:18:30 +00001611 if (StatCache)
1612 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001613
Douglas Gregore1d918e2009-04-10 23:10:45 +00001614 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001615 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001616 break;
1617 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001618 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001619 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001620 return Failure;
1621 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001622 break;
1623 }
Mike Stump1eb44332009-09-09 15:08:12 +00001624 }
1625
Douglas Gregor92b059e2009-04-28 20:33:11 +00001626 // Check the predefines buffer.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +00001627 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregor92b059e2009-04-28 20:33:11 +00001628 PCHPredefinesBufferID))
1629 return IgnorePCH;
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001631 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001632 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001633 // PCH file is read, so there may be some identifiers that were
1634 // loaded into the IdentifierTable before we intercepted the
1635 // creation of identifiers. Iterate through the list of known
1636 // identifiers and determine whether we have to establish
1637 // preprocessor definitions or top-level identifier declaration
1638 // chains for those identifiers.
1639 //
1640 // We copy the IdentifierInfo pointers to a small vector first,
1641 // since de-serializing declarations or macro definitions can add
1642 // new entries into the identifier table, invalidating the
1643 // iterators.
1644 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1645 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1646 IdEnd = PP->getIdentifierTable().end();
1647 Id != IdEnd; ++Id)
1648 Identifiers.push_back(Id->second);
Mike Stump1eb44332009-09-09 15:08:12 +00001649 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001650 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1651 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1652 IdentifierInfo *II = Identifiers[I];
1653 // Look in the on-disk hash table for an entry for
1654 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbare013d682009-10-18 20:26:12 +00001655 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001656 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1657 if (Pos == IdTable->end())
1658 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001660 // Dereferencing the iterator has the effect of populating the
1661 // IdentifierInfo node with the various declarations it needs.
1662 (void)*Pos;
1663 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001664 }
1665
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001666 if (Context)
1667 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001668
Douglas Gregor668c1a42009-04-21 22:25:48 +00001669 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001670}
1671
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001672void PCHReader::setPreprocessor(Preprocessor &pp) {
1673 PP = &pp;
1674
1675 if (NumPreallocatedPreprocessingEntities) {
1676 if (!PP->getPreprocessingRecord())
1677 PP->createPreprocessingRecord();
1678 PP->getPreprocessingRecord()->SetExternalSource(*this,
1679 NumPreallocatedPreprocessingEntities);
1680 NumPreallocatedPreprocessingEntities = 0;
1681 }
1682}
1683
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001684void PCHReader::InitializeContext(ASTContext &Ctx) {
1685 Context = &Ctx;
1686 assert(Context && "Passed null context!");
1687
1688 assert(PP && "Forgot to set Preprocessor ?");
1689 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1690 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00001691 PP->setExternalSource(this);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001692
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001693 // Load the translation unit declaration
1694 ReadDeclRecord(DeclOffsets[0], 0);
1695
1696 // Load the special types.
1697 Context->setBuiltinVaListType(
1698 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1699 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1700 Context->setObjCIdType(GetType(Id));
1701 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1702 Context->setObjCSelType(GetType(Sel));
1703 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1704 Context->setObjCProtoType(GetType(Proto));
1705 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1706 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001707
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001708 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1709 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001710 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001711 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1712 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001713 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1714 QualType FileType = GetType(File);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001715 if (FileType.isNull()) {
1716 Error("FILE type is NULL");
1717 return;
1718 }
John McCall183700f2009-09-21 23:43:11 +00001719 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001720 Context->setFILEDecl(Typedef->getDecl());
1721 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001722 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001723 if (!Tag) {
1724 Error("Invalid FILE type in PCH file");
1725 return;
1726 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001727 Context->setFILEDecl(Tag->getDecl());
1728 }
1729 }
Mike Stump782fa302009-07-28 02:25:19 +00001730 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1731 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001732 if (Jmp_bufType.isNull()) {
1733 Error("jmp_bug type is NULL");
1734 return;
1735 }
John McCall183700f2009-09-21 23:43:11 +00001736 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001737 Context->setjmp_bufDecl(Typedef->getDecl());
1738 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001739 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001740 if (!Tag) {
1741 Error("Invalid jmp_bug type in PCH file");
1742 return;
1743 }
Mike Stump782fa302009-07-28 02:25:19 +00001744 Context->setjmp_bufDecl(Tag->getDecl());
1745 }
1746 }
1747 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1748 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001749 if (Sigjmp_bufType.isNull()) {
1750 Error("sigjmp_buf type is NULL");
1751 return;
1752 }
John McCall183700f2009-09-21 23:43:11 +00001753 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001754 Context->setsigjmp_bufDecl(Typedef->getDecl());
1755 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001756 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001757 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1758 Context->setsigjmp_bufDecl(Tag->getDecl());
1759 }
1760 }
Mike Stump1eb44332009-09-09 15:08:12 +00001761 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001762 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1763 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001764 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001765 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1766 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001767#if 0
1768 // FIXME. Accommodate for this in several PCH/Index tests
1769 if (unsigned ObjCSelRedef
1770 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00001771 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001772#endif
Mike Stumpadaaad32009-10-20 02:12:22 +00001773 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1774 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00001775 if (unsigned String
1776 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1777 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001778}
1779
Douglas Gregorb64c1932009-05-12 01:31:05 +00001780/// \brief Retrieve the name of the original source file name
1781/// directly from the PCH file, without actually loading the PCH
1782/// file.
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001783std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1784 Diagnostic &Diags) {
Douglas Gregorb64c1932009-05-12 01:31:05 +00001785 // Open the PCH file.
1786 std::string ErrStr;
1787 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1788 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1789 if (!Buffer) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001790 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001791 return std::string();
1792 }
1793
1794 // Initialize the stream
1795 llvm::BitstreamReader StreamFile;
1796 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00001797 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00001798 (const unsigned char *)Buffer->getBufferEnd());
1799 Stream.init(StreamFile);
1800
1801 // Sniff for the signature.
1802 if (Stream.Read(8) != 'C' ||
1803 Stream.Read(8) != 'P' ||
1804 Stream.Read(8) != 'C' ||
1805 Stream.Read(8) != 'H') {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001806 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001807 return std::string();
1808 }
1809
1810 RecordData Record;
1811 while (!Stream.AtEndOfStream()) {
1812 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Douglas Gregorb64c1932009-05-12 01:31:05 +00001814 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1815 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Douglas Gregorb64c1932009-05-12 01:31:05 +00001817 // We only know the PCH subblock ID.
1818 switch (BlockID) {
1819 case pch::PCH_BLOCK_ID:
1820 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001821 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001822 return std::string();
1823 }
1824 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Douglas Gregorb64c1932009-05-12 01:31:05 +00001826 default:
1827 if (Stream.SkipBlock()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001828 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001829 return std::string();
1830 }
1831 break;
1832 }
1833 continue;
1834 }
1835
1836 if (Code == llvm::bitc::END_BLOCK) {
1837 if (Stream.ReadBlockEnd()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001838 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001839 return std::string();
1840 }
1841 continue;
1842 }
1843
1844 if (Code == llvm::bitc::DEFINE_ABBREV) {
1845 Stream.ReadAbbrevRecord();
1846 continue;
1847 }
1848
1849 Record.clear();
1850 const char *BlobStart = 0;
1851 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001852 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00001853 == pch::ORIGINAL_FILE_NAME)
1854 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001855 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00001856
1857 return std::string();
1858}
1859
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001860/// \brief Parse the record that corresponds to a LangOptions data
1861/// structure.
1862///
1863/// This routine compares the language options used to generate the
1864/// PCH file against the language options set for the current
1865/// compilation. For each option, we classify differences between the
1866/// two compiler states as either "benign" or "important". Benign
1867/// differences don't matter, and we accept them without complaint
1868/// (and without modifying the language options). Differences between
1869/// the states for important options cause the PCH file to be
1870/// unusable, so we emit a warning and return true to indicate that
1871/// there was an error.
1872///
1873/// \returns true if the PCH file is unacceptable, false otherwise.
1874bool PCHReader::ParseLanguageOptions(
1875 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001876 if (Listener) {
1877 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001879 #define PARSE_LANGOPT(Option) \
1880 LangOpts.Option = Record[Idx]; \
1881 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001883 unsigned Idx = 0;
1884 PARSE_LANGOPT(Trigraphs);
1885 PARSE_LANGOPT(BCPLComment);
1886 PARSE_LANGOPT(DollarIdents);
1887 PARSE_LANGOPT(AsmPreprocessor);
1888 PARSE_LANGOPT(GNUMode);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +00001889 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001890 PARSE_LANGOPT(ImplicitInt);
1891 PARSE_LANGOPT(Digraphs);
1892 PARSE_LANGOPT(HexFloats);
1893 PARSE_LANGOPT(C99);
1894 PARSE_LANGOPT(Microsoft);
1895 PARSE_LANGOPT(CPlusPlus);
1896 PARSE_LANGOPT(CPlusPlus0x);
1897 PARSE_LANGOPT(CXXOperatorNames);
1898 PARSE_LANGOPT(ObjC1);
1899 PARSE_LANGOPT(ObjC2);
1900 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001901 PARSE_LANGOPT(ObjCNonFragileABI2);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001902 PARSE_LANGOPT(PascalStrings);
1903 PARSE_LANGOPT(WritableStrings);
1904 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001905 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001906 PARSE_LANGOPT(Exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +00001907 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001908 PARSE_LANGOPT(NeXTRuntime);
1909 PARSE_LANGOPT(Freestanding);
1910 PARSE_LANGOPT(NoBuiltin);
1911 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00001912 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001913 PARSE_LANGOPT(Blocks);
1914 PARSE_LANGOPT(EmitAllDecls);
1915 PARSE_LANGOPT(MathErrno);
1916 PARSE_LANGOPT(OverflowChecking);
1917 PARSE_LANGOPT(HeinousExtensions);
1918 PARSE_LANGOPT(Optimize);
1919 PARSE_LANGOPT(OptimizeSize);
1920 PARSE_LANGOPT(Static);
1921 PARSE_LANGOPT(PICLevel);
1922 PARSE_LANGOPT(GNUInline);
1923 PARSE_LANGOPT(NoInline);
1924 PARSE_LANGOPT(AccessControl);
1925 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00001926 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001927 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1928 ++Idx;
1929 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1930 ++Idx;
Daniel Dunbarab8e2812009-09-21 04:16:19 +00001931 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1932 Record[Idx]);
1933 ++Idx;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001934 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001935 PARSE_LANGOPT(OpenCL);
Mike Stump9c276ae2009-12-12 01:27:46 +00001936 PARSE_LANGOPT(CatchUndefined);
1937 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001938 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001939
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001940 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001941 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001942
1943 return false;
1944}
1945
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001946void PCHReader::ReadPreprocessedEntities() {
1947 ReadDefinedMacros();
1948}
1949
Douglas Gregor2cf26342009-04-09 22:27:44 +00001950/// \brief Read and return the type at the given offset.
1951///
1952/// This routine actually reads the record corresponding to the type
1953/// at the given offset in the bitstream. It is a helper routine for
1954/// GetType, which deals with reading type IDs.
1955QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001956 // Keep track of where we are in the stream, then jump back there
1957 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001958 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001959
Douglas Gregord89275b2009-07-06 18:54:52 +00001960 // Note that we are loading a type record.
1961 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001962
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001963 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001964 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001965 unsigned Code = DeclsCursor.ReadCode();
1966 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001967 case pch::TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001968 if (Record.size() != 2) {
1969 Error("Incorrect encoding of extended qualifier type");
1970 return QualType();
1971 }
Douglas Gregor6d473962009-04-15 22:00:08 +00001972 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00001973 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1974 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00001975 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001976
Douglas Gregor2cf26342009-04-09 22:27:44 +00001977 case pch::TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001978 if (Record.size() != 1) {
1979 Error("Incorrect encoding of complex type");
1980 return QualType();
1981 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001982 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001983 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001984 }
1985
1986 case pch::TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001987 if (Record.size() != 1) {
1988 Error("Incorrect encoding of pointer type");
1989 return QualType();
1990 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001991 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001992 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001993 }
1994
1995 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001996 if (Record.size() != 1) {
1997 Error("Incorrect encoding of block pointer type");
1998 return QualType();
1999 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002000 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002001 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002002 }
2003
2004 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002005 if (Record.size() != 1) {
2006 Error("Incorrect encoding of lvalue reference type");
2007 return QualType();
2008 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002009 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002010 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002011 }
2012
2013 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002014 if (Record.size() != 1) {
2015 Error("Incorrect encoding of rvalue reference type");
2016 return QualType();
2017 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002018 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002019 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002020 }
2021
2022 case pch::TYPE_MEMBER_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002023 if (Record.size() != 1) {
2024 Error("Incorrect encoding of member pointer type");
2025 return QualType();
2026 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002027 QualType PointeeType = GetType(Record[0]);
2028 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002029 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00002030 }
2031
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002032 case pch::TYPE_CONSTANT_ARRAY: {
2033 QualType ElementType = GetType(Record[0]);
2034 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2035 unsigned IndexTypeQuals = Record[2];
2036 unsigned Idx = 3;
2037 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002038 return Context->getConstantArrayType(ElementType, Size,
2039 ASM, IndexTypeQuals);
2040 }
2041
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002042 case pch::TYPE_INCOMPLETE_ARRAY: {
2043 QualType ElementType = GetType(Record[0]);
2044 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2045 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002046 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002047 }
2048
2049 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00002050 QualType ElementType = GetType(Record[0]);
2051 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2052 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002053 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2054 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002055 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002056 ASM, IndexTypeQuals,
2057 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002058 }
2059
2060 case pch::TYPE_VECTOR: {
John Thompson82287d12010-02-05 00:12:22 +00002061 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002062 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002063 return QualType();
2064 }
2065
2066 QualType ElementType = GetType(Record[0]);
2067 unsigned NumElements = Record[1];
John Thompson82287d12010-02-05 00:12:22 +00002068 bool AltiVec = Record[2];
2069 bool Pixel = Record[3];
2070 return Context->getVectorType(ElementType, NumElements, AltiVec, Pixel);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002071 }
2072
2073 case pch::TYPE_EXT_VECTOR: {
John Thompson82287d12010-02-05 00:12:22 +00002074 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002075 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002076 return QualType();
2077 }
2078
2079 QualType ElementType = GetType(Record[0]);
2080 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002081 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002082 }
2083
2084 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola425ef722010-03-30 22:15:11 +00002085 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002086 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002087 return QualType();
2088 }
2089 QualType ResultType = GetType(Record[0]);
Rafael Espindola425ef722010-03-30 22:15:11 +00002090 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindola264ba482010-03-30 20:24:48 +00002091 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002092 }
2093
2094 case pch::TYPE_FUNCTION_PROTO: {
2095 QualType ResultType = GetType(Record[0]);
Douglas Gregor91236662009-12-22 18:11:50 +00002096 bool NoReturn = Record[1];
Rafael Espindola425ef722010-03-30 22:15:11 +00002097 unsigned RegParm = Record[2];
2098 CallingConv CallConv = (CallingConv)Record[3];
2099 unsigned Idx = 4;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002100 unsigned NumParams = Record[Idx++];
2101 llvm::SmallVector<QualType, 16> ParamTypes;
2102 for (unsigned I = 0; I != NumParams; ++I)
2103 ParamTypes.push_back(GetType(Record[Idx++]));
2104 bool isVariadic = Record[Idx++];
2105 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00002106 bool hasExceptionSpec = Record[Idx++];
2107 bool hasAnyExceptionSpec = Record[Idx++];
2108 unsigned NumExceptions = Record[Idx++];
2109 llvm::SmallVector<QualType, 2> Exceptions;
2110 for (unsigned I = 0; I != NumExceptions; ++I)
2111 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00002112 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00002113 isVariadic, Quals, hasExceptionSpec,
2114 hasAnyExceptionSpec, NumExceptions,
Rafael Espindola264ba482010-03-30 20:24:48 +00002115 Exceptions.data(),
Rafael Espindola425ef722010-03-30 22:15:11 +00002116 FunctionType::ExtInfo(NoReturn, RegParm,
2117 CallConv));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002118 }
2119
John McCalled976492009-12-04 22:46:56 +00002120 case pch::TYPE_UNRESOLVED_USING:
2121 return Context->getTypeDeclType(
2122 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2123
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002124 case pch::TYPE_TYPEDEF:
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002125 if (Record.size() != 1) {
2126 Error("incorrect encoding of typedef type");
2127 return QualType();
2128 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002129 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002130
2131 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002132 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002133
2134 case pch::TYPE_TYPEOF: {
2135 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002136 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002137 return QualType();
2138 }
2139 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002140 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002141 }
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Anders Carlsson395b4752009-06-24 19:06:50 +00002143 case pch::TYPE_DECLTYPE:
2144 return Context->getDecltypeType(ReadTypeExpr());
2145
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002146 case pch::TYPE_RECORD:
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002147 if (Record.size() != 1) {
2148 Error("incorrect encoding of record type");
2149 return QualType();
2150 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002151 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002152
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002153 case pch::TYPE_ENUM:
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002154 if (Record.size() != 1) {
2155 Error("incorrect encoding of enum type");
2156 return QualType();
2157 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002158 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002159
John McCall7da24312009-09-05 00:15:47 +00002160 case pch::TYPE_ELABORATED: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002161 if (Record.size() != 2) {
2162 Error("incorrect encoding of elaborated type");
2163 return QualType();
2164 }
John McCall7da24312009-09-05 00:15:47 +00002165 unsigned Tag = Record[1];
2166 return Context->getElaboratedType(GetType(Record[0]),
2167 (ElaboratedType::TagKind) Tag);
2168 }
2169
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002170 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002171 unsigned Idx = 0;
2172 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
2173 unsigned NumProtos = Record[Idx++];
2174 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2175 for (unsigned I = 0; I != NumProtos; ++I)
2176 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002177 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002178 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002179
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002180 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002181 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00002182 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002183 unsigned NumProtos = Record[Idx++];
2184 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2185 for (unsigned I = 0; I != NumProtos; ++I)
2186 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00002187 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002188 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00002189
John McCall49a832b2009-10-18 09:09:24 +00002190 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2191 unsigned Idx = 0;
2192 QualType Parm = GetType(Record[Idx++]);
2193 QualType Replacement = GetType(Record[Idx++]);
2194 return
2195 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2196 Replacement);
2197 }
John McCall3cb0ebd2010-03-10 03:28:59 +00002198
2199 case pch::TYPE_INJECTED_CLASS_NAME: {
2200 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2201 QualType TST = GetType(Record[1]); // probably derivable
2202 return Context->getInjectedClassNameType(D, TST);
2203 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002204 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002205 // Suppress a GCC warning
2206 return QualType();
2207}
2208
John McCalla1ee0c52009-10-16 21:56:05 +00002209namespace {
2210
2211class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2212 PCHReader &Reader;
2213 const PCHReader::RecordData &Record;
2214 unsigned &Idx;
2215
2216public:
2217 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2218 unsigned &Idx)
2219 : Reader(Reader), Record(Record), Idx(Idx) { }
2220
John McCall51bd8032009-10-18 01:05:36 +00002221 // We want compile-time assurance that we've enumerated all of
2222 // these, so unfortunately we have to declare them first, then
2223 // define them out-of-line.
2224#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00002225#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002226 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002227#include "clang/AST/TypeLocNodes.def"
2228
John McCall51bd8032009-10-18 01:05:36 +00002229 void VisitFunctionTypeLoc(FunctionTypeLoc);
2230 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002231};
2232
2233}
2234
John McCall51bd8032009-10-18 01:05:36 +00002235void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002236 // nothing to do
2237}
John McCall51bd8032009-10-18 01:05:36 +00002238void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorddf889a2010-01-18 18:04:31 +00002239 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2240 if (TL.needsExtraLocalData()) {
2241 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2242 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2243 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2244 TL.setModeAttr(Record[Idx++]);
2245 }
John McCalla1ee0c52009-10-16 21:56:05 +00002246}
John McCall51bd8032009-10-18 01:05:36 +00002247void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2248 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002249}
John McCall51bd8032009-10-18 01:05:36 +00002250void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2251 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002252}
John McCall51bd8032009-10-18 01:05:36 +00002253void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2254 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002255}
John McCall51bd8032009-10-18 01:05:36 +00002256void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2257 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002258}
John McCall51bd8032009-10-18 01:05:36 +00002259void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2260 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002261}
John McCall51bd8032009-10-18 01:05:36 +00002262void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2263 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002264}
John McCall51bd8032009-10-18 01:05:36 +00002265void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2266 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2267 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002268 if (Record[Idx++])
John McCall51bd8032009-10-18 01:05:36 +00002269 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002270 else
John McCall51bd8032009-10-18 01:05:36 +00002271 TL.setSizeExpr(0);
2272}
2273void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2274 VisitArrayTypeLoc(TL);
2275}
2276void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2277 VisitArrayTypeLoc(TL);
2278}
2279void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2280 VisitArrayTypeLoc(TL);
2281}
2282void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2283 DependentSizedArrayTypeLoc TL) {
2284 VisitArrayTypeLoc(TL);
2285}
2286void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2287 DependentSizedExtVectorTypeLoc TL) {
2288 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2289}
2290void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2291 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2292}
2293void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2294 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2295}
2296void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2297 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2298 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2299 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002300 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002301 }
2302}
2303void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2304 VisitFunctionTypeLoc(TL);
2305}
2306void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2307 VisitFunctionTypeLoc(TL);
2308}
John McCalled976492009-12-04 22:46:56 +00002309void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2310 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2311}
John McCall51bd8032009-10-18 01:05:36 +00002312void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2313 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2314}
2315void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002316 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2317 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2318 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002319}
2320void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002321 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2322 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2323 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2324 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002325}
2326void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2327 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2328}
2329void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2330 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2331}
2332void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2333 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2334}
2335void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2336 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2337}
2338void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2339 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2340}
John McCall49a832b2009-10-18 09:09:24 +00002341void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2342 SubstTemplateTypeParmTypeLoc TL) {
2343 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2344}
John McCall51bd8032009-10-18 01:05:36 +00002345void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2346 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002347 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2348 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2349 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2350 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2351 TL.setArgLocInfo(i,
2352 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2353 Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002354}
2355void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2356 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2357}
John McCall3cb0ebd2010-03-10 03:28:59 +00002358void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2359 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2360}
Douglas Gregor4714c122010-03-31 17:34:00 +00002361void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
John McCall51bd8032009-10-18 01:05:36 +00002362 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2363}
2364void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2365 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002366 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2367 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2368 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2369 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002370}
John McCall54e14c42009-10-22 22:37:11 +00002371void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2372 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2373 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2374 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2375 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2376 TL.setHasProtocolsAsWritten(Record[Idx++]);
2377 if (TL.hasProtocolsAsWritten())
2378 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2379 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2380}
John McCalla1ee0c52009-10-16 21:56:05 +00002381
John McCalla93c9342009-12-07 02:54:59 +00002382TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00002383 unsigned &Idx) {
2384 QualType InfoTy = GetType(Record[Idx++]);
2385 if (InfoTy.isNull())
2386 return 0;
2387
John McCalla93c9342009-12-07 02:54:59 +00002388 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCalla1ee0c52009-10-16 21:56:05 +00002389 TypeLocReader TLR(*this, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00002390 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00002391 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00002392 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00002393}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002394
Douglas Gregor8038d512009-04-10 17:25:41 +00002395QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002396 unsigned FastQuals = ID & Qualifiers::FastMask;
2397 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002398
2399 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2400 QualType T;
2401 switch ((pch::PredefinedTypeIDs)Index) {
2402 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002403 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2404 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002405
2406 case pch::PREDEF_TYPE_CHAR_U_ID:
2407 case pch::PREDEF_TYPE_CHAR_S_ID:
2408 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002409 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002410 break;
2411
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002412 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2413 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2414 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2415 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2416 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002417 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002418 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2419 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2420 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2421 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2422 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2423 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002424 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002425 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2426 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2427 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2428 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2429 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002430 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002431 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2432 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002433 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2434 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002435 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002436 }
2437
2438 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002439 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002440 }
2441
2442 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002443 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall0953e762009-09-24 19:53:00 +00002444 if (TypesLoaded[Index].isNull())
2445 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump1eb44332009-09-09 15:08:12 +00002446
John McCall0953e762009-09-24 19:53:00 +00002447 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002448}
2449
John McCall833ca992009-10-29 08:12:44 +00002450TemplateArgumentLocInfo
2451PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2452 const RecordData &Record,
2453 unsigned &Index) {
2454 switch (Kind) {
2455 case TemplateArgument::Expression:
2456 return ReadDeclExpr();
2457 case TemplateArgument::Type:
John McCalla93c9342009-12-07 02:54:59 +00002458 return GetTypeSourceInfo(Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002459 case TemplateArgument::Template: {
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00002460 SourceLocation
Douglas Gregor788cd062009-11-11 01:00:40 +00002461 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2462 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2463 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2464 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2465 TemplateNameLoc);
2466 }
John McCall833ca992009-10-29 08:12:44 +00002467 case TemplateArgument::Null:
2468 case TemplateArgument::Integral:
2469 case TemplateArgument::Declaration:
2470 case TemplateArgument::Pack:
2471 return TemplateArgumentLocInfo();
2472 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002473 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00002474 return TemplateArgumentLocInfo();
2475}
2476
Douglas Gregor8038d512009-04-10 17:25:41 +00002477Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002478 if (ID == 0)
2479 return 0;
2480
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002481 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002482 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002483 return 0;
2484 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002485
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002486 unsigned Index = ID - 1;
2487 if (!DeclsLoaded[Index])
2488 ReadDeclRecord(DeclOffsets[Index], Index);
2489
2490 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002491}
2492
Chris Lattner887e2b32009-04-27 05:46:25 +00002493/// \brief Resolve the offset of a statement into a statement.
2494///
2495/// This operation will read a new statement from the external
2496/// source each time it is called, and is meant to be used via a
2497/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2498Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002499 // Since we know tha this statement is part of a decl, make sure to use the
2500 // decl cursor to read it.
2501 DeclsCursor.JumpToBit(Offset);
2502 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002503}
2504
Douglas Gregor2cf26342009-04-09 22:27:44 +00002505bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002506 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002507 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002508 "DeclContext has no lexical decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002509
Douglas Gregor2cf26342009-04-09 22:27:44 +00002510 uint64_t Offset = DeclContextOffsets[DC].first;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002511 if (Offset == 0) {
2512 Error("DeclContext has no lexical decls in storage");
2513 return true;
2514 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002515
Douglas Gregor0b748912009-04-14 21:18:50 +00002516 // Keep track of where we are in the stream, then jump back there
2517 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002518 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002519
Douglas Gregor2cf26342009-04-09 22:27:44 +00002520 // Load the record containing all of the declarations lexically in
2521 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002522 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002523 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002524 unsigned Code = DeclsCursor.ReadCode();
2525 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002526 if (RecCode != pch::DECL_CONTEXT_LEXICAL) {
2527 Error("Expected lexical block");
2528 return true;
2529 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002530
2531 // Load all of the declaration IDs
2532 Decls.clear();
2533 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002534 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002535 return false;
2536}
2537
2538bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002539 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002540 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002541 "DeclContext has no visible decls in storage");
2542 uint64_t Offset = DeclContextOffsets[DC].second;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002543 if (Offset == 0) {
2544 Error("DeclContext has no visible decls in storage");
2545 return true;
2546 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002547
Douglas Gregor0b748912009-04-14 21:18:50 +00002548 // Keep track of where we are in the stream, then jump back there
2549 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002550 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002551
Douglas Gregor2cf26342009-04-09 22:27:44 +00002552 // Load the record containing all of the declarations visible in
2553 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002554 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002555 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002556 unsigned Code = DeclsCursor.ReadCode();
2557 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002558 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2559 Error("Expected visible block");
2560 return true;
2561 }
2562
Douglas Gregor2cf26342009-04-09 22:27:44 +00002563 if (Record.size() == 0)
Mike Stump1eb44332009-09-09 15:08:12 +00002564 return false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002565
2566 Decls.clear();
2567
2568 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002569 while (Idx < Record.size()) {
2570 Decls.push_back(VisibleDeclaration());
2571 Decls.back().Name = ReadDeclarationName(Record, Idx);
2572
Douglas Gregor2cf26342009-04-09 22:27:44 +00002573 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002574 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002575 LoadedDecls.reserve(Size);
2576 for (unsigned I = 0; I < Size; ++I)
2577 LoadedDecls.push_back(Record[Idx++]);
2578 }
2579
Douglas Gregor25123082009-04-22 22:34:57 +00002580 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002581 return false;
2582}
2583
Douglas Gregorfdd01722009-04-14 00:24:19 +00002584void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002585 this->Consumer = Consumer;
2586
Douglas Gregorfdd01722009-04-14 00:24:19 +00002587 if (!Consumer)
2588 return;
2589
2590 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002591 // Force deserialization of this decl, which will cause it to be passed to
2592 // the consumer (or queued).
2593 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002594 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002595
2596 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2597 DeclGroupRef DG(InterestingDecls[I]);
2598 Consumer->HandleTopLevelDecl(DG);
2599 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002600}
2601
Douglas Gregor2cf26342009-04-09 22:27:44 +00002602void PCHReader::PrintStats() {
2603 std::fprintf(stderr, "*** PCH Statistics:\n");
2604
Mike Stump1eb44332009-09-09 15:08:12 +00002605 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002606 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002607 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002608 unsigned NumDeclsLoaded
2609 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2610 (Decl *)0);
2611 unsigned NumIdentifiersLoaded
2612 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2613 IdentifiersLoaded.end(),
2614 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002615 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002616 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2617 SelectorsLoaded.end(),
2618 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002619
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002620 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2621 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002622 if (TotalNumSLocEntries)
2623 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2624 NumSLocEntriesRead, TotalNumSLocEntries,
2625 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002626 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002627 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002628 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2629 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2630 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002631 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002632 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2633 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002634 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002635 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002636 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2637 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002638 if (TotalNumSelectors)
2639 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2640 NumSelectorsLoaded, TotalNumSelectors,
2641 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2642 if (TotalNumStatements)
2643 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2644 NumStatementsRead, TotalNumStatements,
2645 ((float)NumStatementsRead/TotalNumStatements * 100));
2646 if (TotalNumMacros)
2647 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2648 NumMacrosRead, TotalNumMacros,
2649 ((float)NumMacrosRead/TotalNumMacros * 100));
2650 if (TotalLexicalDeclContexts)
2651 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2652 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2653 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2654 * 100));
2655 if (TotalVisibleDeclContexts)
2656 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2657 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2658 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2659 * 100));
2660 if (TotalSelectorsInMethodPool) {
2661 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2662 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2663 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2664 * 100));
2665 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2666 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002667 std::fprintf(stderr, "\n");
2668}
2669
Douglas Gregor668c1a42009-04-21 22:25:48 +00002670void PCHReader::InitializeSema(Sema &S) {
2671 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002672 S.ExternalSource = this;
2673
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002674 // Makes sure any declarations that were deserialized "too early"
2675 // still get added to the identifier's declaration chains.
2676 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2677 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2678 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002679 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002680 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002681
2682 // If there were any tentative definitions, deserialize them and add
Sebastian Redle9d12b62010-01-31 22:27:38 +00002683 // them to Sema's list of tentative definitions.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002684 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2685 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redle9d12b62010-01-31 22:27:38 +00002686 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002687 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00002688
Tanya Lattnere6bbc012010-02-12 00:07:30 +00002689 // If there were any unused static functions, deserialize them and add to
2690 // Sema's list of unused static functions.
2691 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
2692 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
2693 SemaObj->UnusedStaticFuncs.push_back(FD);
2694 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002695
2696 // If there were any locally-scoped external declarations,
2697 // deserialize them and add them to Sema's table of locally-scoped
2698 // external declarations.
2699 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2700 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2701 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2702 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002703
2704 // If there were any ext_vector type declarations, deserialize them
2705 // and add them to Sema's vector of such declarations.
2706 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2707 SemaObj->ExtVectorDecls.push_back(
2708 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002709}
2710
2711IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2712 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00002713 PCHIdentifierLookupTable *IdTable
Douglas Gregor668c1a42009-04-21 22:25:48 +00002714 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2715 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2716 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2717 if (Pos == IdTable->end())
2718 return 0;
2719
2720 // Dereferencing the iterator has the effect of building the
2721 // IdentifierInfo node and populating it with the various
2722 // declarations it needs.
2723 return *Pos;
2724}
2725
Mike Stump1eb44332009-09-09 15:08:12 +00002726std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002727PCHReader::ReadMethodPool(Selector Sel) {
2728 if (!MethodPoolLookupTable)
2729 return std::pair<ObjCMethodList, ObjCMethodList>();
2730
2731 // Try to find this selector within our on-disk hash table.
2732 PCHMethodPoolLookupTable *PoolTable
2733 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2734 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002735 if (Pos == PoolTable->end()) {
2736 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002737 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002738 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002739
Douglas Gregor83941df2009-04-25 17:48:32 +00002740 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002741 return *Pos;
2742}
2743
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002744void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002745 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002746 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002747 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002748}
2749
Douglas Gregord89275b2009-07-06 18:54:52 +00002750/// \brief Set the globally-visible declarations associated with the given
2751/// identifier.
2752///
2753/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00002754/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00002755/// them.
2756///
2757/// \param II an IdentifierInfo that refers to one or more globally-visible
2758/// declarations.
2759///
2760/// \param DeclIDs the set of declaration IDs with the name @p II that are
2761/// visible at global scope.
2762///
2763/// \param Nonrecursive should be true to indicate that the caller knows that
2764/// this call is non-recursive, and therefore the globally-visible declarations
2765/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00002766void
2767PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00002768 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2769 bool Nonrecursive) {
2770 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2771 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2772 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2773 PII.II = II;
2774 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2775 PII.DeclIDs.push_back(DeclIDs[I]);
2776 return;
2777 }
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Douglas Gregord89275b2009-07-06 18:54:52 +00002779 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2780 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2781 if (SemaObj) {
2782 // Introduce this declaration into the translation-unit scope
2783 // and add it to the declaration chain for this identifier, so
2784 // that (unqualified) name lookup will find it.
2785 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2786 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2787 } else {
2788 // Queue this declaration so that it will be added to the
2789 // translation unit scope and identifier's declaration chain
2790 // once a Sema object is known.
2791 PreloadedDecls.push_back(D);
2792 }
2793 }
2794}
2795
Chris Lattner7356a312009-04-11 21:15:38 +00002796IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002797 if (ID == 0)
2798 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002799
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002800 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002801 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002802 return 0;
2803 }
Mike Stump1eb44332009-09-09 15:08:12 +00002804
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002805 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002806 if (!IdentifiersLoaded[ID - 1]) {
2807 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002808 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002809
Douglas Gregor02fc7512009-04-28 20:01:51 +00002810 // All of the strings in the PCH file are preceded by a 16-bit
2811 // length. Extract that 16-bit length to avoid having to execute
2812 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00002813 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2814 // unsigned integers. This is important to avoid integer overflow when
2815 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00002816 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00002817 unsigned StrLen = (((unsigned) StrLenPtr[0])
2818 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002819 IdentifiersLoaded[ID - 1]
Kovarththanan Rajaratnam811f4262010-03-12 10:32:27 +00002820 = &PP->getIdentifierTable().get(Str, StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002821 }
Mike Stump1eb44332009-09-09 15:08:12 +00002822
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002823 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002824}
2825
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002826void PCHReader::ReadSLocEntry(unsigned ID) {
2827 ReadSLocEntryRecord(ID);
2828}
2829
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002830Selector PCHReader::DecodeSelector(unsigned ID) {
2831 if (ID == 0)
2832 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00002833
Douglas Gregora02b1472009-04-28 21:53:25 +00002834 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002835 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002836
2837 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002838 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002839 return Selector();
2840 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002841
2842 unsigned Index = ID - 1;
2843 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2844 // Load this selector from the selector table.
2845 // FIXME: endianness portability issues with SelectorOffsets table
2846 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002847 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00002848 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2849 }
2850
2851 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002852}
2853
Douglas Gregor719770d2010-04-06 17:30:22 +00002854Selector PCHReader::GetSelector(uint32_t ID) {
2855 return DecodeSelector(ID);
2856}
2857
2858uint32_t PCHReader::GetNumKnownSelectors() {
2859 return TotalNumSelectors + 1;
2860}
2861
Mike Stump1eb44332009-09-09 15:08:12 +00002862DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00002863PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2864 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2865 switch (Kind) {
2866 case DeclarationName::Identifier:
2867 return DeclarationName(GetIdentifierInfo(Record, Idx));
2868
2869 case DeclarationName::ObjCZeroArgSelector:
2870 case DeclarationName::ObjCOneArgSelector:
2871 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002872 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002873
2874 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002875 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002876 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002877
2878 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002879 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002880 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002881
2882 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002883 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002884 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002885
2886 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002887 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002888 (OverloadedOperatorKind)Record[Idx++]);
2889
Sean Hunt3e518bd2009-11-29 07:34:05 +00002890 case DeclarationName::CXXLiteralOperatorName:
2891 return Context->DeclarationNames.getCXXLiteralOperatorName(
2892 GetIdentifierInfo(Record, Idx));
2893
Douglas Gregor2cf26342009-04-09 22:27:44 +00002894 case DeclarationName::CXXUsingDirective:
2895 return DeclarationName::getUsingDirectiveName();
2896 }
2897
2898 // Required to silence GCC warning
2899 return DeclarationName();
2900}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002901
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002902/// \brief Read an integral value
2903llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2904 unsigned BitWidth = Record[Idx++];
2905 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2906 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2907 Idx += NumWords;
2908 return Result;
2909}
2910
2911/// \brief Read a signed integral value
2912llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2913 bool isUnsigned = Record[Idx++];
2914 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2915}
2916
Douglas Gregor17fc2232009-04-14 21:55:33 +00002917/// \brief Read a floating-point value
2918llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002919 return llvm::APFloat(ReadAPInt(Record, Idx));
2920}
2921
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002922// \brief Read a string
2923std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2924 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002925 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002926 Idx += Len;
2927 return Result;
2928}
2929
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002930DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002931 return Diag(SourceLocation(), DiagID);
2932}
2933
2934DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002935 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002936}
Douglas Gregor025452f2009-04-17 00:04:06 +00002937
Douglas Gregor668c1a42009-04-21 22:25:48 +00002938/// \brief Retrieve the identifier table associated with the
2939/// preprocessor.
2940IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002941 assert(PP && "Forgot to set Preprocessor ?");
2942 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002943}
2944
Douglas Gregor025452f2009-04-17 00:04:06 +00002945/// \brief Record that the given ID maps to the given switch-case
2946/// statement.
2947void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2948 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2949 SwitchCaseStmts[ID] = SC;
2950}
2951
2952/// \brief Retrieve the switch-case statement with the given ID.
2953SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2954 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2955 return SwitchCaseStmts[ID];
2956}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002957
2958/// \brief Record that the given label statement has been
2959/// deserialized and has the given ID.
2960void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00002961 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002962 "Deserialized label twice");
2963 LabelStmts[ID] = S;
2964
2965 // If we've already seen any goto statements that point to this
2966 // label, resolve them now.
2967 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2968 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2969 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2970 Goto->second->setLabel(S);
2971 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002972
2973 // If we've already seen any address-label statements that point to
2974 // this label, resolve them now.
2975 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00002976 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002977 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002978 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002979 AddrLabel != AddrLabels.second; ++AddrLabel)
2980 AddrLabel->second->setLabel(S);
2981 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002982}
2983
2984/// \brief Set the label of the given statement to the label
2985/// identified by ID.
2986///
2987/// Depending on the order in which the label and other statements
2988/// referencing that label occur, this operation may complete
2989/// immediately (updating the statement) or it may queue the
2990/// statement to be back-patched later.
2991void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2992 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2993 if (Label != LabelStmts.end()) {
2994 // We've already seen this label, so set the label of the goto and
2995 // we're done.
2996 S->setLabel(Label->second);
2997 } else {
2998 // We haven't seen this label yet, so add this goto to the set of
2999 // unresolved goto statements.
3000 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3001 }
3002}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003003
3004/// \brief Set the label of the given expression to the label
3005/// identified by ID.
3006///
3007/// Depending on the order in which the label and other statements
3008/// referencing that label occur, this operation may complete
3009/// immediately (updating the statement) or it may queue the
3010/// statement to be back-patched later.
3011void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3012 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3013 if (Label != LabelStmts.end()) {
3014 // We've already seen this label, so set the label of the
3015 // label-address expression and we're done.
3016 S->setLabel(Label->second);
3017 } else {
3018 // We haven't seen this label yet, so add this label-address
3019 // expression to the set of unresolved label-address expressions.
3020 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3021 }
3022}
Douglas Gregord89275b2009-07-06 18:54:52 +00003023
3024
Mike Stump1eb44332009-09-09 15:08:12 +00003025PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00003026 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
3027 Reader.CurrentlyLoadingTypeOrDecl = this;
3028}
3029
3030PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
3031 if (!Parent) {
3032 // If any identifiers with corresponding top-level declarations have
3033 // been loaded, load those declarations now.
3034 while (!Reader.PendingIdentifierInfos.empty()) {
3035 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
3036 Reader.PendingIdentifierInfos.front().DeclIDs,
3037 true);
3038 Reader.PendingIdentifierInfos.pop_front();
3039 }
3040 }
3041
Mike Stump1eb44332009-09-09 15:08:12 +00003042 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00003043}