blob: 36cddd32e5cf1f5213cc1b3ad824f341b0072d66 [file] [log] [blame]
Douglas Gregoref84c4b2009-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 Lattner92ba5ff2009-04-27 05:14:47 +000013
Douglas Gregoref84c4b2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor55abb232009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar732ef8a2009-11-11 23:58:53 +000016#include "clang/Frontend/Utils.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000017#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor1a0d0b92009-04-14 00:24:19 +000018#include "clang/AST/ASTConsumer.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000022#include "clang/AST/TypeLocVisitor.h"
Chris Lattner34321bc2009-04-10 21:41:48 +000023#include "clang/Lex/MacroInfo.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000024#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000025#include "clang/Lex/HeaderSearch.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000029#include "clang/Basic/FileManager.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000030#include "clang/Basic/TargetInfo.h"
Douglas Gregord54f3a12009-10-05 21:07:28 +000031#include "clang/Basic/Version.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000032#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000034#include "llvm/Support/MemoryBuffer.h"
John McCall0ad16662009-10-29 08:12:44 +000035#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +000036#include "llvm/System/Path.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000037#include <algorithm>
Douglas Gregorc379c072009-04-28 18:58:38 +000038#include <iterator>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000039#include <cstdio>
Douglas Gregorc5046832009-04-27 18:38:38 +000040#include <sys/stat.h>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000041using namespace clang;
42
43//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000044// PCH reader validator implementation
45//===----------------------------------------------------------------------===//
46
47PCHReaderListener::~PCHReaderListener() {}
48
49bool
50PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
51 const LangOptions &PPLangOpts = PP.getLangOptions();
52#define PARSE_LANGOPT_BENIGN(Option)
53#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
54 if (PPLangOpts.Option != LangOpts.Option) { \
55 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
56 return true; \
57 }
58
59 PARSE_LANGOPT_BENIGN(Trigraphs);
60 PARSE_LANGOPT_BENIGN(BCPLComment);
61 PARSE_LANGOPT_BENIGN(DollarIdents);
62 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
63 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
64 PARSE_LANGOPT_BENIGN(ImplicitInt);
65 PARSE_LANGOPT_BENIGN(Digraphs);
66 PARSE_LANGOPT_BENIGN(HexFloats);
67 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
68 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
69 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
70 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
71 PARSE_LANGOPT_BENIGN(CXXOperatorName);
72 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
73 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
74 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
Fariborz Jahanian45878032010-02-09 19:31:38 +000075 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000076 PARSE_LANGOPT_BENIGN(PascalStrings);
77 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump11289f42009-09-09 15:08:12 +000078 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000079 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +000080 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000081 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +000082 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000083 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
84 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
85 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +000086 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000087 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000088 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000089 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
90 PARSE_LANGOPT_BENIGN(EmitAllDecls);
91 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
92 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump11289f42009-09-09 15:08:12 +000093 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000094 diag::warn_pch_heinous_extensions);
95 // FIXME: Most of the options below are benign if the macro wasn't
96 // used. Unfortunately, this means that a PCH compiled without
97 // optimization can't be used with optimization turned on, even
98 // though the only thing that changes is whether __OPTIMIZE__ was
99 // defined... but if __OPTIMIZE__ never showed up in the header, it
100 // doesn't matter. We could consider making this some special kind
101 // of check.
102 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
103 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
104 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
105 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
106 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
107 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
108 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
109 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsoned4e2952009-11-05 20:14:16 +0000110 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000111 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000112 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000113 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
114 return true;
115 }
116 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000117 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
118 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000119 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000120 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stumpd9546382009-12-12 01:27:46 +0000121 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000122 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +0000123#undef PARSE_LANGOPT_IMPORTANT
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000124#undef PARSE_LANGOPT_BENIGN
125
126 return false;
127}
128
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000129bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
130 if (Triple == PP.getTargetInfo().getTriple().str())
131 return false;
132
133 Reader.Diag(diag::warn_pch_target_triple)
134 << Triple << PP.getTargetInfo().getTriple().str();
135 return true;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000136}
137
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000138bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000139 FileID PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000140 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000141 std::string &SuggestedPredefines) {
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000142 // We are in the context of an implicit include, so the predefines buffer will
143 // have a #include entry for the PCH file itself (as normalized by the
144 // preprocessor initialization). Find it and skip over it in the checking
145 // below.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000146 llvm::SmallString<256> PCHInclude;
147 PCHInclude += "#include \"";
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000148 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000149 PCHInclude += "\"\n";
150 std::pair<llvm::StringRef,llvm::StringRef> Split =
151 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
152 llvm::StringRef Left = Split.first, Right = Split.second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000153 if (Left == PP.getPredefines()) {
154 Error("Missing PCH include entry!");
155 return true;
156 }
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000157
158 // If the predefines is equal to the joined left and right halves, we're done!
159 if (Left.size() + Right.size() == PCHPredef.size() &&
160 PCHPredef.startswith(Left) && PCHPredef.endswith(Right))
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000161 return false;
162
163 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000164
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000165 // The predefines buffers are different. Determine what the differences are,
166 // and whether they require us to reject the PCH file.
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000167 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
168 PCHPredef.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
169
170 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
171 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
172 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000173
Daniel Dunbar499baed2009-11-11 05:26:28 +0000174 // Sort both sets of predefined buffer lines, since we allow some extra
175 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000176 std::sort(CmdLineLines.begin(), CmdLineLines.end());
177 std::sort(PCHLines.begin(), PCHLines.end());
178
Daniel Dunbar499baed2009-11-11 05:26:28 +0000179 // Determine which predefines that were used to build the PCH file are missing
180 // from the command line.
181 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000182 std::set_difference(PCHLines.begin(), PCHLines.end(),
183 CmdLineLines.begin(), CmdLineLines.end(),
184 std::back_inserter(MissingPredefines));
185
186 bool MissingDefines = false;
187 bool ConflictingDefines = false;
188 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000189 llvm::StringRef Missing = MissingPredefines[I];
190 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000191 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
192 return true;
193 }
Mike Stump11289f42009-09-09 15:08:12 +0000194
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000195 // This is a macro definition. Determine the name of the macro we're
196 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000197 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000198 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000199 = Missing.find_first_of("( \n\r", StartOfMacroName);
200 assert(EndOfMacroName != std::string::npos &&
201 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000202 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000203
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000204 // Determine whether this macro was given a different definition on the
205 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000206 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000207 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000208 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000209 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
210 MacroDefStart);
211 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000212 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000213 // Different macro; we're done.
214 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000215 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000216 }
Mike Stump11289f42009-09-09 15:08:12 +0000217
218 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000219 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000220 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000221 (*ConflictPos)[MacroDefLen] != '(')
222 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000223
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000224 // We found a conflicting macro definition.
225 break;
226 }
Mike Stump11289f42009-09-09 15:08:12 +0000227
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000228 if (ConflictPos != CmdLineLines.end()) {
229 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
230 << MacroName;
231
232 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000233 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
234 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
235 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
236 .getFileLocWithOffset(Offset);
237 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000238
239 ConflictingDefines = true;
240 continue;
241 }
Mike Stump11289f42009-09-09 15:08:12 +0000242
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000243 // If the macro doesn't conflict, then we'll just pick up the macro
244 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000245 if (ConflictingDefines)
246 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000247
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000248 if (!MissingDefines) {
249 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
250 MissingDefines = true;
251 }
252
253 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000254 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
255 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
256 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000257 .getFileLocWithOffset(Offset);
258 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
259 }
Mike Stump11289f42009-09-09 15:08:12 +0000260
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000261 if (ConflictingDefines)
262 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000263
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000264 // Determine what predefines were introduced based on command-line
265 // parameters that were not present when building the PCH
266 // file. Extra #defines are okay, so long as the identifiers being
267 // defined were not used within the precompiled header.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000268 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000269 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
270 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000271 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000272 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000273 llvm::StringRef &Extra = ExtraPredefines[I];
274 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000275 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
276 return true;
277 }
278
279 // This is an extra macro definition. Determine the name of the
280 // macro we're defining.
281 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000282 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000283 = Extra.find_first_of("( \n\r", StartOfMacroName);
284 assert(EndOfMacroName != std::string::npos &&
285 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000286 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000287
288 // Check whether this name was used somewhere in the PCH file. If
289 // so, defining it as a macro could change behavior, so we reject
290 // the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000291 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000292 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000293 return true;
294 }
295
296 // Add this definition to the suggested predefines buffer.
297 SuggestedPredefines += Extra;
298 SuggestedPredefines += '\n';
299 }
300
301 // If we get here, it's because the predefines buffer had compatible
302 // contents. Accept the PCH file.
303 return false;
304}
305
Douglas Gregor5712ebc2010-03-16 16:35:32 +0000306void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
307 unsigned ID) {
308 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
309 ++NumHeaderInfos;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000310}
311
312void PCHValidator::ReadCounter(unsigned Value) {
313 PP.setCounterValue(Value);
314}
315
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000316//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000317// PCH reader implementation
318//===----------------------------------------------------------------------===//
319
Mike Stump11289f42009-09-09 15:08:12 +0000320PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
321 const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000322 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
323 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000324 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000325 IdentifierTableData(0), IdentifierLookupTable(0),
326 IdentifierOffsets(0),
327 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
328 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000329 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000330 NumStatHits(0), NumStatMisses(0),
331 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000332 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000333 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000334 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000335 RelocatablePCH = false;
336}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000337
338PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000339 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000340 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000341 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000342 IdentifierTableData(0), IdentifierLookupTable(0),
343 IdentifierOffsets(0),
344 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
345 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000346 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000347 NumStatHits(0), NumStatMisses(0),
348 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000349 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000350 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000351 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000352 RelocatablePCH = false;
353}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000354
355PCHReader::~PCHReader() {}
356
Chris Lattner1de76db2009-04-27 05:58:23 +0000357Expr *PCHReader::ReadDeclExpr() {
358 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
359}
360
361Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor12bfa382009-10-17 00:13:19 +0000362 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000363}
364
365
Douglas Gregora868bbd2009-04-21 22:25:48 +0000366namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000367class PCHMethodPoolLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000368 PCHReader &Reader;
369
370public:
371 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
372
373 typedef Selector external_key_type;
374 typedef external_key_type internal_key_type;
375
376 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000377
Douglas Gregorc78d3462009-04-24 21:10:55 +0000378 static bool EqualKey(const internal_key_type& a,
379 const internal_key_type& b) {
380 return a == b;
381 }
Mike Stump11289f42009-09-09 15:08:12 +0000382
Douglas Gregorc78d3462009-04-24 21:10:55 +0000383 static unsigned ComputeHash(Selector Sel) {
384 unsigned N = Sel.getNumArgs();
385 if (N == 0)
386 ++N;
387 unsigned R = 5381;
388 for (unsigned I = 0; I != N; ++I)
389 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000390 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000391 return R;
392 }
Mike Stump11289f42009-09-09 15:08:12 +0000393
Douglas Gregorc78d3462009-04-24 21:10:55 +0000394 // This hopefully will just get inlined and removed by the optimizer.
395 static const internal_key_type&
396 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000397
Douglas Gregorc78d3462009-04-24 21:10:55 +0000398 static std::pair<unsigned, unsigned>
399 ReadKeyDataLength(const unsigned char*& d) {
400 using namespace clang::io;
401 unsigned KeyLen = ReadUnalignedLE16(d);
402 unsigned DataLen = ReadUnalignedLE16(d);
403 return std::make_pair(KeyLen, DataLen);
404 }
Mike Stump11289f42009-09-09 15:08:12 +0000405
Douglas Gregor95c13f52009-04-25 17:48:32 +0000406 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000407 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000408 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000409 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000410 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000411 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
412 if (N == 0)
413 return SelTable.getNullarySelector(FirstII);
414 else if (N == 1)
415 return SelTable.getUnarySelector(FirstII);
416
417 llvm::SmallVector<IdentifierInfo *, 16> Args;
418 Args.push_back(FirstII);
419 for (unsigned I = 1; I != N; ++I)
420 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
421
Douglas Gregor038c3382009-05-22 22:45:36 +0000422 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000423 }
Mike Stump11289f42009-09-09 15:08:12 +0000424
Douglas Gregorc78d3462009-04-24 21:10:55 +0000425 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
426 using namespace clang::io;
427 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
428 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
429
430 data_type Result;
431
432 // Load instance methods
433 ObjCMethodList *Prev = 0;
434 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000435 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000436 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
437 if (!Result.first.Method) {
438 // This is the first method, which is the easy case.
439 Result.first.Method = Method;
440 Prev = &Result.first;
441 continue;
442 }
443
Ted Kremenekda4abf12010-02-11 00:53:01 +0000444 ObjCMethodList *Mem =
445 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
446 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000447 Prev = Prev->Next;
448 }
449
450 // Load factory methods
451 Prev = 0;
452 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000453 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000454 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
455 if (!Result.second.Method) {
456 // This is the first method, which is the easy case.
457 Result.second.Method = Method;
458 Prev = &Result.second;
459 continue;
460 }
461
Ted Kremenekda4abf12010-02-11 00:53:01 +0000462 ObjCMethodList *Mem =
463 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
464 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000465 Prev = Prev->Next;
466 }
467
468 return Result;
469 }
470};
Mike Stump11289f42009-09-09 15:08:12 +0000471
472} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000473
474/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000475typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000476 PCHMethodPoolLookupTable;
477
478namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000479class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000480 PCHReader &Reader;
481
482 // If we know the IdentifierInfo in advance, it is here and we will
483 // not build a new one. Used when deserializing information about an
484 // identifier that was constructed before the PCH file was read.
485 IdentifierInfo *KnownII;
486
487public:
488 typedef IdentifierInfo * data_type;
489
490 typedef const std::pair<const char*, unsigned> external_key_type;
491
492 typedef external_key_type internal_key_type;
493
Mike Stump11289f42009-09-09 15:08:12 +0000494 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregora868bbd2009-04-21 22:25:48 +0000495 : Reader(Reader), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000496
Douglas Gregora868bbd2009-04-21 22:25:48 +0000497 static bool EqualKey(const internal_key_type& a,
498 const internal_key_type& b) {
499 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
500 : false;
501 }
Mike Stump11289f42009-09-09 15:08:12 +0000502
Douglas Gregora868bbd2009-04-21 22:25:48 +0000503 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000504 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
Douglas Gregora868bbd2009-04-21 22:25:48 +0000507 // This hopefully will just get inlined and removed by the optimizer.
508 static const internal_key_type&
509 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000510
Douglas Gregora868bbd2009-04-21 22:25:48 +0000511 static std::pair<unsigned, unsigned>
512 ReadKeyDataLength(const unsigned char*& d) {
513 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000514 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000515 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000516 return std::make_pair(KeyLen, DataLen);
517 }
Mike Stump11289f42009-09-09 15:08:12 +0000518
Douglas Gregora868bbd2009-04-21 22:25:48 +0000519 static std::pair<const char*, unsigned>
520 ReadKey(const unsigned char* d, unsigned n) {
521 assert(n >= 2 && d[n-1] == '\0');
522 return std::make_pair((const char*) d, n-1);
523 }
Mike Stump11289f42009-09-09 15:08:12 +0000524
525 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000526 const unsigned char* d,
527 unsigned DataLen) {
528 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000529 pch::IdentID ID = ReadUnalignedLE32(d);
530 bool IsInteresting = ID & 0x01;
531
532 // Wipe out the "is interesting" bit.
533 ID = ID >> 1;
534
535 if (!IsInteresting) {
536 // For unintersting identifiers, just build the IdentifierInfo
537 // and associate it with the persistent ID.
538 IdentifierInfo *II = KnownII;
539 if (!II)
540 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
541 k.first, k.first + k.second);
542 Reader.SetIdentifierInfo(ID, II);
543 return II;
544 }
545
Douglas Gregorb9256522009-04-28 21:32:13 +0000546 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000547 bool CPlusPlusOperatorKeyword = Bits & 0x01;
548 Bits >>= 1;
549 bool Poisoned = Bits & 0x01;
550 Bits >>= 1;
551 bool ExtensionToken = Bits & 0x01;
552 Bits >>= 1;
553 bool hasMacroDefinition = Bits & 0x01;
554 Bits >>= 1;
555 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
556 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000557
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000558 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000559 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000560
561 // Build the IdentifierInfo itself and link the identifier ID with
562 // the new IdentifierInfo.
563 IdentifierInfo *II = KnownII;
564 if (!II)
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000565 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
566 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000567 Reader.SetIdentifierInfo(ID, II);
568
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000569 // Set or check the various bits in the IdentifierInfo structure.
570 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000571 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000572 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000573 "Incorrect extension token flag");
574 (void)ExtensionToken;
575 II->setIsPoisoned(Poisoned);
576 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
577 "Incorrect C++ operator keyword flag");
578 (void)CPlusPlusOperatorKeyword;
579
Douglas Gregorc3366a52009-04-21 23:56:24 +0000580 // If this identifier is a macro, deserialize the macro
581 // definition.
582 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000583 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregorc3366a52009-04-21 23:56:24 +0000584 Reader.ReadMacroRecord(Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000585 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000586 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000587
588 // Read all of the declarations visible at global scope with this
589 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000590 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000591 if (DataLen > 0) {
592 llvm::SmallVector<uint32_t, 4> DeclIDs;
593 for (; DataLen > 0; DataLen -= 4)
594 DeclIDs.push_back(ReadUnalignedLE32(d));
595 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000596 }
Mike Stump11289f42009-09-09 15:08:12 +0000597
Douglas Gregora868bbd2009-04-21 22:25:48 +0000598 return II;
599 }
600};
Mike Stump11289f42009-09-09 15:08:12 +0000601
602} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000603
604/// \brief The on-disk hash table used to contain information about
605/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000606typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000607 PCHIdentifierLookupTable;
608
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000609void PCHReader::Error(const char *Msg) {
610 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000611}
612
Douglas Gregor92863e42009-04-10 23:10:45 +0000613/// \brief Check the contents of the predefines buffer against the
614/// contents of the predefines buffer used to build the PCH file.
615///
616/// The contents of the two predefines buffers should be the same. If
617/// not, then some command-line option changed the preprocessor state
618/// and we must reject the PCH file.
619///
620/// \param PCHPredef The start of the predefines buffer in the PCH
621/// file.
622///
623/// \param PCHPredefLen The length of the predefines buffer in the PCH
624/// file.
625///
626/// \param PCHBufferID The FileID for the PCH predefines buffer.
627///
628/// \returns true if there was a mismatch (in which case the PCH file
629/// should be ignored), or false otherwise.
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000630bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregor92863e42009-04-10 23:10:45 +0000631 FileID PCHBufferID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000632 if (Listener)
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000633 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000634 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000635 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000636 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000637}
638
Douglas Gregorc5046832009-04-27 18:38:38 +0000639//===----------------------------------------------------------------------===//
640// Source Manager Deserialization
641//===----------------------------------------------------------------------===//
642
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000643/// \brief Read the line table in the source manager block.
644/// \returns true if ther was an error.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000645bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000646 unsigned Idx = 0;
647 LineTableInfo &LineTable = SourceMgr.getLineTable();
648
649 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000650 std::map<int, int> FileIDs;
651 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000652 // Extract the file name
653 unsigned FilenameLen = Record[Idx++];
654 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
655 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000656 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000657 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000658 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000659 }
660
661 // Parse the line entries
662 std::vector<LineEntry> Entries;
663 while (Idx < Record.size()) {
Douglas Gregora8854652009-04-13 17:12:42 +0000664 int FID = FileIDs[Record[Idx++]];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000665
666 // Extract the line entries
667 unsigned NumEntries = Record[Idx++];
668 Entries.clear();
669 Entries.reserve(NumEntries);
670 for (unsigned I = 0; I != NumEntries; ++I) {
671 unsigned FileOffset = Record[Idx++];
672 unsigned LineNo = Record[Idx++];
673 int FilenameID = Record[Idx++];
Mike Stump11289f42009-09-09 15:08:12 +0000674 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000675 = (SrcMgr::CharacteristicKind)Record[Idx++];
676 unsigned IncludeOffset = Record[Idx++];
677 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
678 FileKind, IncludeOffset));
679 }
680 LineTable.AddEntry(FID, Entries);
681 }
682
683 return false;
684}
685
Douglas Gregorc5046832009-04-27 18:38:38 +0000686namespace {
687
Benjamin Kramer16634c22009-11-28 10:07:24 +0000688class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000689public:
690 const bool hasStat;
691 const ino_t ino;
692 const dev_t dev;
693 const mode_t mode;
694 const time_t mtime;
695 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000696
Douglas Gregorc5046832009-04-27 18:38:38 +0000697 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000698 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
699
Douglas Gregorc5046832009-04-27 18:38:38 +0000700 PCHStatData()
701 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
702};
703
Benjamin Kramer16634c22009-11-28 10:07:24 +0000704class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000705 public:
706 typedef const char *external_key_type;
707 typedef const char *internal_key_type;
708
709 typedef PCHStatData data_type;
710
711 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000712 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000713 }
714
715 static internal_key_type GetInternalKey(const char *path) { return path; }
716
717 static bool EqualKey(internal_key_type a, internal_key_type b) {
718 return strcmp(a, b) == 0;
719 }
720
721 static std::pair<unsigned, unsigned>
722 ReadKeyDataLength(const unsigned char*& d) {
723 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
724 unsigned DataLen = (unsigned) *d++;
725 return std::make_pair(KeyLen + 1, DataLen);
726 }
727
728 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
729 return (const char *)d;
730 }
731
732 static data_type ReadData(const internal_key_type, const unsigned char *d,
733 unsigned /*DataLen*/) {
734 using namespace clang::io;
735
736 if (*d++ == 1)
737 return data_type();
738
739 ino_t ino = (ino_t) ReadUnalignedLE32(d);
740 dev_t dev = (dev_t) ReadUnalignedLE32(d);
741 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000742 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000743 off_t size = (off_t) ReadUnalignedLE64(d);
744 return data_type(ino, dev, mode, mtime, size);
745 }
746};
747
748/// \brief stat() cache for precompiled headers.
749///
750/// This cache is very similar to the stat cache used by pretokenized
751/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000752class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000753 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
754 CacheTy *Cache;
755
756 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000757public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000758 PCHStatCache(const unsigned char *Buckets,
759 const unsigned char *Base,
760 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000761 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000762 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
763 Cache = CacheTy::Create(Buckets, Base);
764 }
765
766 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Douglas Gregorc5046832009-04-27 18:38:38 +0000768 int stat(const char *path, struct stat *buf) {
769 // Do the lookup for the file's data in the PCH file.
770 CacheTy::iterator I = Cache->find(path);
771
772 // If we don't get a hit in the PCH file just forward to 'stat'.
773 if (I == Cache->end()) {
774 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000775 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000776 }
Mike Stump11289f42009-09-09 15:08:12 +0000777
Douglas Gregorc5046832009-04-27 18:38:38 +0000778 ++NumStatHits;
779 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000780
Douglas Gregorc5046832009-04-27 18:38:38 +0000781 if (!Data.hasStat)
782 return 1;
783
784 buf->st_ino = Data.ino;
785 buf->st_dev = Data.dev;
786 buf->st_mtime = Data.mtime;
787 buf->st_mode = Data.mode;
788 buf->st_size = Data.size;
789 return 0;
790 }
791};
792} // end anonymous namespace
793
794
Douglas Gregora7f71a92009-04-10 03:52:48 +0000795/// \brief Read the source manager block
Douglas Gregor92863e42009-04-10 23:10:45 +0000796PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000797 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000798
799 // Set the source-location entry cursor to the current position in
800 // the stream. This cursor will be used to read the contents of the
801 // source manager block initially, and then lazily read
802 // source-location entries as needed.
803 SLocEntryCursor = Stream;
804
805 // The stream itself is going to skip over the source manager block.
806 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000807 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000808 return Failure;
809 }
810
811 // Enter the source manager block.
812 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000813 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000814 return Failure;
815 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000816
Douglas Gregora7f71a92009-04-10 03:52:48 +0000817 RecordData Record;
818 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000819 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000820 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000821 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000822 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000823 return Failure;
824 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000825 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000826 }
Mike Stump11289f42009-09-09 15:08:12 +0000827
Douglas Gregora7f71a92009-04-10 03:52:48 +0000828 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
829 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000830 SLocEntryCursor.ReadSubBlockID();
831 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000832 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000833 return Failure;
834 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000835 continue;
836 }
Mike Stump11289f42009-09-09 15:08:12 +0000837
Douglas Gregora7f71a92009-04-10 03:52:48 +0000838 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000839 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000840 continue;
841 }
Mike Stump11289f42009-09-09 15:08:12 +0000842
Douglas Gregora7f71a92009-04-10 03:52:48 +0000843 // Read a record.
844 const char *BlobStart;
845 unsigned BlobLen;
846 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000847 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000848 default: // Default behavior: ignore.
849 break;
850
Chris Lattner184e65d2009-04-14 23:22:57 +0000851 case pch::SM_LINE_TABLE:
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000852 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000853 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000854 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000855
Douglas Gregor258ae542009-04-27 06:38:32 +0000856 case pch::SM_SLOC_FILE_ENTRY:
857 case pch::SM_SLOC_BUFFER_ENTRY:
858 case pch::SM_SLOC_INSTANTIATION_ENTRY:
859 // Once we hit one of the source location entries, we're done.
860 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000861 }
862 }
863}
864
Douglas Gregor258ae542009-04-27 06:38:32 +0000865/// \brief Read in the source location entry with the given ID.
866PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
867 if (ID == 0)
868 return Success;
869
870 if (ID > TotalNumSLocEntries) {
871 Error("source location entry ID out-of-range for PCH file");
872 return Failure;
873 }
874
875 ++NumSLocEntriesRead;
876 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
877 unsigned Code = SLocEntryCursor.ReadCode();
878 if (Code == llvm::bitc::END_BLOCK ||
879 Code == llvm::bitc::ENTER_SUBBLOCK ||
880 Code == llvm::bitc::DEFINE_ABBREV) {
881 Error("incorrectly-formatted source location entry in PCH file");
882 return Failure;
883 }
884
Douglas Gregor258ae542009-04-27 06:38:32 +0000885 RecordData Record;
886 const char *BlobStart;
887 unsigned BlobLen;
888 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
889 default:
890 Error("incorrectly-formatted source location entry in PCH file");
891 return Failure;
892
893 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000894 std::string Filename(BlobStart, BlobStart + BlobLen);
895 MaybeAddSystemRootToFilename(Filename);
896 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000897 if (File == 0) {
898 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000899 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000900 ErrorStr += "' referenced by PCH file";
901 Error(ErrorStr.c_str());
902 return Failure;
903 }
Mike Stump11289f42009-09-09 15:08:12 +0000904
Ted Kremenekabb1ddd2010-03-18 21:23:05 +0000905 if (Record.size() < 8) {
906 Error("source location entry is incorrect");
907 return Failure;
908 }
909
Douglas Gregor258ae542009-04-27 06:38:32 +0000910 FileID FID = SourceMgr.createFileID(File,
911 SourceLocation::getFromRawEncoding(Record[1]),
912 (SrcMgr::CharacteristicKind)Record[2],
913 ID, Record[0]);
914 if (Record[3])
915 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
916 .setHasLineDirectives();
917
Douglas Gregor5712ebc2010-03-16 16:35:32 +0000918 // Reconstruct header-search information for this file.
919 HeaderFileInfo HFI;
920 HFI.isImport = Record[4];
921 HFI.DirInfo = Record[5];
922 HFI.NumIncludes = Record[6];
923 HFI.ControllingMacroID = Record[7];
924 if (Listener)
925 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor258ae542009-04-27 06:38:32 +0000926 break;
927 }
928
929 case pch::SM_SLOC_BUFFER_ENTRY: {
930 const char *Name = BlobStart;
931 unsigned Offset = Record[0];
932 unsigned Code = SLocEntryCursor.ReadCode();
933 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000934 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +0000935 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000936
937 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
938 Error("PCH record has invalid code");
939 return Failure;
940 }
941
Douglas Gregor258ae542009-04-27 06:38:32 +0000942 llvm::MemoryBuffer *Buffer
Mike Stump11289f42009-09-09 15:08:12 +0000943 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor258ae542009-04-27 06:38:32 +0000944 BlobStart + BlobLen - 1,
945 Name);
946 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000947
Douglas Gregore6648fb2009-04-28 20:33:11 +0000948 if (strcmp(Name, "<built-in>") == 0) {
949 PCHPredefinesBufferID = BufferID;
950 PCHPredefines = BlobStart;
951 PCHPredefinesLen = BlobLen - 1;
952 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000953
954 break;
955 }
956
957 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +0000958 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +0000959 = SourceLocation::getFromRawEncoding(Record[1]);
960 SourceMgr.createInstantiationLoc(SpellingLoc,
961 SourceLocation::getFromRawEncoding(Record[2]),
962 SourceLocation::getFromRawEncoding(Record[3]),
963 Record[4],
964 ID,
965 Record[0]);
966 break;
Mike Stump11289f42009-09-09 15:08:12 +0000967 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000968 }
969
970 return Success;
971}
972
Chris Lattnere78a6be2009-04-27 01:05:14 +0000973/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
974/// specified cursor. Read the abbreviations that are at the top of the block
975/// and then leave the cursor pointing into the block.
976bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
977 unsigned BlockID) {
978 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000979 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +0000980 return Failure;
981 }
Mike Stump11289f42009-09-09 15:08:12 +0000982
Chris Lattnere78a6be2009-04-27 01:05:14 +0000983 while (true) {
984 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattnere78a6be2009-04-27 01:05:14 +0000986 // We expect all abbrevs to be at the start of the block.
987 if (Code != llvm::bitc::DEFINE_ABBREV)
988 return false;
989 Cursor.ReadAbbrevRecord();
990 }
991}
992
Douglas Gregorc3366a52009-04-21 23:56:24 +0000993void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000994 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +0000995
Douglas Gregorc3366a52009-04-21 23:56:24 +0000996 // Keep track of where we are in the stream, then jump back there
997 // after reading this macro.
998 SavedStreamPosition SavedPosition(Stream);
999
1000 Stream.JumpToBit(Offset);
1001 RecordData Record;
1002 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1003 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001004
Douglas Gregorc3366a52009-04-21 23:56:24 +00001005 while (true) {
1006 unsigned Code = Stream.ReadCode();
1007 switch (Code) {
1008 case llvm::bitc::END_BLOCK:
1009 return;
1010
1011 case llvm::bitc::ENTER_SUBBLOCK:
1012 // No known subblocks, always skip them.
1013 Stream.ReadSubBlockID();
1014 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001015 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001016 return;
1017 }
1018 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001019
Douglas Gregorc3366a52009-04-21 23:56:24 +00001020 case llvm::bitc::DEFINE_ABBREV:
1021 Stream.ReadAbbrevRecord();
1022 continue;
1023 default: break;
1024 }
1025
1026 // Read a record.
1027 Record.clear();
1028 pch::PreprocessorRecordTypes RecType =
1029 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1030 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001031 case pch::PP_MACRO_OBJECT_LIKE:
1032 case pch::PP_MACRO_FUNCTION_LIKE: {
1033 // If we already have a macro, that means that we've hit the end
1034 // of the definition of the macro we were looking for. We're
1035 // done.
1036 if (Macro)
1037 return;
1038
1039 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1040 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001041 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001042 return;
1043 }
1044 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1045 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001046
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001047 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001048 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001049
Douglas Gregorc3366a52009-04-21 23:56:24 +00001050 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1051 // Decode function-like macro info.
1052 bool isC99VarArgs = Record[3];
1053 bool isGNUVarArgs = Record[4];
1054 MacroArgs.clear();
1055 unsigned NumArgs = Record[5];
1056 for (unsigned i = 0; i != NumArgs; ++i)
1057 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1058
1059 // Install function-like macro info.
1060 MI->setIsFunctionLike();
1061 if (isC99VarArgs) MI->setIsC99Varargs();
1062 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001063 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001064 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001065 }
1066
1067 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001068 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001069
1070 // Remember that we saw this macro last so that we add the tokens that
1071 // form its body to it.
1072 Macro = MI;
1073 ++NumMacrosRead;
1074 break;
1075 }
Mike Stump11289f42009-09-09 15:08:12 +00001076
Douglas Gregorc3366a52009-04-21 23:56:24 +00001077 case pch::PP_TOKEN: {
1078 // If we see a TOKEN before a PP_MACRO_*, then the file is
1079 // erroneous, just pretend we didn't see this.
1080 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregorc3366a52009-04-21 23:56:24 +00001082 Token Tok;
1083 Tok.startToken();
1084 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1085 Tok.setLength(Record[1]);
1086 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1087 Tok.setIdentifierInfo(II);
1088 Tok.setKind((tok::TokenKind)Record[3]);
1089 Tok.setFlag((Token::TokenFlags)Record[4]);
1090 Macro->AddTokenToBody(Tok);
1091 break;
1092 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001093 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001094 }
1095}
1096
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001097void PCHReader::ReadDefinedMacros() {
1098 // If there was no preprocessor block, do nothing.
1099 if (!MacroCursor.getBitStreamReader())
1100 return;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001101
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001102 llvm::BitstreamCursor Cursor = MacroCursor;
1103 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1104 Error("malformed preprocessor block record in PCH file");
1105 return;
1106 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001107
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001108 RecordData Record;
1109 while (true) {
1110 unsigned Code = Cursor.ReadCode();
1111 if (Code == llvm::bitc::END_BLOCK) {
1112 if (Cursor.ReadBlockEnd())
1113 Error("error at end of preprocessor block in PCH file");
1114 return;
1115 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001116
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001117 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1118 // No known subblocks, always skip them.
1119 Cursor.ReadSubBlockID();
1120 if (Cursor.SkipBlock()) {
1121 Error("malformed block record in PCH file");
1122 return;
1123 }
1124 continue;
1125 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001126
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001127 if (Code == llvm::bitc::DEFINE_ABBREV) {
1128 Cursor.ReadAbbrevRecord();
1129 continue;
1130 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001131
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001132 // Read a record.
1133 const char *BlobStart;
1134 unsigned BlobLen;
1135 Record.clear();
1136 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1137 default: // Default behavior: ignore.
1138 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001139
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001140 case pch::PP_MACRO_OBJECT_LIKE:
1141 case pch::PP_MACRO_FUNCTION_LIKE:
1142 DecodeIdentifierInfo(Record[0]);
1143 break;
1144
1145 case pch::PP_TOKEN:
1146 // Ignore tokens.
1147 break;
1148 }
1149 }
1150}
1151
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001152/// \brief If we are loading a relocatable PCH file, and the filename is
1153/// not an absolute path, add the system root to the beginning of the file
1154/// name.
1155void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1156 // If this is not a relocatable PCH file, there's nothing to do.
1157 if (!RelocatablePCH)
1158 return;
Mike Stump11289f42009-09-09 15:08:12 +00001159
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001160 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001161 return;
1162
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001163 if (isysroot == 0) {
1164 // If no system root was given, default to '/'
1165 Filename.insert(Filename.begin(), '/');
1166 return;
1167 }
Mike Stump11289f42009-09-09 15:08:12 +00001168
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001169 unsigned Length = strlen(isysroot);
1170 if (isysroot[Length - 1] != '/')
1171 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001172
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001173 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1174}
1175
Mike Stump11289f42009-09-09 15:08:12 +00001176PCHReader::PCHReadResult
Douglas Gregoreda6a892009-04-26 00:07:37 +00001177PCHReader::ReadPCHBlock() {
Douglas Gregor55abb232009-04-10 20:39:37 +00001178 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001179 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001180 return Failure;
1181 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001182
1183 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001184 RecordData Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001185 while (!Stream.AtEndOfStream()) {
1186 unsigned Code = Stream.ReadCode();
1187 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001188 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001189 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001190 return Failure;
1191 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001192
Douglas Gregor55abb232009-04-10 20:39:37 +00001193 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001194 }
1195
1196 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1197 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001198 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001199 // We lazily load the decls block, but we want to set up the
1200 // DeclsCursor cursor to point into it. Clone our current bitcode
1201 // cursor to it, enter the block and read the abbrevs in that block.
1202 // With the main cursor, we just skip over it.
1203 DeclsCursor = Stream;
1204 if (Stream.SkipBlock() || // Skip with the main cursor.
1205 // Read the abbrevs.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001206 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001207 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001208 return Failure;
1209 }
1210 break;
Mike Stump11289f42009-09-09 15:08:12 +00001211
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001212 case pch::PREPROCESSOR_BLOCK_ID:
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001213 MacroCursor = Stream;
1214 if (PP)
1215 PP->setExternalSource(this);
1216
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001217 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001218 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001219 return Failure;
1220 }
1221 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001222
Douglas Gregora7f71a92009-04-10 03:52:48 +00001223 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001224 switch (ReadSourceManagerBlock()) {
1225 case Success:
1226 break;
1227
1228 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001229 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001230 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001231
1232 case IgnorePCH:
1233 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001234 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001235 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001236 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001237 continue;
1238 }
1239
1240 if (Code == llvm::bitc::DEFINE_ABBREV) {
1241 Stream.ReadAbbrevRecord();
1242 continue;
1243 }
1244
1245 // Read and process a record.
1246 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001247 const char *BlobStart = 0;
1248 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001249 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001250 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001251 default: // Default behavior: ignore.
1252 break;
1253
1254 case pch::TYPE_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001255 if (!TypesLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001256 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001257 return Failure;
1258 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001259 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001260 TypesLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001261 break;
1262
1263 case pch::DECL_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001264 if (!DeclsLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001265 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001266 return Failure;
1267 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001268 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001269 DeclsLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001270 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001271
1272 case pch::LANGUAGE_OPTIONS:
1273 if (ParseLanguageOptions(Record))
1274 return IgnorePCH;
1275 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001276
Douglas Gregor7b71e632009-04-27 22:23:34 +00001277 case pch::METADATA: {
1278 if (Record[0] != pch::VERSION_MAJOR) {
1279 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1280 : diag::warn_pch_version_too_new);
1281 return IgnorePCH;
1282 }
1283
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001284 RelocatablePCH = Record[4];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001285 if (Listener) {
1286 std::string TargetTriple(BlobStart, BlobLen);
1287 if (Listener->ReadTargetTriple(TargetTriple))
1288 return IgnorePCH;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001289 }
1290 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001291 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001292
1293 case pch::IDENTIFIER_TABLE:
Douglas Gregora868bbd2009-04-21 22:25:48 +00001294 IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001295 if (Record[0]) {
Mike Stump11289f42009-09-09 15:08:12 +00001296 IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001297 = PCHIdentifierLookupTable::Create(
Douglas Gregora868bbd2009-04-21 22:25:48 +00001298 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001299 (const unsigned char *)IdentifierTableData,
Douglas Gregora868bbd2009-04-21 22:25:48 +00001300 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001301 if (PP)
1302 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001303 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001304 break;
1305
1306 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001307 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001308 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001309 return Failure;
1310 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001311 IdentifierOffsets = (const uint32_t *)BlobStart;
1312 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001313 if (PP)
1314 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001315 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001316
1317 case pch::EXTERNAL_DEFINITIONS:
1318 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001319 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001320 return Failure;
1321 }
1322 ExternalDefinitions.swap(Record);
1323 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001324
Douglas Gregor652d82a2009-04-18 05:55:16 +00001325 case pch::SPECIAL_TYPES:
1326 SpecialTypes.swap(Record);
1327 break;
1328
Douglas Gregor08f01292009-04-17 22:13:46 +00001329 case pch::STATISTICS:
1330 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001331 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001332 TotalLexicalDeclContexts = Record[2];
1333 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001334 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001335
Douglas Gregord4df8652009-04-22 22:02:47 +00001336 case pch::TENTATIVE_DEFINITIONS:
1337 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001338 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001339 return Failure;
1340 }
1341 TentativeDefinitions.swap(Record);
1342 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001343
Tanya Lattner90073802010-02-12 00:07:30 +00001344 case pch::UNUSED_STATIC_FUNCS:
1345 if (!UnusedStaticFuncs.empty()) {
1346 Error("duplicate UNUSED_STATIC_FUNCS record in PCH file");
1347 return Failure;
1348 }
1349 UnusedStaticFuncs.swap(Record);
1350 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001351
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001352 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1353 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001354 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001355 return Failure;
1356 }
1357 LocallyScopedExternalDecls.swap(Record);
1358 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001359
Douglas Gregor95c13f52009-04-25 17:48:32 +00001360 case pch::SELECTOR_OFFSETS:
1361 SelectorOffsets = (const uint32_t *)BlobStart;
1362 TotalNumSelectors = Record[0];
1363 SelectorsLoaded.resize(TotalNumSelectors);
1364 break;
1365
Douglas Gregorc78d3462009-04-24 21:10:55 +00001366 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001367 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1368 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001369 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001370 = PCHMethodPoolLookupTable::Create(
1371 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001372 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001373 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001374 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001375 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001376
1377 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001378 if (!Record.empty() && Listener)
1379 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001380 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001381
1382 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001383 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001384 TotalNumSLocEntries = Record[0];
Douglas Gregord54f3a12009-10-05 21:07:28 +00001385 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001386 break;
1387
1388 case pch::SOURCE_LOCATION_PRELOADS:
1389 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1390 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1391 if (Result != Success)
1392 return Result;
1393 }
1394 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001395
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001396 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001397 PCHStatCache *MyStatCache =
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001398 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1399 (const unsigned char *)BlobStart,
1400 NumStatHits, NumStatMisses);
1401 FileMgr.addStatCache(MyStatCache);
1402 StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001403 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001404 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001405
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001406 case pch::EXT_VECTOR_DECLS:
1407 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001408 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001409 return Failure;
1410 }
1411 ExtVectorDecls.swap(Record);
1412 break;
1413
Douglas Gregor45fe0362009-05-12 01:31:05 +00001414 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001415 ActualOriginalFileName.assign(BlobStart, BlobLen);
1416 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001417 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001418 break;
Mike Stump11289f42009-09-09 15:08:12 +00001419
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001420 case pch::COMMENT_RANGES:
1421 Comments = (SourceRange *)BlobStart;
1422 NumComments = BlobLen / sizeof(SourceRange);
1423 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001424
Ted Kremenek17437132010-01-22 20:59:36 +00001425 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek8bd09292010-02-12 23:31:14 +00001426 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek2377a0e2010-01-22 20:55:35 +00001427 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Ted Kremenek8bd09292010-02-12 23:31:14 +00001428 if (llvm::StringRef(CurBranch) != PCHBranch) {
Douglas Gregord54f3a12009-10-05 21:07:28 +00001429 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1430 return IgnorePCH;
1431 }
1432 break;
1433 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001434 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001435 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001436 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001437 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001438}
1439
Douglas Gregor92863e42009-04-10 23:10:45 +00001440PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001441 // Set the PCH file name.
1442 this->FileName = FileName;
1443
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001444 // Open the PCH file.
Daniel Dunbar2d925eb2009-09-22 05:38:01 +00001445 //
1446 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001447 std::string ErrStr;
Daniel Dunbar69914f42009-11-10 00:46:19 +00001448 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregor92863e42009-04-10 23:10:45 +00001449 if (!Buffer) {
1450 Error(ErrStr.c_str());
1451 return IgnorePCH;
1452 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001453
1454 // Initialize the stream
Mike Stump11289f42009-09-09 15:08:12 +00001455 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattner9356ace2009-04-26 20:59:20 +00001456 (const unsigned char *)Buffer->getBufferEnd());
1457 Stream.init(StreamFile);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001458
1459 // Sniff for the signature.
1460 if (Stream.Read(8) != 'C' ||
1461 Stream.Read(8) != 'P' ||
1462 Stream.Read(8) != 'C' ||
Douglas Gregor92863e42009-04-10 23:10:45 +00001463 Stream.Read(8) != 'H') {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001464 Diag(diag::err_not_a_pch_file) << FileName;
1465 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001466 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001467
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001468 while (!Stream.AtEndOfStream()) {
1469 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001470
Douglas Gregor92863e42009-04-10 23:10:45 +00001471 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001472 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001473 return Failure;
1474 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001475
1476 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001477
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001478 // We only know the PCH subblock ID.
1479 switch (BlockID) {
1480 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001481 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001482 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001483 return Failure;
1484 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001485 break;
1486 case pch::PCH_BLOCK_ID:
Douglas Gregoreda6a892009-04-26 00:07:37 +00001487 switch (ReadPCHBlock()) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001488 case Success:
1489 break;
1490
1491 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001492 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001493
1494 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001495 // FIXME: We could consider reading through to the end of this
1496 // PCH block, skipping subblocks, to see if there are other
1497 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001498
1499 // Clear out any preallocated source location entries, so that
1500 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001501 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001502
1503 // Remove the stat cache.
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001504 if (StatCache)
1505 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001506
Douglas Gregor92863e42009-04-10 23:10:45 +00001507 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001508 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001509 break;
1510 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001511 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001512 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001513 return Failure;
1514 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001515 break;
1516 }
Mike Stump11289f42009-09-09 15:08:12 +00001517 }
1518
Douglas Gregore6648fb2009-04-28 20:33:11 +00001519 // Check the predefines buffer.
Daniel Dunbar20a682d2009-11-11 00:52:11 +00001520 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregore6648fb2009-04-28 20:33:11 +00001521 PCHPredefinesBufferID))
1522 return IgnorePCH;
Mike Stump11289f42009-09-09 15:08:12 +00001523
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001524 if (PP) {
Zhongxing Xu3f51f412009-07-18 09:26:51 +00001525 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001526 // PCH file is read, so there may be some identifiers that were
1527 // loaded into the IdentifierTable before we intercepted the
1528 // creation of identifiers. Iterate through the list of known
1529 // identifiers and determine whether we have to establish
1530 // preprocessor definitions or top-level identifier declaration
1531 // chains for those identifiers.
1532 //
1533 // We copy the IdentifierInfo pointers to a small vector first,
1534 // since de-serializing declarations or macro definitions can add
1535 // new entries into the identifier table, invalidating the
1536 // iterators.
1537 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1538 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1539 IdEnd = PP->getIdentifierTable().end();
1540 Id != IdEnd; ++Id)
1541 Identifiers.push_back(Id->second);
Mike Stump11289f42009-09-09 15:08:12 +00001542 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001543 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1544 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1545 IdentifierInfo *II = Identifiers[I];
1546 // Look in the on-disk hash table for an entry for
1547 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001548 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001549 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1550 if (Pos == IdTable->end())
1551 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001552
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001553 // Dereferencing the iterator has the effect of populating the
1554 // IdentifierInfo node with the various declarations it needs.
1555 (void)*Pos;
1556 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001557 }
1558
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001559 if (Context)
1560 InitializeContext(*Context);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001561
Douglas Gregora868bbd2009-04-21 22:25:48 +00001562 return Success;
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001563}
1564
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001565void PCHReader::InitializeContext(ASTContext &Ctx) {
1566 Context = &Ctx;
1567 assert(Context && "Passed null context!");
1568
1569 assert(PP && "Forgot to set Preprocessor ?");
1570 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1571 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001572 PP->setExternalSource(this);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001573
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001574 // Load the translation unit declaration
1575 ReadDeclRecord(DeclOffsets[0], 0);
1576
1577 // Load the special types.
1578 Context->setBuiltinVaListType(
1579 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1580 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1581 Context->setObjCIdType(GetType(Id));
1582 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1583 Context->setObjCSelType(GetType(Sel));
1584 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1585 Context->setObjCProtoType(GetType(Proto));
1586 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1587 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001588
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001589 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1590 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001591 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001592 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1593 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001594 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1595 QualType FileType = GetType(File);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001596 if (FileType.isNull()) {
1597 Error("FILE type is NULL");
1598 return;
1599 }
John McCall9dd450b2009-09-21 23:43:11 +00001600 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001601 Context->setFILEDecl(Typedef->getDecl());
1602 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001603 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001604 if (!Tag) {
1605 Error("Invalid FILE type in PCH file");
1606 return;
1607 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00001608 Context->setFILEDecl(Tag->getDecl());
1609 }
1610 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001611 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1612 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001613 if (Jmp_bufType.isNull()) {
1614 Error("jmp_bug type is NULL");
1615 return;
1616 }
John McCall9dd450b2009-09-21 23:43:11 +00001617 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001618 Context->setjmp_bufDecl(Typedef->getDecl());
1619 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001620 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001621 if (!Tag) {
1622 Error("Invalid jmp_bug type in PCH file");
1623 return;
1624 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001625 Context->setjmp_bufDecl(Tag->getDecl());
1626 }
1627 }
1628 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1629 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001630 if (Sigjmp_bufType.isNull()) {
1631 Error("sigjmp_buf type is NULL");
1632 return;
1633 }
John McCall9dd450b2009-09-21 23:43:11 +00001634 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001635 Context->setsigjmp_bufDecl(Typedef->getDecl());
1636 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001637 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001638 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1639 Context->setsigjmp_bufDecl(Tag->getDecl());
1640 }
1641 }
Mike Stump11289f42009-09-09 15:08:12 +00001642 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001643 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1644 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001645 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001646 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1647 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001648#if 0
1649 // FIXME. Accommodate for this in several PCH/Index tests
1650 if (unsigned ObjCSelRedef
1651 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00001652 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001653#endif
Mike Stumpd0153282009-10-20 02:12:22 +00001654 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1655 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00001656 if (unsigned String
1657 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1658 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001659}
1660
Douglas Gregor45fe0362009-05-12 01:31:05 +00001661/// \brief Retrieve the name of the original source file name
1662/// directly from the PCH file, without actually loading the PCH
1663/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00001664std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1665 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00001666 // Open the PCH file.
1667 std::string ErrStr;
1668 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1669 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1670 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001671 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001672 return std::string();
1673 }
1674
1675 // Initialize the stream
1676 llvm::BitstreamReader StreamFile;
1677 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001678 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001679 (const unsigned char *)Buffer->getBufferEnd());
1680 Stream.init(StreamFile);
1681
1682 // Sniff for the signature.
1683 if (Stream.Read(8) != 'C' ||
1684 Stream.Read(8) != 'P' ||
1685 Stream.Read(8) != 'C' ||
1686 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001687 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001688 return std::string();
1689 }
1690
1691 RecordData Record;
1692 while (!Stream.AtEndOfStream()) {
1693 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001694
Douglas Gregor45fe0362009-05-12 01:31:05 +00001695 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1696 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001697
Douglas Gregor45fe0362009-05-12 01:31:05 +00001698 // We only know the PCH subblock ID.
1699 switch (BlockID) {
1700 case pch::PCH_BLOCK_ID:
1701 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001702 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001703 return std::string();
1704 }
1705 break;
Mike Stump11289f42009-09-09 15:08:12 +00001706
Douglas Gregor45fe0362009-05-12 01:31:05 +00001707 default:
1708 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001709 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001710 return std::string();
1711 }
1712 break;
1713 }
1714 continue;
1715 }
1716
1717 if (Code == llvm::bitc::END_BLOCK) {
1718 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001719 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001720 return std::string();
1721 }
1722 continue;
1723 }
1724
1725 if (Code == llvm::bitc::DEFINE_ABBREV) {
1726 Stream.ReadAbbrevRecord();
1727 continue;
1728 }
1729
1730 Record.clear();
1731 const char *BlobStart = 0;
1732 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001733 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00001734 == pch::ORIGINAL_FILE_NAME)
1735 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00001736 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00001737
1738 return std::string();
1739}
1740
Douglas Gregor55abb232009-04-10 20:39:37 +00001741/// \brief Parse the record that corresponds to a LangOptions data
1742/// structure.
1743///
1744/// This routine compares the language options used to generate the
1745/// PCH file against the language options set for the current
1746/// compilation. For each option, we classify differences between the
1747/// two compiler states as either "benign" or "important". Benign
1748/// differences don't matter, and we accept them without complaint
1749/// (and without modifying the language options). Differences between
1750/// the states for important options cause the PCH file to be
1751/// unusable, so we emit a warning and return true to indicate that
1752/// there was an error.
1753///
1754/// \returns true if the PCH file is unacceptable, false otherwise.
1755bool PCHReader::ParseLanguageOptions(
1756 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001757 if (Listener) {
1758 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00001759
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001760 #define PARSE_LANGOPT(Option) \
1761 LangOpts.Option = Record[Idx]; \
1762 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00001763
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001764 unsigned Idx = 0;
1765 PARSE_LANGOPT(Trigraphs);
1766 PARSE_LANGOPT(BCPLComment);
1767 PARSE_LANGOPT(DollarIdents);
1768 PARSE_LANGOPT(AsmPreprocessor);
1769 PARSE_LANGOPT(GNUMode);
1770 PARSE_LANGOPT(ImplicitInt);
1771 PARSE_LANGOPT(Digraphs);
1772 PARSE_LANGOPT(HexFloats);
1773 PARSE_LANGOPT(C99);
1774 PARSE_LANGOPT(Microsoft);
1775 PARSE_LANGOPT(CPlusPlus);
1776 PARSE_LANGOPT(CPlusPlus0x);
1777 PARSE_LANGOPT(CXXOperatorNames);
1778 PARSE_LANGOPT(ObjC1);
1779 PARSE_LANGOPT(ObjC2);
1780 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00001781 PARSE_LANGOPT(ObjCNonFragileABI2);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001782 PARSE_LANGOPT(PascalStrings);
1783 PARSE_LANGOPT(WritableStrings);
1784 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00001785 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001786 PARSE_LANGOPT(Exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +00001787 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001788 PARSE_LANGOPT(NeXTRuntime);
1789 PARSE_LANGOPT(Freestanding);
1790 PARSE_LANGOPT(NoBuiltin);
1791 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00001792 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001793 PARSE_LANGOPT(Blocks);
1794 PARSE_LANGOPT(EmitAllDecls);
1795 PARSE_LANGOPT(MathErrno);
1796 PARSE_LANGOPT(OverflowChecking);
1797 PARSE_LANGOPT(HeinousExtensions);
1798 PARSE_LANGOPT(Optimize);
1799 PARSE_LANGOPT(OptimizeSize);
1800 PARSE_LANGOPT(Static);
1801 PARSE_LANGOPT(PICLevel);
1802 PARSE_LANGOPT(GNUInline);
1803 PARSE_LANGOPT(NoInline);
1804 PARSE_LANGOPT(AccessControl);
1805 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00001806 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001807 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1808 ++Idx;
1809 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1810 ++Idx;
Daniel Dunbar143021e2009-09-21 04:16:19 +00001811 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1812 Record[Idx]);
1813 ++Idx;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001814 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00001815 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00001816 PARSE_LANGOPT(CatchUndefined);
1817 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001818 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00001819
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001820 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00001821 }
Douglas Gregor55abb232009-04-10 20:39:37 +00001822
1823 return false;
1824}
1825
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001826void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1827 Comments.resize(NumComments);
1828 std::copy(this->Comments, this->Comments + NumComments,
1829 Comments.begin());
1830}
1831
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001832/// \brief Read and return the type at the given offset.
1833///
1834/// This routine actually reads the record corresponding to the type
1835/// at the given offset in the bitstream. It is a helper routine for
1836/// GetType, which deals with reading type IDs.
1837QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001838 // Keep track of where we are in the stream, then jump back there
1839 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001840 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001841
Douglas Gregor1342e842009-07-06 18:54:52 +00001842 // Note that we are loading a type record.
1843 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00001844
Douglas Gregor12bfa382009-10-17 00:13:19 +00001845 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001846 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00001847 unsigned Code = DeclsCursor.ReadCode();
1848 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00001849 case pch::TYPE_EXT_QUAL: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001850 if (Record.size() != 2) {
1851 Error("Incorrect encoding of extended qualifier type");
1852 return QualType();
1853 }
Douglas Gregor455b8f42009-04-15 22:00:08 +00001854 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00001855 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1856 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00001857 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001858
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001859 case pch::TYPE_COMPLEX: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001860 if (Record.size() != 1) {
1861 Error("Incorrect encoding of complex type");
1862 return QualType();
1863 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001864 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001865 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001866 }
1867
1868 case pch::TYPE_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001869 if (Record.size() != 1) {
1870 Error("Incorrect encoding of pointer type");
1871 return QualType();
1872 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001873 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001874 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001875 }
1876
1877 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001878 if (Record.size() != 1) {
1879 Error("Incorrect encoding of block pointer type");
1880 return QualType();
1881 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001882 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001883 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001884 }
1885
1886 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001887 if (Record.size() != 1) {
1888 Error("Incorrect encoding of lvalue reference type");
1889 return QualType();
1890 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001891 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001892 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001893 }
1894
1895 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001896 if (Record.size() != 1) {
1897 Error("Incorrect encoding of rvalue reference type");
1898 return QualType();
1899 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001900 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001901 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001902 }
1903
1904 case pch::TYPE_MEMBER_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001905 if (Record.size() != 1) {
1906 Error("Incorrect encoding of member pointer type");
1907 return QualType();
1908 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001909 QualType PointeeType = GetType(Record[0]);
1910 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001911 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001912 }
1913
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001914 case pch::TYPE_CONSTANT_ARRAY: {
1915 QualType ElementType = GetType(Record[0]);
1916 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1917 unsigned IndexTypeQuals = Record[2];
1918 unsigned Idx = 3;
1919 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00001920 return Context->getConstantArrayType(ElementType, Size,
1921 ASM, IndexTypeQuals);
1922 }
1923
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001924 case pch::TYPE_INCOMPLETE_ARRAY: {
1925 QualType ElementType = GetType(Record[0]);
1926 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1927 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00001928 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001929 }
1930
1931 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001932 QualType ElementType = GetType(Record[0]);
1933 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1934 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00001935 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1936 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001937 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00001938 ASM, IndexTypeQuals,
1939 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001940 }
1941
1942 case pch::TYPE_VECTOR: {
John Thompson22334602010-02-05 00:12:22 +00001943 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001944 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001945 return QualType();
1946 }
1947
1948 QualType ElementType = GetType(Record[0]);
1949 unsigned NumElements = Record[1];
John Thompson22334602010-02-05 00:12:22 +00001950 bool AltiVec = Record[2];
1951 bool Pixel = Record[3];
1952 return Context->getVectorType(ElementType, NumElements, AltiVec, Pixel);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001953 }
1954
1955 case pch::TYPE_EXT_VECTOR: {
John Thompson22334602010-02-05 00:12:22 +00001956 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001957 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001958 return QualType();
1959 }
1960
1961 QualType ElementType = GetType(Record[0]);
1962 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001963 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001964 }
1965
1966 case pch::TYPE_FUNCTION_NO_PROTO: {
Douglas Gregor8c940862010-01-18 17:14:39 +00001967 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001968 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001969 return QualType();
1970 }
1971 QualType ResultType = GetType(Record[0]);
Douglas Gregor8c940862010-01-18 17:14:39 +00001972 return Context->getFunctionNoProtoType(ResultType, Record[1],
1973 (CallingConv)Record[2]);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001974 }
1975
1976 case pch::TYPE_FUNCTION_PROTO: {
1977 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00001978 bool NoReturn = Record[1];
Douglas Gregor8c940862010-01-18 17:14:39 +00001979 CallingConv CallConv = (CallingConv)Record[2];
1980 unsigned Idx = 3;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001981 unsigned NumParams = Record[Idx++];
1982 llvm::SmallVector<QualType, 16> ParamTypes;
1983 for (unsigned I = 0; I != NumParams; ++I)
1984 ParamTypes.push_back(GetType(Record[Idx++]));
1985 bool isVariadic = Record[Idx++];
1986 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001987 bool hasExceptionSpec = Record[Idx++];
1988 bool hasAnyExceptionSpec = Record[Idx++];
1989 unsigned NumExceptions = Record[Idx++];
1990 llvm::SmallVector<QualType, 2> Exceptions;
1991 for (unsigned I = 0; I != NumExceptions; ++I)
1992 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00001993 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001994 isVariadic, Quals, hasExceptionSpec,
1995 hasAnyExceptionSpec, NumExceptions,
Douglas Gregor8c940862010-01-18 17:14:39 +00001996 Exceptions.data(), NoReturn, CallConv);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001997 }
1998
John McCallb96ec562009-12-04 22:46:56 +00001999 case pch::TYPE_UNRESOLVED_USING:
2000 return Context->getTypeDeclType(
2001 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2002
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002003 case pch::TYPE_TYPEDEF:
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002004 if (Record.size() != 1) {
2005 Error("incorrect encoding of typedef type");
2006 return QualType();
2007 }
Chris Lattner8575daa2009-04-27 21:45:14 +00002008 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002009
2010 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner8575daa2009-04-27 21:45:14 +00002011 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002012
2013 case pch::TYPE_TYPEOF: {
2014 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002015 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002016 return QualType();
2017 }
2018 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002019 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002020 }
Mike Stump11289f42009-09-09 15:08:12 +00002021
Anders Carlsson81df7b82009-06-24 19:06:50 +00002022 case pch::TYPE_DECLTYPE:
2023 return Context->getDecltypeType(ReadTypeExpr());
2024
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002025 case pch::TYPE_RECORD:
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002026 if (Record.size() != 1) {
2027 Error("incorrect encoding of record type");
2028 return QualType();
2029 }
Chris Lattner8575daa2009-04-27 21:45:14 +00002030 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002031
Douglas Gregor1daeb692009-04-13 18:14:40 +00002032 case pch::TYPE_ENUM:
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002033 if (Record.size() != 1) {
2034 Error("incorrect encoding of enum type");
2035 return QualType();
2036 }
Chris Lattner8575daa2009-04-27 21:45:14 +00002037 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor1daeb692009-04-13 18:14:40 +00002038
John McCallfcc33b02009-09-05 00:15:47 +00002039 case pch::TYPE_ELABORATED: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002040 if (Record.size() != 2) {
2041 Error("incorrect encoding of elaborated type");
2042 return QualType();
2043 }
John McCallfcc33b02009-09-05 00:15:47 +00002044 unsigned Tag = Record[1];
2045 return Context->getElaboratedType(GetType(Record[0]),
2046 (ElaboratedType::TagKind) Tag);
2047 }
2048
Steve Naroffc277ad12009-07-18 15:33:26 +00002049 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00002050 unsigned Idx = 0;
2051 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
2052 unsigned NumProtos = Record[Idx++];
2053 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2054 for (unsigned I = 0; I != NumProtos; ++I)
2055 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc277ad12009-07-18 15:33:26 +00002056 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00002057 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002058
Steve Narofffb4330f2009-06-17 22:40:22 +00002059 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00002060 unsigned Idx = 0;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002061 QualType OIT = GetType(Record[Idx++]);
Chris Lattner6e054af2009-04-22 06:40:03 +00002062 unsigned NumProtos = Record[Idx++];
2063 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2064 for (unsigned I = 0; I != NumProtos; ++I)
2065 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff7cae42b2009-07-10 23:34:53 +00002066 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattner6e054af2009-04-22 06:40:03 +00002067 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00002068
John McCallcebee162009-10-18 09:09:24 +00002069 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2070 unsigned Idx = 0;
2071 QualType Parm = GetType(Record[Idx++]);
2072 QualType Replacement = GetType(Record[Idx++]);
2073 return
2074 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2075 Replacement);
2076 }
John McCalle78aac42010-03-10 03:28:59 +00002077
2078 case pch::TYPE_INJECTED_CLASS_NAME: {
2079 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2080 QualType TST = GetType(Record[1]); // probably derivable
2081 return Context->getInjectedClassNameType(D, TST);
2082 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002083 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002084 // Suppress a GCC warning
2085 return QualType();
2086}
2087
John McCall8f115c62009-10-16 21:56:05 +00002088namespace {
2089
2090class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2091 PCHReader &Reader;
2092 const PCHReader::RecordData &Record;
2093 unsigned &Idx;
2094
2095public:
2096 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2097 unsigned &Idx)
2098 : Reader(Reader), Record(Record), Idx(Idx) { }
2099
John McCall17001972009-10-18 01:05:36 +00002100 // We want compile-time assurance that we've enumerated all of
2101 // these, so unfortunately we have to declare them first, then
2102 // define them out-of-line.
2103#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002104#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002105 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002106#include "clang/AST/TypeLocNodes.def"
2107
John McCall17001972009-10-18 01:05:36 +00002108 void VisitFunctionTypeLoc(FunctionTypeLoc);
2109 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002110};
2111
2112}
2113
John McCall17001972009-10-18 01:05:36 +00002114void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002115 // nothing to do
2116}
John McCall17001972009-10-18 01:05:36 +00002117void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +00002118 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2119 if (TL.needsExtraLocalData()) {
2120 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2121 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2122 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2123 TL.setModeAttr(Record[Idx++]);
2124 }
John McCall8f115c62009-10-16 21:56:05 +00002125}
John McCall17001972009-10-18 01:05:36 +00002126void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2127 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002128}
John McCall17001972009-10-18 01:05:36 +00002129void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2130 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002131}
John McCall17001972009-10-18 01:05:36 +00002132void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2133 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002134}
John McCall17001972009-10-18 01:05:36 +00002135void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2136 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002137}
John McCall17001972009-10-18 01:05:36 +00002138void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2139 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002140}
John McCall17001972009-10-18 01:05:36 +00002141void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2142 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002143}
John McCall17001972009-10-18 01:05:36 +00002144void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2145 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2146 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002147 if (Record[Idx++])
John McCall17001972009-10-18 01:05:36 +00002148 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor12bfa382009-10-17 00:13:19 +00002149 else
John McCall17001972009-10-18 01:05:36 +00002150 TL.setSizeExpr(0);
2151}
2152void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2153 VisitArrayTypeLoc(TL);
2154}
2155void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2156 VisitArrayTypeLoc(TL);
2157}
2158void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2159 VisitArrayTypeLoc(TL);
2160}
2161void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2162 DependentSizedArrayTypeLoc TL) {
2163 VisitArrayTypeLoc(TL);
2164}
2165void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2166 DependentSizedExtVectorTypeLoc TL) {
2167 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2168}
2169void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2170 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2171}
2172void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2173 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2174}
2175void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2176 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2177 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2178 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002179 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002180 }
2181}
2182void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2183 VisitFunctionTypeLoc(TL);
2184}
2185void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2186 VisitFunctionTypeLoc(TL);
2187}
John McCallb96ec562009-12-04 22:46:56 +00002188void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2189 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2190}
John McCall17001972009-10-18 01:05:36 +00002191void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2192 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2193}
2194void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002195 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2196 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2197 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002198}
2199void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002200 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2201 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2202 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2203 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002204}
2205void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2206 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2207}
2208void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2209 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2210}
2211void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2212 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2213}
2214void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2215 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2216}
2217void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2218 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2219}
John McCallcebee162009-10-18 09:09:24 +00002220void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2221 SubstTemplateTypeParmTypeLoc TL) {
2222 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2223}
John McCall17001972009-10-18 01:05:36 +00002224void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2225 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002226 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2227 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2228 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2229 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2230 TL.setArgLocInfo(i,
2231 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2232 Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002233}
2234void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2235 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2236}
John McCalle78aac42010-03-10 03:28:59 +00002237void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2238 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2239}
John McCall17001972009-10-18 01:05:36 +00002240void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2241 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2242}
2243void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2244 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002245 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2246 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2247 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2248 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002249}
John McCallfc93cf92009-10-22 22:37:11 +00002250void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2251 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2252 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2253 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2254 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2255 TL.setHasProtocolsAsWritten(Record[Idx++]);
2256 if (TL.hasProtocolsAsWritten())
2257 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2258 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2259}
John McCall8f115c62009-10-16 21:56:05 +00002260
John McCallbcd03502009-12-07 02:54:59 +00002261TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002262 unsigned &Idx) {
2263 QualType InfoTy = GetType(Record[Idx++]);
2264 if (InfoTy.isNull())
2265 return 0;
2266
John McCallbcd03502009-12-07 02:54:59 +00002267 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCall8f115c62009-10-16 21:56:05 +00002268 TypeLocReader TLR(*this, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002269 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002270 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002271 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002272}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002273
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002274QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002275 unsigned FastQuals = ID & Qualifiers::FastMask;
2276 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002277
2278 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2279 QualType T;
2280 switch ((pch::PredefinedTypeIDs)Index) {
2281 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002282 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2283 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002284
2285 case pch::PREDEF_TYPE_CHAR_U_ID:
2286 case pch::PREDEF_TYPE_CHAR_S_ID:
2287 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002288 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002289 break;
2290
Chris Lattner8575daa2009-04-27 21:45:14 +00002291 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2292 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2293 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2294 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2295 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002296 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002297 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2298 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2299 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2300 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2301 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2302 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002303 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002304 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2305 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2306 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2307 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2308 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002309 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002310 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2311 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002312 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2313 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002314 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002315 }
2316
2317 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002318 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002319 }
2320
2321 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002322 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall8ccfcb52009-09-24 19:53:00 +00002323 if (TypesLoaded[Index].isNull())
2324 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump11289f42009-09-09 15:08:12 +00002325
John McCall8ccfcb52009-09-24 19:53:00 +00002326 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002327}
2328
John McCall0ad16662009-10-29 08:12:44 +00002329TemplateArgumentLocInfo
2330PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2331 const RecordData &Record,
2332 unsigned &Index) {
2333 switch (Kind) {
2334 case TemplateArgument::Expression:
2335 return ReadDeclExpr();
2336 case TemplateArgument::Type:
John McCallbcd03502009-12-07 02:54:59 +00002337 return GetTypeSourceInfo(Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002338 case TemplateArgument::Template: {
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00002339 SourceLocation
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002340 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2341 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2342 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2343 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2344 TemplateNameLoc);
2345 }
John McCall0ad16662009-10-29 08:12:44 +00002346 case TemplateArgument::Null:
2347 case TemplateArgument::Integral:
2348 case TemplateArgument::Declaration:
2349 case TemplateArgument::Pack:
2350 return TemplateArgumentLocInfo();
2351 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002352 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002353 return TemplateArgumentLocInfo();
2354}
2355
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002356Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002357 if (ID == 0)
2358 return 0;
2359
Douglas Gregor745ed142009-04-25 18:35:21 +00002360 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002361 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002362 return 0;
2363 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002364
Douglas Gregor745ed142009-04-25 18:35:21 +00002365 unsigned Index = ID - 1;
2366 if (!DeclsLoaded[Index])
2367 ReadDeclRecord(DeclOffsets[Index], Index);
2368
2369 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002370}
2371
Chris Lattner9c28af02009-04-27 05:46:25 +00002372/// \brief Resolve the offset of a statement into a statement.
2373///
2374/// This operation will read a new statement from the external
2375/// source each time it is called, and is meant to be used via a
2376/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2377Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002378 // Since we know tha this statement is part of a decl, make sure to use the
2379 // decl cursor to read it.
2380 DeclsCursor.JumpToBit(Offset);
2381 return ReadStmt(DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002382}
2383
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002384bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002385 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002386 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002387 "DeclContext has no lexical decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002388
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002389 uint64_t Offset = DeclContextOffsets[DC].first;
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002390 if (Offset == 0) {
2391 Error("DeclContext has no lexical decls in storage");
2392 return true;
2393 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002394
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002395 // Keep track of where we are in the stream, then jump back there
2396 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002397 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002398
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002399 // Load the record containing all of the declarations lexically in
2400 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002401 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002402 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002403 unsigned Code = DeclsCursor.ReadCode();
2404 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002405 if (RecCode != pch::DECL_CONTEXT_LEXICAL) {
2406 Error("Expected lexical block");
2407 return true;
2408 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002409
2410 // Load all of the declaration IDs
2411 Decls.clear();
2412 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002413 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002414 return false;
2415}
2416
2417bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner72405d62009-04-27 07:35:40 +00002418 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002419 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002420 "DeclContext has no visible decls in storage");
2421 uint64_t Offset = DeclContextOffsets[DC].second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002422 if (Offset == 0) {
2423 Error("DeclContext has no visible decls in storage");
2424 return true;
2425 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002426
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002427 // Keep track of where we are in the stream, then jump back there
2428 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002429 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002430
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002431 // Load the record containing all of the declarations visible in
2432 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002433 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002434 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002435 unsigned Code = DeclsCursor.ReadCode();
2436 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002437 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2438 Error("Expected visible block");
2439 return true;
2440 }
2441
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002442 if (Record.size() == 0)
Mike Stump11289f42009-09-09 15:08:12 +00002443 return false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002444
2445 Decls.clear();
2446
2447 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002448 while (Idx < Record.size()) {
2449 Decls.push_back(VisibleDeclaration());
2450 Decls.back().Name = ReadDeclarationName(Record, Idx);
2451
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002452 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002453 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002454 LoadedDecls.reserve(Size);
2455 for (unsigned I = 0; I < Size; ++I)
2456 LoadedDecls.push_back(Record[Idx++]);
2457 }
2458
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002459 ++NumVisibleDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002460 return false;
2461}
2462
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002463void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002464 this->Consumer = Consumer;
2465
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002466 if (!Consumer)
2467 return;
2468
2469 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002470 // Force deserialization of this decl, which will cause it to be passed to
2471 // the consumer (or queued).
2472 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002473 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002474
2475 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2476 DeclGroupRef DG(InterestingDecls[I]);
2477 Consumer->HandleTopLevelDecl(DG);
2478 }
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002479}
2480
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002481void PCHReader::PrintStats() {
2482 std::fprintf(stderr, "*** PCH Statistics:\n");
2483
Mike Stump11289f42009-09-09 15:08:12 +00002484 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002485 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00002486 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00002487 unsigned NumDeclsLoaded
2488 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2489 (Decl *)0);
2490 unsigned NumIdentifiersLoaded
2491 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2492 IdentifiersLoaded.end(),
2493 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002494 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002495 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2496 SelectorsLoaded.end(),
2497 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002498
Douglas Gregorc5046832009-04-27 18:38:38 +00002499 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2500 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002501 if (TotalNumSLocEntries)
2502 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2503 NumSLocEntriesRead, TotalNumSLocEntries,
2504 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002505 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002506 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002507 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2508 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2509 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002510 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002511 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2512 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002513 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002514 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002515 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2516 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002517 if (TotalNumSelectors)
2518 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2519 NumSelectorsLoaded, TotalNumSelectors,
2520 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2521 if (TotalNumStatements)
2522 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2523 NumStatementsRead, TotalNumStatements,
2524 ((float)NumStatementsRead/TotalNumStatements * 100));
2525 if (TotalNumMacros)
2526 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2527 NumMacrosRead, TotalNumMacros,
2528 ((float)NumMacrosRead/TotalNumMacros * 100));
2529 if (TotalLexicalDeclContexts)
2530 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2531 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2532 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2533 * 100));
2534 if (TotalVisibleDeclContexts)
2535 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2536 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2537 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2538 * 100));
2539 if (TotalSelectorsInMethodPool) {
2540 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2541 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2542 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2543 * 100));
2544 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2545 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002546 std::fprintf(stderr, "\n");
2547}
2548
Douglas Gregora868bbd2009-04-21 22:25:48 +00002549void PCHReader::InitializeSema(Sema &S) {
2550 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002551 S.ExternalSource = this;
2552
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002553 // Makes sure any declarations that were deserialized "too early"
2554 // still get added to the identifier's declaration chains.
2555 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2556 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2557 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002558 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002559 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002560
2561 // If there were any tentative definitions, deserialize them and add
Sebastian Redl35351a92010-01-31 22:27:38 +00002562 // them to Sema's list of tentative definitions.
Douglas Gregord4df8652009-04-22 22:02:47 +00002563 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2564 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redl35351a92010-01-31 22:27:38 +00002565 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregord4df8652009-04-22 22:02:47 +00002566 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00002567
Tanya Lattner90073802010-02-12 00:07:30 +00002568 // If there were any unused static functions, deserialize them and add to
2569 // Sema's list of unused static functions.
2570 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
2571 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
2572 SemaObj->UnusedStaticFuncs.push_back(FD);
2573 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002574
2575 // If there were any locally-scoped external declarations,
2576 // deserialize them and add them to Sema's table of locally-scoped
2577 // external declarations.
2578 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2579 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2580 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2581 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002582
2583 // If there were any ext_vector type declarations, deserialize them
2584 // and add them to Sema's vector of such declarations.
2585 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2586 SemaObj->ExtVectorDecls.push_back(
2587 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00002588}
2589
2590IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2591 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00002592 PCHIdentifierLookupTable *IdTable
Douglas Gregora868bbd2009-04-21 22:25:48 +00002593 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2594 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2595 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2596 if (Pos == IdTable->end())
2597 return 0;
2598
2599 // Dereferencing the iterator has the effect of building the
2600 // IdentifierInfo node and populating it with the various
2601 // declarations it needs.
2602 return *Pos;
2603}
2604
Mike Stump11289f42009-09-09 15:08:12 +00002605std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00002606PCHReader::ReadMethodPool(Selector Sel) {
2607 if (!MethodPoolLookupTable)
2608 return std::pair<ObjCMethodList, ObjCMethodList>();
2609
2610 // Try to find this selector within our on-disk hash table.
2611 PCHMethodPoolLookupTable *PoolTable
2612 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2613 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00002614 if (Pos == PoolTable->end()) {
2615 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002616 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00002617 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00002618
Douglas Gregor95c13f52009-04-25 17:48:32 +00002619 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002620 return *Pos;
2621}
2622
Douglas Gregor0e149972009-04-25 19:10:14 +00002623void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00002624 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002625 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00002626 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00002627}
2628
Douglas Gregor1342e842009-07-06 18:54:52 +00002629/// \brief Set the globally-visible declarations associated with the given
2630/// identifier.
2631///
2632/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00002633/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00002634/// them.
2635///
2636/// \param II an IdentifierInfo that refers to one or more globally-visible
2637/// declarations.
2638///
2639/// \param DeclIDs the set of declaration IDs with the name @p II that are
2640/// visible at global scope.
2641///
2642/// \param Nonrecursive should be true to indicate that the caller knows that
2643/// this call is non-recursive, and therefore the globally-visible declarations
2644/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00002645void
2646PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00002647 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2648 bool Nonrecursive) {
2649 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2650 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2651 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2652 PII.II = II;
2653 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2654 PII.DeclIDs.push_back(DeclIDs[I]);
2655 return;
2656 }
Mike Stump11289f42009-09-09 15:08:12 +00002657
Douglas Gregor1342e842009-07-06 18:54:52 +00002658 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2659 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2660 if (SemaObj) {
2661 // Introduce this declaration into the translation-unit scope
2662 // and add it to the declaration chain for this identifier, so
2663 // that (unqualified) name lookup will find it.
2664 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2665 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2666 } else {
2667 // Queue this declaration so that it will be added to the
2668 // translation unit scope and identifier's declaration chain
2669 // once a Sema object is known.
2670 PreloadedDecls.push_back(D);
2671 }
2672 }
2673}
2674
Chris Lattnerc523d8e2009-04-11 21:15:38 +00002675IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002676 if (ID == 0)
2677 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002678
Douglas Gregor0e149972009-04-25 19:10:14 +00002679 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002680 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002681 return 0;
2682 }
Mike Stump11289f42009-09-09 15:08:12 +00002683
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002684 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00002685 if (!IdentifiersLoaded[ID - 1]) {
2686 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor95272492009-04-25 21:21:38 +00002687 const char *Str = IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00002688
Douglas Gregorab4df582009-04-28 20:01:51 +00002689 // All of the strings in the PCH file are preceded by a 16-bit
2690 // length. Extract that 16-bit length to avoid having to execute
2691 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00002692 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2693 // unsigned integers. This is important to avoid integer overflow when
2694 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00002695 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00002696 unsigned StrLen = (((unsigned) StrLenPtr[0])
2697 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00002698 IdentifiersLoaded[ID - 1]
Kovarththanan Rajaratnama3b09592010-03-12 10:32:27 +00002699 = &PP->getIdentifierTable().get(Str, StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002700 }
Mike Stump11289f42009-09-09 15:08:12 +00002701
Douglas Gregor0e149972009-04-25 19:10:14 +00002702 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002703}
2704
Douglas Gregor258ae542009-04-27 06:38:32 +00002705void PCHReader::ReadSLocEntry(unsigned ID) {
2706 ReadSLocEntryRecord(ID);
2707}
2708
Steve Naroff2ddea052009-04-23 10:39:46 +00002709Selector PCHReader::DecodeSelector(unsigned ID) {
2710 if (ID == 0)
2711 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00002712
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002713 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00002714 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002715
2716 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002717 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00002718 return Selector();
2719 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00002720
2721 unsigned Index = ID - 1;
2722 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2723 // Load this selector from the selector table.
2724 // FIXME: endianness portability issues with SelectorOffsets table
2725 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002726 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00002727 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2728 }
2729
2730 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00002731}
2732
Mike Stump11289f42009-09-09 15:08:12 +00002733DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002734PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2735 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2736 switch (Kind) {
2737 case DeclarationName::Identifier:
2738 return DeclarationName(GetIdentifierInfo(Record, Idx));
2739
2740 case DeclarationName::ObjCZeroArgSelector:
2741 case DeclarationName::ObjCOneArgSelector:
2742 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00002743 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002744
2745 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002746 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002747 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002748
2749 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002750 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002751 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002752
2753 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002754 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002755 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002756
2757 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002758 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002759 (OverloadedOperatorKind)Record[Idx++]);
2760
Alexis Hunt3d221f22009-11-29 07:34:05 +00002761 case DeclarationName::CXXLiteralOperatorName:
2762 return Context->DeclarationNames.getCXXLiteralOperatorName(
2763 GetIdentifierInfo(Record, Idx));
2764
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002765 case DeclarationName::CXXUsingDirective:
2766 return DeclarationName::getUsingDirectiveName();
2767 }
2768
2769 // Required to silence GCC warning
2770 return DeclarationName();
2771}
Douglas Gregor55abb232009-04-10 20:39:37 +00002772
Douglas Gregor1daeb692009-04-13 18:14:40 +00002773/// \brief Read an integral value
2774llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2775 unsigned BitWidth = Record[Idx++];
2776 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2777 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2778 Idx += NumWords;
2779 return Result;
2780}
2781
2782/// \brief Read a signed integral value
2783llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2784 bool isUnsigned = Record[Idx++];
2785 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2786}
2787
Douglas Gregore0a3a512009-04-14 21:55:33 +00002788/// \brief Read a floating-point value
2789llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00002790 return llvm::APFloat(ReadAPInt(Record, Idx));
2791}
2792
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002793// \brief Read a string
2794std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2795 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00002796 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002797 Idx += Len;
2798 return Result;
2799}
2800
Douglas Gregor55abb232009-04-10 20:39:37 +00002801DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00002802 return Diag(SourceLocation(), DiagID);
2803}
2804
2805DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002806 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00002807}
Douglas Gregora9af1d12009-04-17 00:04:06 +00002808
Douglas Gregora868bbd2009-04-21 22:25:48 +00002809/// \brief Retrieve the identifier table associated with the
2810/// preprocessor.
2811IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002812 assert(PP && "Forgot to set Preprocessor ?");
2813 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00002814}
2815
Douglas Gregora9af1d12009-04-17 00:04:06 +00002816/// \brief Record that the given ID maps to the given switch-case
2817/// statement.
2818void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2819 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2820 SwitchCaseStmts[ID] = SC;
2821}
2822
2823/// \brief Retrieve the switch-case statement with the given ID.
2824SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2825 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2826 return SwitchCaseStmts[ID];
2827}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002828
2829/// \brief Record that the given label statement has been
2830/// deserialized and has the given ID.
2831void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00002832 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002833 "Deserialized label twice");
2834 LabelStmts[ID] = S;
2835
2836 // If we've already seen any goto statements that point to this
2837 // label, resolve them now.
2838 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2839 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2840 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2841 Goto->second->setLabel(S);
2842 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00002843
2844 // If we've already seen any address-label statements that point to
2845 // this label, resolve them now.
2846 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00002847 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00002848 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00002849 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00002850 AddrLabel != AddrLabels.second; ++AddrLabel)
2851 AddrLabel->second->setLabel(S);
2852 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002853}
2854
2855/// \brief Set the label of the given statement to the label
2856/// identified by ID.
2857///
2858/// Depending on the order in which the label and other statements
2859/// referencing that label occur, this operation may complete
2860/// immediately (updating the statement) or it may queue the
2861/// statement to be back-patched later.
2862void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2863 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2864 if (Label != LabelStmts.end()) {
2865 // We've already seen this label, so set the label of the goto and
2866 // we're done.
2867 S->setLabel(Label->second);
2868 } else {
2869 // We haven't seen this label yet, so add this goto to the set of
2870 // unresolved goto statements.
2871 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2872 }
2873}
Douglas Gregor779d8652009-04-17 18:58:21 +00002874
2875/// \brief Set the label of the given expression to the label
2876/// identified by ID.
2877///
2878/// Depending on the order in which the label and other statements
2879/// referencing that label occur, this operation may complete
2880/// immediately (updating the statement) or it may queue the
2881/// statement to be back-patched later.
2882void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2883 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2884 if (Label != LabelStmts.end()) {
2885 // We've already seen this label, so set the label of the
2886 // label-address expression and we're done.
2887 S->setLabel(Label->second);
2888 } else {
2889 // We haven't seen this label yet, so add this label-address
2890 // expression to the set of unresolved label-address expressions.
2891 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2892 }
2893}
Douglas Gregor1342e842009-07-06 18:54:52 +00002894
2895
Mike Stump11289f42009-09-09 15:08:12 +00002896PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00002897 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2898 Reader.CurrentlyLoadingTypeOrDecl = this;
2899}
2900
2901PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2902 if (!Parent) {
2903 // If any identifiers with corresponding top-level declarations have
2904 // been loaded, load those declarations now.
2905 while (!Reader.PendingIdentifierInfos.empty()) {
2906 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2907 Reader.PendingIdentifierInfos.front().DeclIDs,
2908 true);
2909 Reader.PendingIdentifierInfos.pop_front();
2910 }
2911 }
2912
Mike Stump11289f42009-09-09 15:08:12 +00002913 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00002914}