blob: 4c6e5f44a0e2760af948740886e7e71730fb46fd [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);
75 PARSE_LANGOPT_BENIGN(PascalStrings);
76 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump11289f42009-09-09 15:08:12 +000077 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000078 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +000079 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000080 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
81 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
82 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
83 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +000084 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000085 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000086 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000087 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
88 PARSE_LANGOPT_BENIGN(EmitAllDecls);
89 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
90 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump11289f42009-09-09 15:08:12 +000091 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000092 diag::warn_pch_heinous_extensions);
93 // FIXME: Most of the options below are benign if the macro wasn't
94 // used. Unfortunately, this means that a PCH compiled without
95 // optimization can't be used with optimization turned on, even
96 // though the only thing that changes is whether __OPTIMIZE__ was
97 // defined... but if __OPTIMIZE__ never showed up in the header, it
98 // doesn't matter. We could consider making this some special kind
99 // of check.
100 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
101 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
102 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
103 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
104 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
105 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
106 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
107 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsoned4e2952009-11-05 20:14:16 +0000108 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000109 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000110 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000111 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
112 return true;
113 }
114 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000115 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
116 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000117 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000118 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stumpd9546382009-12-12 01:27:46 +0000119 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000120 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000121#undef PARSE_LANGOPT_IRRELEVANT
122#undef PARSE_LANGOPT_BENIGN
123
124 return false;
125}
126
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000127bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
128 if (Triple == PP.getTargetInfo().getTriple().str())
129 return false;
130
131 Reader.Diag(diag::warn_pch_target_triple)
132 << Triple << PP.getTargetInfo().getTriple().str();
133 return true;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000134}
135
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000136bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000137 FileID PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000138 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000139 std::string &SuggestedPredefines) {
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000140 // We are in the context of an implicit include, so the predefines buffer will
141 // have a #include entry for the PCH file itself (as normalized by the
142 // preprocessor initialization). Find it and skip over it in the checking
143 // below.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000144 llvm::SmallString<256> PCHInclude;
145 PCHInclude += "#include \"";
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000146 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000147 PCHInclude += "\"\n";
148 std::pair<llvm::StringRef,llvm::StringRef> Split =
149 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
150 llvm::StringRef Left = Split.first, Right = Split.second;
151 assert(Left != PP.getPredefines() && "Missing PCH include entry!");
152
153 // If the predefines is equal to the joined left and right halves, we're done!
154 if (Left.size() + Right.size() == PCHPredef.size() &&
155 PCHPredef.startswith(Left) && PCHPredef.endswith(Right))
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000156 return false;
157
158 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000159
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000160 // The predefines buffers are different. Determine what the differences are,
161 // and whether they require us to reject the PCH file.
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000162 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
163 PCHPredef.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
164
165 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
166 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
167 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000168
Daniel Dunbar499baed2009-11-11 05:26:28 +0000169 // Sort both sets of predefined buffer lines, since we allow some extra
170 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000171 std::sort(CmdLineLines.begin(), CmdLineLines.end());
172 std::sort(PCHLines.begin(), PCHLines.end());
173
Daniel Dunbar499baed2009-11-11 05:26:28 +0000174 // Determine which predefines that were used to build the PCH file are missing
175 // from the command line.
176 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000177 std::set_difference(PCHLines.begin(), PCHLines.end(),
178 CmdLineLines.begin(), CmdLineLines.end(),
179 std::back_inserter(MissingPredefines));
180
181 bool MissingDefines = false;
182 bool ConflictingDefines = false;
183 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000184 llvm::StringRef Missing = MissingPredefines[I];
185 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000186 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
187 return true;
188 }
Mike Stump11289f42009-09-09 15:08:12 +0000189
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000190 // This is a macro definition. Determine the name of the macro we're
191 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000192 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000193 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000194 = Missing.find_first_of("( \n\r", StartOfMacroName);
195 assert(EndOfMacroName != std::string::npos &&
196 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000197 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000198
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000199 // Determine whether this macro was given a different definition on the
200 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000201 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000202 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000203 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000204 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
205 MacroDefStart);
206 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000207 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000208 // Different macro; we're done.
209 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000210 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000211 }
Mike Stump11289f42009-09-09 15:08:12 +0000212
213 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000214 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000215 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000216 (*ConflictPos)[MacroDefLen] != '(')
217 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000218
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000219 // We found a conflicting macro definition.
220 break;
221 }
Mike Stump11289f42009-09-09 15:08:12 +0000222
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000223 if (ConflictPos != CmdLineLines.end()) {
224 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
225 << MacroName;
226
227 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000228 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
229 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
230 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
231 .getFileLocWithOffset(Offset);
232 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000233
234 ConflictingDefines = true;
235 continue;
236 }
Mike Stump11289f42009-09-09 15:08:12 +0000237
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000238 // If the macro doesn't conflict, then we'll just pick up the macro
239 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000240 if (ConflictingDefines)
241 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000242
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000243 if (!MissingDefines) {
244 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
245 MissingDefines = true;
246 }
247
248 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000249 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
250 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
251 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000252 .getFileLocWithOffset(Offset);
253 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
254 }
Mike Stump11289f42009-09-09 15:08:12 +0000255
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000256 if (ConflictingDefines)
257 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000258
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000259 // Determine what predefines were introduced based on command-line
260 // parameters that were not present when building the PCH
261 // file. Extra #defines are okay, so long as the identifiers being
262 // defined were not used within the precompiled header.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000263 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000264 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
265 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000266 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000267 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000268 llvm::StringRef &Extra = ExtraPredefines[I];
269 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000270 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
271 return true;
272 }
273
274 // This is an extra macro definition. Determine the name of the
275 // macro we're defining.
276 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000277 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000278 = Extra.find_first_of("( \n\r", StartOfMacroName);
279 assert(EndOfMacroName != std::string::npos &&
280 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000281 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000282
283 // Check whether this name was used somewhere in the PCH file. If
284 // so, defining it as a macro could change behavior, so we reject
285 // the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000286 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000287 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000288 return true;
289 }
290
291 // Add this definition to the suggested predefines buffer.
292 SuggestedPredefines += Extra;
293 SuggestedPredefines += '\n';
294 }
295
296 // If we get here, it's because the predefines buffer had compatible
297 // contents. Accept the PCH file.
298 return false;
299}
300
301void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
302 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
303}
304
305void PCHValidator::ReadCounter(unsigned Value) {
306 PP.setCounterValue(Value);
307}
308
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000309//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000310// PCH reader implementation
311//===----------------------------------------------------------------------===//
312
Mike Stump11289f42009-09-09 15:08:12 +0000313PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
314 const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000315 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
316 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000317 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000318 IdentifierTableData(0), IdentifierLookupTable(0),
319 IdentifierOffsets(0),
320 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
321 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000322 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000323 NumStatHits(0), NumStatMisses(0),
324 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000325 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000326 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000327 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000328 RelocatablePCH = false;
329}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000330
331PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000332 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000333 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000334 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000335 IdentifierTableData(0), IdentifierLookupTable(0),
336 IdentifierOffsets(0),
337 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
338 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000339 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000340 NumStatHits(0), NumStatMisses(0),
341 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000342 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000343 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000344 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000345 RelocatablePCH = false;
346}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000347
348PCHReader::~PCHReader() {}
349
Chris Lattner1de76db2009-04-27 05:58:23 +0000350Expr *PCHReader::ReadDeclExpr() {
351 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
352}
353
354Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor12bfa382009-10-17 00:13:19 +0000355 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000356}
357
358
Douglas Gregora868bbd2009-04-21 22:25:48 +0000359namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000360class PCHMethodPoolLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000361 PCHReader &Reader;
362
363public:
364 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
365
366 typedef Selector external_key_type;
367 typedef external_key_type internal_key_type;
368
369 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000370
Douglas Gregorc78d3462009-04-24 21:10:55 +0000371 static bool EqualKey(const internal_key_type& a,
372 const internal_key_type& b) {
373 return a == b;
374 }
Mike Stump11289f42009-09-09 15:08:12 +0000375
Douglas Gregorc78d3462009-04-24 21:10:55 +0000376 static unsigned ComputeHash(Selector Sel) {
377 unsigned N = Sel.getNumArgs();
378 if (N == 0)
379 ++N;
380 unsigned R = 5381;
381 for (unsigned I = 0; I != N; ++I)
382 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000383 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000384 return R;
385 }
Mike Stump11289f42009-09-09 15:08:12 +0000386
Douglas Gregorc78d3462009-04-24 21:10:55 +0000387 // This hopefully will just get inlined and removed by the optimizer.
388 static const internal_key_type&
389 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000390
Douglas Gregorc78d3462009-04-24 21:10:55 +0000391 static std::pair<unsigned, unsigned>
392 ReadKeyDataLength(const unsigned char*& d) {
393 using namespace clang::io;
394 unsigned KeyLen = ReadUnalignedLE16(d);
395 unsigned DataLen = ReadUnalignedLE16(d);
396 return std::make_pair(KeyLen, DataLen);
397 }
Mike Stump11289f42009-09-09 15:08:12 +0000398
Douglas Gregor95c13f52009-04-25 17:48:32 +0000399 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000400 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000401 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000402 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000403 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000404 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
405 if (N == 0)
406 return SelTable.getNullarySelector(FirstII);
407 else if (N == 1)
408 return SelTable.getUnarySelector(FirstII);
409
410 llvm::SmallVector<IdentifierInfo *, 16> Args;
411 Args.push_back(FirstII);
412 for (unsigned I = 1; I != N; ++I)
413 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
414
Douglas Gregor038c3382009-05-22 22:45:36 +0000415 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000416 }
Mike Stump11289f42009-09-09 15:08:12 +0000417
Douglas Gregorc78d3462009-04-24 21:10:55 +0000418 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
419 using namespace clang::io;
420 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
421 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
422
423 data_type Result;
424
425 // Load instance methods
426 ObjCMethodList *Prev = 0;
427 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000428 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000429 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
430 if (!Result.first.Method) {
431 // This is the first method, which is the easy case.
432 Result.first.Method = Method;
433 Prev = &Result.first;
434 continue;
435 }
436
437 Prev->Next = new ObjCMethodList(Method, 0);
438 Prev = Prev->Next;
439 }
440
441 // Load factory methods
442 Prev = 0;
443 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000444 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000445 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
446 if (!Result.second.Method) {
447 // This is the first method, which is the easy case.
448 Result.second.Method = Method;
449 Prev = &Result.second;
450 continue;
451 }
452
453 Prev->Next = new ObjCMethodList(Method, 0);
454 Prev = Prev->Next;
455 }
456
457 return Result;
458 }
459};
Mike Stump11289f42009-09-09 15:08:12 +0000460
461} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000462
463/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000464typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000465 PCHMethodPoolLookupTable;
466
467namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000468class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000469 PCHReader &Reader;
470
471 // If we know the IdentifierInfo in advance, it is here and we will
472 // not build a new one. Used when deserializing information about an
473 // identifier that was constructed before the PCH file was read.
474 IdentifierInfo *KnownII;
475
476public:
477 typedef IdentifierInfo * data_type;
478
479 typedef const std::pair<const char*, unsigned> external_key_type;
480
481 typedef external_key_type internal_key_type;
482
Mike Stump11289f42009-09-09 15:08:12 +0000483 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregora868bbd2009-04-21 22:25:48 +0000484 : Reader(Reader), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000485
Douglas Gregora868bbd2009-04-21 22:25:48 +0000486 static bool EqualKey(const internal_key_type& a,
487 const internal_key_type& b) {
488 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
489 : false;
490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregora868bbd2009-04-21 22:25:48 +0000492 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000493 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000494 }
Mike Stump11289f42009-09-09 15:08:12 +0000495
Douglas Gregora868bbd2009-04-21 22:25:48 +0000496 // This hopefully will just get inlined and removed by the optimizer.
497 static const internal_key_type&
498 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000499
Douglas Gregora868bbd2009-04-21 22:25:48 +0000500 static std::pair<unsigned, unsigned>
501 ReadKeyDataLength(const unsigned char*& d) {
502 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000503 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000504 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000505 return std::make_pair(KeyLen, DataLen);
506 }
Mike Stump11289f42009-09-09 15:08:12 +0000507
Douglas Gregora868bbd2009-04-21 22:25:48 +0000508 static std::pair<const char*, unsigned>
509 ReadKey(const unsigned char* d, unsigned n) {
510 assert(n >= 2 && d[n-1] == '\0');
511 return std::make_pair((const char*) d, n-1);
512 }
Mike Stump11289f42009-09-09 15:08:12 +0000513
514 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000515 const unsigned char* d,
516 unsigned DataLen) {
517 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000518 pch::IdentID ID = ReadUnalignedLE32(d);
519 bool IsInteresting = ID & 0x01;
520
521 // Wipe out the "is interesting" bit.
522 ID = ID >> 1;
523
524 if (!IsInteresting) {
525 // For unintersting identifiers, just build the IdentifierInfo
526 // and associate it with the persistent ID.
527 IdentifierInfo *II = KnownII;
528 if (!II)
529 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
530 k.first, k.first + k.second);
531 Reader.SetIdentifierInfo(ID, II);
532 return II;
533 }
534
Douglas Gregorb9256522009-04-28 21:32:13 +0000535 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000536 bool CPlusPlusOperatorKeyword = Bits & 0x01;
537 Bits >>= 1;
538 bool Poisoned = Bits & 0x01;
539 Bits >>= 1;
540 bool ExtensionToken = Bits & 0x01;
541 Bits >>= 1;
542 bool hasMacroDefinition = Bits & 0x01;
543 Bits >>= 1;
544 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
545 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000546
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000547 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000548 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000549
550 // Build the IdentifierInfo itself and link the identifier ID with
551 // the new IdentifierInfo.
552 IdentifierInfo *II = KnownII;
553 if (!II)
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000554 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
555 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000556 Reader.SetIdentifierInfo(ID, II);
557
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000558 // Set or check the various bits in the IdentifierInfo structure.
559 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000560 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000561 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000562 "Incorrect extension token flag");
563 (void)ExtensionToken;
564 II->setIsPoisoned(Poisoned);
565 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
566 "Incorrect C++ operator keyword flag");
567 (void)CPlusPlusOperatorKeyword;
568
Douglas Gregorc3366a52009-04-21 23:56:24 +0000569 // If this identifier is a macro, deserialize the macro
570 // definition.
571 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000572 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregorc3366a52009-04-21 23:56:24 +0000573 Reader.ReadMacroRecord(Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000574 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000575 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000576
577 // Read all of the declarations visible at global scope with this
578 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000579 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000580 if (DataLen > 0) {
581 llvm::SmallVector<uint32_t, 4> DeclIDs;
582 for (; DataLen > 0; DataLen -= 4)
583 DeclIDs.push_back(ReadUnalignedLE32(d));
584 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000585 }
Mike Stump11289f42009-09-09 15:08:12 +0000586
Douglas Gregora868bbd2009-04-21 22:25:48 +0000587 return II;
588 }
589};
Mike Stump11289f42009-09-09 15:08:12 +0000590
591} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000592
593/// \brief The on-disk hash table used to contain information about
594/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000595typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000596 PCHIdentifierLookupTable;
597
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000598bool PCHReader::Error(const char *Msg) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000599 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
600 Diag(DiagID);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000601 return true;
602}
603
Douglas Gregor92863e42009-04-10 23:10:45 +0000604/// \brief Check the contents of the predefines buffer against the
605/// contents of the predefines buffer used to build the PCH file.
606///
607/// The contents of the two predefines buffers should be the same. If
608/// not, then some command-line option changed the preprocessor state
609/// and we must reject the PCH file.
610///
611/// \param PCHPredef The start of the predefines buffer in the PCH
612/// file.
613///
614/// \param PCHPredefLen The length of the predefines buffer in the PCH
615/// file.
616///
617/// \param PCHBufferID The FileID for the PCH predefines buffer.
618///
619/// \returns true if there was a mismatch (in which case the PCH file
620/// should be ignored), or false otherwise.
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000621bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregor92863e42009-04-10 23:10:45 +0000622 FileID PCHBufferID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000623 if (Listener)
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000624 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000625 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000626 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000627 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000628}
629
Douglas Gregorc5046832009-04-27 18:38:38 +0000630//===----------------------------------------------------------------------===//
631// Source Manager Deserialization
632//===----------------------------------------------------------------------===//
633
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000634/// \brief Read the line table in the source manager block.
635/// \returns true if ther was an error.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000636bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000637 unsigned Idx = 0;
638 LineTableInfo &LineTable = SourceMgr.getLineTable();
639
640 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000641 std::map<int, int> FileIDs;
642 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000643 // Extract the file name
644 unsigned FilenameLen = Record[Idx++];
645 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
646 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000647 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000648 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000649 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000650 }
651
652 // Parse the line entries
653 std::vector<LineEntry> Entries;
654 while (Idx < Record.size()) {
Douglas Gregora8854652009-04-13 17:12:42 +0000655 int FID = FileIDs[Record[Idx++]];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000656
657 // Extract the line entries
658 unsigned NumEntries = Record[Idx++];
659 Entries.clear();
660 Entries.reserve(NumEntries);
661 for (unsigned I = 0; I != NumEntries; ++I) {
662 unsigned FileOffset = Record[Idx++];
663 unsigned LineNo = Record[Idx++];
664 int FilenameID = Record[Idx++];
Mike Stump11289f42009-09-09 15:08:12 +0000665 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000666 = (SrcMgr::CharacteristicKind)Record[Idx++];
667 unsigned IncludeOffset = Record[Idx++];
668 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
669 FileKind, IncludeOffset));
670 }
671 LineTable.AddEntry(FID, Entries);
672 }
673
674 return false;
675}
676
Douglas Gregorc5046832009-04-27 18:38:38 +0000677namespace {
678
Benjamin Kramer16634c22009-11-28 10:07:24 +0000679class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000680public:
681 const bool hasStat;
682 const ino_t ino;
683 const dev_t dev;
684 const mode_t mode;
685 const time_t mtime;
686 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000687
Douglas Gregorc5046832009-04-27 18:38:38 +0000688 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000689 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
690
Douglas Gregorc5046832009-04-27 18:38:38 +0000691 PCHStatData()
692 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
693};
694
Benjamin Kramer16634c22009-11-28 10:07:24 +0000695class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000696 public:
697 typedef const char *external_key_type;
698 typedef const char *internal_key_type;
699
700 typedef PCHStatData data_type;
701
702 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000703 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000704 }
705
706 static internal_key_type GetInternalKey(const char *path) { return path; }
707
708 static bool EqualKey(internal_key_type a, internal_key_type b) {
709 return strcmp(a, b) == 0;
710 }
711
712 static std::pair<unsigned, unsigned>
713 ReadKeyDataLength(const unsigned char*& d) {
714 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
715 unsigned DataLen = (unsigned) *d++;
716 return std::make_pair(KeyLen + 1, DataLen);
717 }
718
719 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
720 return (const char *)d;
721 }
722
723 static data_type ReadData(const internal_key_type, const unsigned char *d,
724 unsigned /*DataLen*/) {
725 using namespace clang::io;
726
727 if (*d++ == 1)
728 return data_type();
729
730 ino_t ino = (ino_t) ReadUnalignedLE32(d);
731 dev_t dev = (dev_t) ReadUnalignedLE32(d);
732 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000733 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000734 off_t size = (off_t) ReadUnalignedLE64(d);
735 return data_type(ino, dev, mode, mtime, size);
736 }
737};
738
739/// \brief stat() cache for precompiled headers.
740///
741/// This cache is very similar to the stat cache used by pretokenized
742/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000743class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000744 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
745 CacheTy *Cache;
746
747 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000748public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000749 PCHStatCache(const unsigned char *Buckets,
750 const unsigned char *Base,
751 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000752 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000753 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
754 Cache = CacheTy::Create(Buckets, Base);
755 }
756
757 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000758
Douglas Gregorc5046832009-04-27 18:38:38 +0000759 int stat(const char *path, struct stat *buf) {
760 // Do the lookup for the file's data in the PCH file.
761 CacheTy::iterator I = Cache->find(path);
762
763 // If we don't get a hit in the PCH file just forward to 'stat'.
764 if (I == Cache->end()) {
765 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000766 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000767 }
Mike Stump11289f42009-09-09 15:08:12 +0000768
Douglas Gregorc5046832009-04-27 18:38:38 +0000769 ++NumStatHits;
770 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000771
Douglas Gregorc5046832009-04-27 18:38:38 +0000772 if (!Data.hasStat)
773 return 1;
774
775 buf->st_ino = Data.ino;
776 buf->st_dev = Data.dev;
777 buf->st_mtime = Data.mtime;
778 buf->st_mode = Data.mode;
779 buf->st_size = Data.size;
780 return 0;
781 }
782};
783} // end anonymous namespace
784
785
Douglas Gregora7f71a92009-04-10 03:52:48 +0000786/// \brief Read the source manager block
Douglas Gregor92863e42009-04-10 23:10:45 +0000787PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000788 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000789
790 // Set the source-location entry cursor to the current position in
791 // the stream. This cursor will be used to read the contents of the
792 // source manager block initially, and then lazily read
793 // source-location entries as needed.
794 SLocEntryCursor = Stream;
795
796 // The stream itself is going to skip over the source manager block.
797 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000798 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000799 return Failure;
800 }
801
802 // Enter the source manager block.
803 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000804 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000805 return Failure;
806 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000807
Douglas Gregora7f71a92009-04-10 03:52:48 +0000808 RecordData Record;
809 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000810 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000811 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000812 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000813 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000814 return Failure;
815 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000816 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000817 }
Mike Stump11289f42009-09-09 15:08:12 +0000818
Douglas Gregora7f71a92009-04-10 03:52:48 +0000819 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
820 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000821 SLocEntryCursor.ReadSubBlockID();
822 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000823 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000824 return Failure;
825 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000826 continue;
827 }
Mike Stump11289f42009-09-09 15:08:12 +0000828
Douglas Gregora7f71a92009-04-10 03:52:48 +0000829 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000830 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000831 continue;
832 }
Mike Stump11289f42009-09-09 15:08:12 +0000833
Douglas Gregora7f71a92009-04-10 03:52:48 +0000834 // Read a record.
835 const char *BlobStart;
836 unsigned BlobLen;
837 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000838 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000839 default: // Default behavior: ignore.
840 break;
841
Chris Lattner184e65d2009-04-14 23:22:57 +0000842 case pch::SM_LINE_TABLE:
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000843 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000844 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000845 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000846
847 case pch::SM_HEADER_FILE_INFO: {
848 HeaderFileInfo HFI;
849 HFI.isImport = Record[0];
850 HFI.DirInfo = Record[1];
851 HFI.NumIncludes = Record[2];
852 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000853 if (Listener)
854 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregoreda6a892009-04-26 00:07:37 +0000855 break;
856 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000857
858 case pch::SM_SLOC_FILE_ENTRY:
859 case pch::SM_SLOC_BUFFER_ENTRY:
860 case pch::SM_SLOC_INSTANTIATION_ENTRY:
861 // Once we hit one of the source location entries, we're done.
862 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000863 }
864 }
865}
866
Douglas Gregor258ae542009-04-27 06:38:32 +0000867/// \brief Read in the source location entry with the given ID.
868PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
869 if (ID == 0)
870 return Success;
871
872 if (ID > TotalNumSLocEntries) {
873 Error("source location entry ID out-of-range for PCH file");
874 return Failure;
875 }
876
877 ++NumSLocEntriesRead;
878 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
879 unsigned Code = SLocEntryCursor.ReadCode();
880 if (Code == llvm::bitc::END_BLOCK ||
881 Code == llvm::bitc::ENTER_SUBBLOCK ||
882 Code == llvm::bitc::DEFINE_ABBREV) {
883 Error("incorrectly-formatted source location entry in PCH file");
884 return Failure;
885 }
886
Douglas Gregor258ae542009-04-27 06:38:32 +0000887 RecordData Record;
888 const char *BlobStart;
889 unsigned BlobLen;
890 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
891 default:
892 Error("incorrectly-formatted source location entry in PCH file");
893 return Failure;
894
895 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000896 std::string Filename(BlobStart, BlobStart + BlobLen);
897 MaybeAddSystemRootToFilename(Filename);
898 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000899 if (File == 0) {
900 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000901 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000902 ErrorStr += "' referenced by PCH file";
903 Error(ErrorStr.c_str());
904 return Failure;
905 }
Mike Stump11289f42009-09-09 15:08:12 +0000906
Douglas Gregor258ae542009-04-27 06:38:32 +0000907 FileID FID = SourceMgr.createFileID(File,
908 SourceLocation::getFromRawEncoding(Record[1]),
909 (SrcMgr::CharacteristicKind)Record[2],
910 ID, Record[0]);
911 if (Record[3])
912 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
913 .setHasLineDirectives();
914
915 break;
916 }
917
918 case pch::SM_SLOC_BUFFER_ENTRY: {
919 const char *Name = BlobStart;
920 unsigned Offset = Record[0];
921 unsigned Code = SLocEntryCursor.ReadCode();
922 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000923 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +0000924 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
925 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
926 (void)RecCode;
927 llvm::MemoryBuffer *Buffer
Mike Stump11289f42009-09-09 15:08:12 +0000928 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor258ae542009-04-27 06:38:32 +0000929 BlobStart + BlobLen - 1,
930 Name);
931 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000932
Douglas Gregore6648fb2009-04-28 20:33:11 +0000933 if (strcmp(Name, "<built-in>") == 0) {
934 PCHPredefinesBufferID = BufferID;
935 PCHPredefines = BlobStart;
936 PCHPredefinesLen = BlobLen - 1;
937 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000938
939 break;
940 }
941
942 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +0000943 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +0000944 = SourceLocation::getFromRawEncoding(Record[1]);
945 SourceMgr.createInstantiationLoc(SpellingLoc,
946 SourceLocation::getFromRawEncoding(Record[2]),
947 SourceLocation::getFromRawEncoding(Record[3]),
948 Record[4],
949 ID,
950 Record[0]);
951 break;
Mike Stump11289f42009-09-09 15:08:12 +0000952 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000953 }
954
955 return Success;
956}
957
Chris Lattnere78a6be2009-04-27 01:05:14 +0000958/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
959/// specified cursor. Read the abbreviations that are at the top of the block
960/// and then leave the cursor pointing into the block.
961bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
962 unsigned BlockID) {
963 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000964 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +0000965 return Failure;
966 }
Mike Stump11289f42009-09-09 15:08:12 +0000967
Chris Lattnere78a6be2009-04-27 01:05:14 +0000968 while (true) {
969 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +0000970
Chris Lattnere78a6be2009-04-27 01:05:14 +0000971 // We expect all abbrevs to be at the start of the block.
972 if (Code != llvm::bitc::DEFINE_ABBREV)
973 return false;
974 Cursor.ReadAbbrevRecord();
975 }
976}
977
Douglas Gregorc3366a52009-04-21 23:56:24 +0000978void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000979 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +0000980
Douglas Gregorc3366a52009-04-21 23:56:24 +0000981 // Keep track of where we are in the stream, then jump back there
982 // after reading this macro.
983 SavedStreamPosition SavedPosition(Stream);
984
985 Stream.JumpToBit(Offset);
986 RecordData Record;
987 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
988 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000989
Douglas Gregorc3366a52009-04-21 23:56:24 +0000990 while (true) {
991 unsigned Code = Stream.ReadCode();
992 switch (Code) {
993 case llvm::bitc::END_BLOCK:
994 return;
995
996 case llvm::bitc::ENTER_SUBBLOCK:
997 // No known subblocks, always skip them.
998 Stream.ReadSubBlockID();
999 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001000 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001001 return;
1002 }
1003 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001004
Douglas Gregorc3366a52009-04-21 23:56:24 +00001005 case llvm::bitc::DEFINE_ABBREV:
1006 Stream.ReadAbbrevRecord();
1007 continue;
1008 default: break;
1009 }
1010
1011 // Read a record.
1012 Record.clear();
1013 pch::PreprocessorRecordTypes RecType =
1014 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1015 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001016 case pch::PP_MACRO_OBJECT_LIKE:
1017 case pch::PP_MACRO_FUNCTION_LIKE: {
1018 // If we already have a macro, that means that we've hit the end
1019 // of the definition of the macro we were looking for. We're
1020 // done.
1021 if (Macro)
1022 return;
1023
1024 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1025 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001026 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001027 return;
1028 }
1029 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1030 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001031
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001032 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001033 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001034
Douglas Gregorc3366a52009-04-21 23:56:24 +00001035 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1036 // Decode function-like macro info.
1037 bool isC99VarArgs = Record[3];
1038 bool isGNUVarArgs = Record[4];
1039 MacroArgs.clear();
1040 unsigned NumArgs = Record[5];
1041 for (unsigned i = 0; i != NumArgs; ++i)
1042 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1043
1044 // Install function-like macro info.
1045 MI->setIsFunctionLike();
1046 if (isC99VarArgs) MI->setIsC99Varargs();
1047 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001048 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001049 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001050 }
1051
1052 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001053 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001054
1055 // Remember that we saw this macro last so that we add the tokens that
1056 // form its body to it.
1057 Macro = MI;
1058 ++NumMacrosRead;
1059 break;
1060 }
Mike Stump11289f42009-09-09 15:08:12 +00001061
Douglas Gregorc3366a52009-04-21 23:56:24 +00001062 case pch::PP_TOKEN: {
1063 // If we see a TOKEN before a PP_MACRO_*, then the file is
1064 // erroneous, just pretend we didn't see this.
1065 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001066
Douglas Gregorc3366a52009-04-21 23:56:24 +00001067 Token Tok;
1068 Tok.startToken();
1069 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1070 Tok.setLength(Record[1]);
1071 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1072 Tok.setIdentifierInfo(II);
1073 Tok.setKind((tok::TokenKind)Record[3]);
1074 Tok.setFlag((Token::TokenFlags)Record[4]);
1075 Macro->AddTokenToBody(Tok);
1076 break;
1077 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001078 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001079 }
1080}
1081
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001082void PCHReader::ReadDefinedMacros() {
1083 // If there was no preprocessor block, do nothing.
1084 if (!MacroCursor.getBitStreamReader())
1085 return;
1086
1087 llvm::BitstreamCursor Cursor = MacroCursor;
1088 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1089 Error("malformed preprocessor block record in PCH file");
1090 return;
1091 }
1092
1093 RecordData Record;
1094 while (true) {
1095 unsigned Code = Cursor.ReadCode();
1096 if (Code == llvm::bitc::END_BLOCK) {
1097 if (Cursor.ReadBlockEnd())
1098 Error("error at end of preprocessor block in PCH file");
1099 return;
1100 }
1101
1102 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1103 // No known subblocks, always skip them.
1104 Cursor.ReadSubBlockID();
1105 if (Cursor.SkipBlock()) {
1106 Error("malformed block record in PCH file");
1107 return;
1108 }
1109 continue;
1110 }
1111
1112 if (Code == llvm::bitc::DEFINE_ABBREV) {
1113 Cursor.ReadAbbrevRecord();
1114 continue;
1115 }
1116
1117 // Read a record.
1118 const char *BlobStart;
1119 unsigned BlobLen;
1120 Record.clear();
1121 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1122 default: // Default behavior: ignore.
1123 break;
1124
1125 case pch::PP_MACRO_OBJECT_LIKE:
1126 case pch::PP_MACRO_FUNCTION_LIKE:
1127 DecodeIdentifierInfo(Record[0]);
1128 break;
1129
1130 case pch::PP_TOKEN:
1131 // Ignore tokens.
1132 break;
1133 }
1134 }
1135}
1136
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001137/// \brief If we are loading a relocatable PCH file, and the filename is
1138/// not an absolute path, add the system root to the beginning of the file
1139/// name.
1140void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1141 // If this is not a relocatable PCH file, there's nothing to do.
1142 if (!RelocatablePCH)
1143 return;
Mike Stump11289f42009-09-09 15:08:12 +00001144
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001145 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001146 return;
1147
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001148 if (isysroot == 0) {
1149 // If no system root was given, default to '/'
1150 Filename.insert(Filename.begin(), '/');
1151 return;
1152 }
Mike Stump11289f42009-09-09 15:08:12 +00001153
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001154 unsigned Length = strlen(isysroot);
1155 if (isysroot[Length - 1] != '/')
1156 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001157
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001158 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1159}
1160
Mike Stump11289f42009-09-09 15:08:12 +00001161PCHReader::PCHReadResult
Douglas Gregoreda6a892009-04-26 00:07:37 +00001162PCHReader::ReadPCHBlock() {
Douglas Gregor55abb232009-04-10 20:39:37 +00001163 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001164 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001165 return Failure;
1166 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001167
1168 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001169 RecordData Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001170 while (!Stream.AtEndOfStream()) {
1171 unsigned Code = Stream.ReadCode();
1172 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001173 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001174 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001175 return Failure;
1176 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001177
Douglas Gregor55abb232009-04-10 20:39:37 +00001178 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001179 }
1180
1181 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1182 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001183 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001184 // We lazily load the decls block, but we want to set up the
1185 // DeclsCursor cursor to point into it. Clone our current bitcode
1186 // cursor to it, enter the block and read the abbrevs in that block.
1187 // With the main cursor, we just skip over it.
1188 DeclsCursor = Stream;
1189 if (Stream.SkipBlock() || // Skip with the main cursor.
1190 // Read the abbrevs.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001191 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001192 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001193 return Failure;
1194 }
1195 break;
Mike Stump11289f42009-09-09 15:08:12 +00001196
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001197 case pch::PREPROCESSOR_BLOCK_ID:
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001198 MacroCursor = Stream;
1199 if (PP)
1200 PP->setExternalSource(this);
1201
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001202 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001203 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001204 return Failure;
1205 }
1206 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001207
Douglas Gregora7f71a92009-04-10 03:52:48 +00001208 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001209 switch (ReadSourceManagerBlock()) {
1210 case Success:
1211 break;
1212
1213 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001214 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001215 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001216
1217 case IgnorePCH:
1218 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001219 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001220 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001221 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001222 continue;
1223 }
1224
1225 if (Code == llvm::bitc::DEFINE_ABBREV) {
1226 Stream.ReadAbbrevRecord();
1227 continue;
1228 }
1229
1230 // Read and process a record.
1231 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001232 const char *BlobStart = 0;
1233 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001234 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001235 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001236 default: // Default behavior: ignore.
1237 break;
1238
1239 case pch::TYPE_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001240 if (!TypesLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001241 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001242 return Failure;
1243 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001244 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001245 TypesLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001246 break;
1247
1248 case pch::DECL_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001249 if (!DeclsLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001250 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001251 return Failure;
1252 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001253 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001254 DeclsLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001255 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001256
1257 case pch::LANGUAGE_OPTIONS:
1258 if (ParseLanguageOptions(Record))
1259 return IgnorePCH;
1260 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001261
Douglas Gregor7b71e632009-04-27 22:23:34 +00001262 case pch::METADATA: {
1263 if (Record[0] != pch::VERSION_MAJOR) {
1264 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1265 : diag::warn_pch_version_too_new);
1266 return IgnorePCH;
1267 }
1268
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001269 RelocatablePCH = Record[4];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001270 if (Listener) {
1271 std::string TargetTriple(BlobStart, BlobLen);
1272 if (Listener->ReadTargetTriple(TargetTriple))
1273 return IgnorePCH;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001274 }
1275 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001276 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001277
1278 case pch::IDENTIFIER_TABLE:
Douglas Gregora868bbd2009-04-21 22:25:48 +00001279 IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001280 if (Record[0]) {
Mike Stump11289f42009-09-09 15:08:12 +00001281 IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001282 = PCHIdentifierLookupTable::Create(
Douglas Gregora868bbd2009-04-21 22:25:48 +00001283 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001284 (const unsigned char *)IdentifierTableData,
Douglas Gregora868bbd2009-04-21 22:25:48 +00001285 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001286 if (PP)
1287 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001288 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001289 break;
1290
1291 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001292 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001293 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001294 return Failure;
1295 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001296 IdentifierOffsets = (const uint32_t *)BlobStart;
1297 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001298 if (PP)
1299 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001300 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001301
1302 case pch::EXTERNAL_DEFINITIONS:
1303 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001304 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001305 return Failure;
1306 }
1307 ExternalDefinitions.swap(Record);
1308 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001309
Douglas Gregor652d82a2009-04-18 05:55:16 +00001310 case pch::SPECIAL_TYPES:
1311 SpecialTypes.swap(Record);
1312 break;
1313
Douglas Gregor08f01292009-04-17 22:13:46 +00001314 case pch::STATISTICS:
1315 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001316 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001317 TotalLexicalDeclContexts = Record[2];
1318 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001319 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001320
Douglas Gregord4df8652009-04-22 22:02:47 +00001321 case pch::TENTATIVE_DEFINITIONS:
1322 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001323 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001324 return Failure;
1325 }
1326 TentativeDefinitions.swap(Record);
1327 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001328
1329 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1330 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001331 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001332 return Failure;
1333 }
1334 LocallyScopedExternalDecls.swap(Record);
1335 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001336
Douglas Gregor95c13f52009-04-25 17:48:32 +00001337 case pch::SELECTOR_OFFSETS:
1338 SelectorOffsets = (const uint32_t *)BlobStart;
1339 TotalNumSelectors = Record[0];
1340 SelectorsLoaded.resize(TotalNumSelectors);
1341 break;
1342
Douglas Gregorc78d3462009-04-24 21:10:55 +00001343 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001344 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1345 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001346 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001347 = PCHMethodPoolLookupTable::Create(
1348 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001349 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001350 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001351 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001352 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001353
1354 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001355 if (!Record.empty() && Listener)
1356 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001357 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001358
1359 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001360 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001361 TotalNumSLocEntries = Record[0];
Douglas Gregord54f3a12009-10-05 21:07:28 +00001362 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001363 break;
1364
1365 case pch::SOURCE_LOCATION_PRELOADS:
1366 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1367 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1368 if (Result != Success)
1369 return Result;
1370 }
1371 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001372
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001373 case pch::STAT_CACHE: {
1374 PCHStatCache *MyStatCache =
1375 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1376 (const unsigned char *)BlobStart,
1377 NumStatHits, NumStatMisses);
1378 FileMgr.addStatCache(MyStatCache);
1379 StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001380 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001381 }
1382
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001383 case pch::EXT_VECTOR_DECLS:
1384 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001385 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001386 return Failure;
1387 }
1388 ExtVectorDecls.swap(Record);
1389 break;
1390
Douglas Gregor45fe0362009-05-12 01:31:05 +00001391 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001392 ActualOriginalFileName.assign(BlobStart, BlobLen);
1393 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001394 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001395 break;
Mike Stump11289f42009-09-09 15:08:12 +00001396
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001397 case pch::COMMENT_RANGES:
1398 Comments = (SourceRange *)BlobStart;
1399 NumComments = BlobLen / sizeof(SourceRange);
1400 break;
Douglas Gregord54f3a12009-10-05 21:07:28 +00001401
1402 case pch::SVN_BRANCH_REVISION: {
1403 unsigned CurRevision = getClangSubversionRevision();
1404 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1405 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1406 : diag::warn_pch_version_too_new);
1407 return IgnorePCH;
1408 }
1409
1410 const char *CurBranch = getClangSubversionPath();
1411 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1412 std::string PCHBranch(BlobStart, BlobLen);
1413 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1414 return IgnorePCH;
1415 }
1416 break;
1417 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001418 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001419 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001420 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001421 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001422}
1423
Douglas Gregor92863e42009-04-10 23:10:45 +00001424PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001425 // Set the PCH file name.
1426 this->FileName = FileName;
1427
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001428 // Open the PCH file.
Daniel Dunbar2d925eb2009-09-22 05:38:01 +00001429 //
1430 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001431 std::string ErrStr;
Daniel Dunbar69914f42009-11-10 00:46:19 +00001432 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregor92863e42009-04-10 23:10:45 +00001433 if (!Buffer) {
1434 Error(ErrStr.c_str());
1435 return IgnorePCH;
1436 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001437
1438 // Initialize the stream
Mike Stump11289f42009-09-09 15:08:12 +00001439 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattner9356ace2009-04-26 20:59:20 +00001440 (const unsigned char *)Buffer->getBufferEnd());
1441 Stream.init(StreamFile);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001442
1443 // Sniff for the signature.
1444 if (Stream.Read(8) != 'C' ||
1445 Stream.Read(8) != 'P' ||
1446 Stream.Read(8) != 'C' ||
Douglas Gregor92863e42009-04-10 23:10:45 +00001447 Stream.Read(8) != 'H') {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001448 Diag(diag::err_not_a_pch_file) << FileName;
1449 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001450 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001451
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001452 while (!Stream.AtEndOfStream()) {
1453 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001454
Douglas Gregor92863e42009-04-10 23:10:45 +00001455 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001456 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001457 return Failure;
1458 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001459
1460 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001461
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001462 // We only know the PCH subblock ID.
1463 switch (BlockID) {
1464 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001465 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001466 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001467 return Failure;
1468 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001469 break;
1470 case pch::PCH_BLOCK_ID:
Douglas Gregoreda6a892009-04-26 00:07:37 +00001471 switch (ReadPCHBlock()) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001472 case Success:
1473 break;
1474
1475 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001476 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001477
1478 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001479 // FIXME: We could consider reading through to the end of this
1480 // PCH block, skipping subblocks, to see if there are other
1481 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001482
1483 // Clear out any preallocated source location entries, so that
1484 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001485 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001486
1487 // Remove the stat cache.
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001488 if (StatCache)
1489 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001490
Douglas Gregor92863e42009-04-10 23:10:45 +00001491 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001492 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001493 break;
1494 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001495 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001496 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001497 return Failure;
1498 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001499 break;
1500 }
Mike Stump11289f42009-09-09 15:08:12 +00001501 }
1502
Douglas Gregore6648fb2009-04-28 20:33:11 +00001503 // Check the predefines buffer.
Daniel Dunbar20a682d2009-11-11 00:52:11 +00001504 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregore6648fb2009-04-28 20:33:11 +00001505 PCHPredefinesBufferID))
1506 return IgnorePCH;
Mike Stump11289f42009-09-09 15:08:12 +00001507
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001508 if (PP) {
Zhongxing Xu3f51f412009-07-18 09:26:51 +00001509 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001510 // PCH file is read, so there may be some identifiers that were
1511 // loaded into the IdentifierTable before we intercepted the
1512 // creation of identifiers. Iterate through the list of known
1513 // identifiers and determine whether we have to establish
1514 // preprocessor definitions or top-level identifier declaration
1515 // chains for those identifiers.
1516 //
1517 // We copy the IdentifierInfo pointers to a small vector first,
1518 // since de-serializing declarations or macro definitions can add
1519 // new entries into the identifier table, invalidating the
1520 // iterators.
1521 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1522 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1523 IdEnd = PP->getIdentifierTable().end();
1524 Id != IdEnd; ++Id)
1525 Identifiers.push_back(Id->second);
Mike Stump11289f42009-09-09 15:08:12 +00001526 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001527 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1528 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1529 IdentifierInfo *II = Identifiers[I];
1530 // Look in the on-disk hash table for an entry for
1531 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001532 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001533 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1534 if (Pos == IdTable->end())
1535 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001536
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001537 // Dereferencing the iterator has the effect of populating the
1538 // IdentifierInfo node with the various declarations it needs.
1539 (void)*Pos;
1540 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001541 }
1542
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001543 if (Context)
1544 InitializeContext(*Context);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001545
Douglas Gregora868bbd2009-04-21 22:25:48 +00001546 return Success;
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001547}
1548
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001549void PCHReader::InitializeContext(ASTContext &Ctx) {
1550 Context = &Ctx;
1551 assert(Context && "Passed null context!");
1552
1553 assert(PP && "Forgot to set Preprocessor ?");
1554 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1555 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001556 PP->setExternalSource(this);
1557
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001558 // Load the translation unit declaration
1559 ReadDeclRecord(DeclOffsets[0], 0);
1560
1561 // Load the special types.
1562 Context->setBuiltinVaListType(
1563 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1564 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1565 Context->setObjCIdType(GetType(Id));
1566 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1567 Context->setObjCSelType(GetType(Sel));
1568 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1569 Context->setObjCProtoType(GetType(Proto));
1570 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1571 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001572
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001573 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1574 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001575 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001576 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1577 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001578 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1579 QualType FileType = GetType(File);
1580 assert(!FileType.isNull() && "FILE type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001581 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001582 Context->setFILEDecl(Typedef->getDecl());
1583 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001584 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregor27821ce2009-07-07 16:35:42 +00001585 assert(Tag && "Invalid FILE type in PCH file");
1586 Context->setFILEDecl(Tag->getDecl());
1587 }
1588 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001589 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1590 QualType Jmp_bufType = GetType(Jmp_buf);
1591 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001592 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001593 Context->setjmp_bufDecl(Typedef->getDecl());
1594 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001595 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001596 assert(Tag && "Invalid jmp_bug type in PCH file");
1597 Context->setjmp_bufDecl(Tag->getDecl());
1598 }
1599 }
1600 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1601 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1602 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001603 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001604 Context->setsigjmp_bufDecl(Typedef->getDecl());
1605 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001606 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001607 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1608 Context->setsigjmp_bufDecl(Tag->getDecl());
1609 }
1610 }
Mike Stump11289f42009-09-09 15:08:12 +00001611 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001612 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1613 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001614 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001615 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1616 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001617#if 0
1618 // FIXME. Accommodate for this in several PCH/Index tests
1619 if (unsigned ObjCSelRedef
1620 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00001621 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001622#endif
Mike Stumpd0153282009-10-20 02:12:22 +00001623 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1624 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00001625 if (unsigned String
1626 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1627 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001628}
1629
Douglas Gregor45fe0362009-05-12 01:31:05 +00001630/// \brief Retrieve the name of the original source file name
1631/// directly from the PCH file, without actually loading the PCH
1632/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00001633std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1634 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00001635 // Open the PCH file.
1636 std::string ErrStr;
1637 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1638 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1639 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001640 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001641 return std::string();
1642 }
1643
1644 // Initialize the stream
1645 llvm::BitstreamReader StreamFile;
1646 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001647 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001648 (const unsigned char *)Buffer->getBufferEnd());
1649 Stream.init(StreamFile);
1650
1651 // Sniff for the signature.
1652 if (Stream.Read(8) != 'C' ||
1653 Stream.Read(8) != 'P' ||
1654 Stream.Read(8) != 'C' ||
1655 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001656 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001657 return std::string();
1658 }
1659
1660 RecordData Record;
1661 while (!Stream.AtEndOfStream()) {
1662 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001663
Douglas Gregor45fe0362009-05-12 01:31:05 +00001664 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1665 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001666
Douglas Gregor45fe0362009-05-12 01:31:05 +00001667 // We only know the PCH subblock ID.
1668 switch (BlockID) {
1669 case pch::PCH_BLOCK_ID:
1670 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001671 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001672 return std::string();
1673 }
1674 break;
Mike Stump11289f42009-09-09 15:08:12 +00001675
Douglas Gregor45fe0362009-05-12 01:31:05 +00001676 default:
1677 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001678 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001679 return std::string();
1680 }
1681 break;
1682 }
1683 continue;
1684 }
1685
1686 if (Code == llvm::bitc::END_BLOCK) {
1687 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001688 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001689 return std::string();
1690 }
1691 continue;
1692 }
1693
1694 if (Code == llvm::bitc::DEFINE_ABBREV) {
1695 Stream.ReadAbbrevRecord();
1696 continue;
1697 }
1698
1699 Record.clear();
1700 const char *BlobStart = 0;
1701 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001702 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00001703 == pch::ORIGINAL_FILE_NAME)
1704 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00001705 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00001706
1707 return std::string();
1708}
1709
Douglas Gregor55abb232009-04-10 20:39:37 +00001710/// \brief Parse the record that corresponds to a LangOptions data
1711/// structure.
1712///
1713/// This routine compares the language options used to generate the
1714/// PCH file against the language options set for the current
1715/// compilation. For each option, we classify differences between the
1716/// two compiler states as either "benign" or "important". Benign
1717/// differences don't matter, and we accept them without complaint
1718/// (and without modifying the language options). Differences between
1719/// the states for important options cause the PCH file to be
1720/// unusable, so we emit a warning and return true to indicate that
1721/// there was an error.
1722///
1723/// \returns true if the PCH file is unacceptable, false otherwise.
1724bool PCHReader::ParseLanguageOptions(
1725 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001726 if (Listener) {
1727 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00001728
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001729 #define PARSE_LANGOPT(Option) \
1730 LangOpts.Option = Record[Idx]; \
1731 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00001732
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001733 unsigned Idx = 0;
1734 PARSE_LANGOPT(Trigraphs);
1735 PARSE_LANGOPT(BCPLComment);
1736 PARSE_LANGOPT(DollarIdents);
1737 PARSE_LANGOPT(AsmPreprocessor);
1738 PARSE_LANGOPT(GNUMode);
1739 PARSE_LANGOPT(ImplicitInt);
1740 PARSE_LANGOPT(Digraphs);
1741 PARSE_LANGOPT(HexFloats);
1742 PARSE_LANGOPT(C99);
1743 PARSE_LANGOPT(Microsoft);
1744 PARSE_LANGOPT(CPlusPlus);
1745 PARSE_LANGOPT(CPlusPlus0x);
1746 PARSE_LANGOPT(CXXOperatorNames);
1747 PARSE_LANGOPT(ObjC1);
1748 PARSE_LANGOPT(ObjC2);
1749 PARSE_LANGOPT(ObjCNonFragileABI);
1750 PARSE_LANGOPT(PascalStrings);
1751 PARSE_LANGOPT(WritableStrings);
1752 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00001753 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001754 PARSE_LANGOPT(Exceptions);
1755 PARSE_LANGOPT(NeXTRuntime);
1756 PARSE_LANGOPT(Freestanding);
1757 PARSE_LANGOPT(NoBuiltin);
1758 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00001759 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001760 PARSE_LANGOPT(Blocks);
1761 PARSE_LANGOPT(EmitAllDecls);
1762 PARSE_LANGOPT(MathErrno);
1763 PARSE_LANGOPT(OverflowChecking);
1764 PARSE_LANGOPT(HeinousExtensions);
1765 PARSE_LANGOPT(Optimize);
1766 PARSE_LANGOPT(OptimizeSize);
1767 PARSE_LANGOPT(Static);
1768 PARSE_LANGOPT(PICLevel);
1769 PARSE_LANGOPT(GNUInline);
1770 PARSE_LANGOPT(NoInline);
1771 PARSE_LANGOPT(AccessControl);
1772 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00001773 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001774 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1775 ++Idx;
1776 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1777 ++Idx;
Daniel Dunbar143021e2009-09-21 04:16:19 +00001778 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1779 Record[Idx]);
1780 ++Idx;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001781 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00001782 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00001783 PARSE_LANGOPT(CatchUndefined);
1784 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001785 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00001786
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001787 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00001788 }
Douglas Gregor55abb232009-04-10 20:39:37 +00001789
1790 return false;
1791}
1792
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001793void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1794 Comments.resize(NumComments);
1795 std::copy(this->Comments, this->Comments + NumComments,
1796 Comments.begin());
1797}
1798
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001799/// \brief Read and return the type at the given offset.
1800///
1801/// This routine actually reads the record corresponding to the type
1802/// at the given offset in the bitstream. It is a helper routine for
1803/// GetType, which deals with reading type IDs.
1804QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001805 // Keep track of where we are in the stream, then jump back there
1806 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001807 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001808
Douglas Gregor1342e842009-07-06 18:54:52 +00001809 // Note that we are loading a type record.
1810 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00001811
Douglas Gregor12bfa382009-10-17 00:13:19 +00001812 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001813 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00001814 unsigned Code = DeclsCursor.ReadCode();
1815 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00001816 case pch::TYPE_EXT_QUAL: {
John McCall8ccfcb52009-09-24 19:53:00 +00001817 assert(Record.size() == 2 &&
Douglas Gregor455b8f42009-04-15 22:00:08 +00001818 "Incorrect encoding of extended qualifier type");
1819 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00001820 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1821 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00001822 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001823
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001824 case pch::TYPE_COMPLEX: {
1825 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1826 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001827 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001828 }
1829
1830 case pch::TYPE_POINTER: {
1831 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1832 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001833 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001834 }
1835
1836 case pch::TYPE_BLOCK_POINTER: {
1837 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1838 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001839 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001840 }
1841
1842 case pch::TYPE_LVALUE_REFERENCE: {
1843 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1844 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001845 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001846 }
1847
1848 case pch::TYPE_RVALUE_REFERENCE: {
1849 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1850 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001851 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001852 }
1853
1854 case pch::TYPE_MEMBER_POINTER: {
1855 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1856 QualType PointeeType = GetType(Record[0]);
1857 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001858 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001859 }
1860
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001861 case pch::TYPE_CONSTANT_ARRAY: {
1862 QualType ElementType = GetType(Record[0]);
1863 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1864 unsigned IndexTypeQuals = Record[2];
1865 unsigned Idx = 3;
1866 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00001867 return Context->getConstantArrayType(ElementType, Size,
1868 ASM, IndexTypeQuals);
1869 }
1870
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001871 case pch::TYPE_INCOMPLETE_ARRAY: {
1872 QualType ElementType = GetType(Record[0]);
1873 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1874 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00001875 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001876 }
1877
1878 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001879 QualType ElementType = GetType(Record[0]);
1880 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1881 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00001882 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1883 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001884 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00001885 ASM, IndexTypeQuals,
1886 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001887 }
1888
1889 case pch::TYPE_VECTOR: {
1890 if (Record.size() != 2) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001891 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001892 return QualType();
1893 }
1894
1895 QualType ElementType = GetType(Record[0]);
1896 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001897 return Context->getVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001898 }
1899
1900 case pch::TYPE_EXT_VECTOR: {
1901 if (Record.size() != 2) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001902 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001903 return QualType();
1904 }
1905
1906 QualType ElementType = GetType(Record[0]);
1907 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001908 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001909 }
1910
1911 case pch::TYPE_FUNCTION_NO_PROTO: {
Douglas Gregordc728752009-12-22 18:11:50 +00001912 if (Record.size() != 2) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001913 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001914 return QualType();
1915 }
1916 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00001917 return Context->getFunctionNoProtoType(ResultType, Record[1]);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001918 }
1919
1920 case pch::TYPE_FUNCTION_PROTO: {
1921 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00001922 bool NoReturn = Record[1];
1923 unsigned Idx = 2;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001924 unsigned NumParams = Record[Idx++];
1925 llvm::SmallVector<QualType, 16> ParamTypes;
1926 for (unsigned I = 0; I != NumParams; ++I)
1927 ParamTypes.push_back(GetType(Record[Idx++]));
1928 bool isVariadic = Record[Idx++];
1929 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001930 bool hasExceptionSpec = Record[Idx++];
1931 bool hasAnyExceptionSpec = Record[Idx++];
1932 unsigned NumExceptions = Record[Idx++];
1933 llvm::SmallVector<QualType, 2> Exceptions;
1934 for (unsigned I = 0; I != NumExceptions; ++I)
1935 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00001936 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001937 isVariadic, Quals, hasExceptionSpec,
1938 hasAnyExceptionSpec, NumExceptions,
Douglas Gregordc728752009-12-22 18:11:50 +00001939 Exceptions.data(), NoReturn);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001940 }
1941
John McCallb96ec562009-12-04 22:46:56 +00001942 case pch::TYPE_UNRESOLVED_USING:
1943 return Context->getTypeDeclType(
1944 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
1945
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001946 case pch::TYPE_TYPEDEF:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001947 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001948 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001949
1950 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner8575daa2009-04-27 21:45:14 +00001951 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001952
1953 case pch::TYPE_TYPEOF: {
1954 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001955 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001956 return QualType();
1957 }
1958 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001959 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001960 }
Mike Stump11289f42009-09-09 15:08:12 +00001961
Anders Carlsson81df7b82009-06-24 19:06:50 +00001962 case pch::TYPE_DECLTYPE:
1963 return Context->getDecltypeType(ReadTypeExpr());
1964
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001965 case pch::TYPE_RECORD:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001966 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001967 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001968
Douglas Gregor1daeb692009-04-13 18:14:40 +00001969 case pch::TYPE_ENUM:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001970 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001971 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor1daeb692009-04-13 18:14:40 +00001972
John McCallfcc33b02009-09-05 00:15:47 +00001973 case pch::TYPE_ELABORATED: {
1974 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1975 unsigned Tag = Record[1];
1976 return Context->getElaboratedType(GetType(Record[0]),
1977 (ElaboratedType::TagKind) Tag);
1978 }
1979
Steve Naroffc277ad12009-07-18 15:33:26 +00001980 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00001981 unsigned Idx = 0;
1982 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1983 unsigned NumProtos = Record[Idx++];
1984 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1985 for (unsigned I = 0; I != NumProtos; ++I)
1986 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc277ad12009-07-18 15:33:26 +00001987 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00001988 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001989
Steve Narofffb4330f2009-06-17 22:40:22 +00001990 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00001991 unsigned Idx = 0;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001992 QualType OIT = GetType(Record[Idx++]);
Chris Lattner6e054af2009-04-22 06:40:03 +00001993 unsigned NumProtos = Record[Idx++];
1994 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1995 for (unsigned I = 0; I != NumProtos; ++I)
1996 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001997 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattner6e054af2009-04-22 06:40:03 +00001998 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00001999
John McCallcebee162009-10-18 09:09:24 +00002000 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2001 unsigned Idx = 0;
2002 QualType Parm = GetType(Record[Idx++]);
2003 QualType Replacement = GetType(Record[Idx++]);
2004 return
2005 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2006 Replacement);
2007 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002008 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002009 // Suppress a GCC warning
2010 return QualType();
2011}
2012
John McCall8f115c62009-10-16 21:56:05 +00002013namespace {
2014
2015class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2016 PCHReader &Reader;
2017 const PCHReader::RecordData &Record;
2018 unsigned &Idx;
2019
2020public:
2021 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2022 unsigned &Idx)
2023 : Reader(Reader), Record(Record), Idx(Idx) { }
2024
John McCall17001972009-10-18 01:05:36 +00002025 // We want compile-time assurance that we've enumerated all of
2026 // these, so unfortunately we have to declare them first, then
2027 // define them out-of-line.
2028#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002029#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002030 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002031#include "clang/AST/TypeLocNodes.def"
2032
John McCall17001972009-10-18 01:05:36 +00002033 void VisitFunctionTypeLoc(FunctionTypeLoc);
2034 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002035};
2036
2037}
2038
John McCall17001972009-10-18 01:05:36 +00002039void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002040 // nothing to do
2041}
John McCall17001972009-10-18 01:05:36 +00002042void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2043 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002044}
John McCall17001972009-10-18 01:05:36 +00002045void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2046 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002047}
John McCall17001972009-10-18 01:05:36 +00002048void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2049 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002050}
John McCall17001972009-10-18 01:05:36 +00002051void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2052 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002053}
John McCall17001972009-10-18 01:05:36 +00002054void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2055 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002056}
John McCall17001972009-10-18 01:05:36 +00002057void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2058 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002059}
John McCall17001972009-10-18 01:05:36 +00002060void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2061 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002062}
John McCall17001972009-10-18 01:05:36 +00002063void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2064 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2065 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002066 if (Record[Idx++])
John McCall17001972009-10-18 01:05:36 +00002067 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor12bfa382009-10-17 00:13:19 +00002068 else
John McCall17001972009-10-18 01:05:36 +00002069 TL.setSizeExpr(0);
2070}
2071void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2072 VisitArrayTypeLoc(TL);
2073}
2074void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2075 VisitArrayTypeLoc(TL);
2076}
2077void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2078 VisitArrayTypeLoc(TL);
2079}
2080void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2081 DependentSizedArrayTypeLoc TL) {
2082 VisitArrayTypeLoc(TL);
2083}
2084void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2085 DependentSizedExtVectorTypeLoc TL) {
2086 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2087}
2088void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2089 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2090}
2091void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2092 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2093}
2094void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2095 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2096 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2097 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002098 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002099 }
2100}
2101void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2102 VisitFunctionTypeLoc(TL);
2103}
2104void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2105 VisitFunctionTypeLoc(TL);
2106}
John McCallb96ec562009-12-04 22:46:56 +00002107void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2108 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2109}
John McCall17001972009-10-18 01:05:36 +00002110void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2111 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2112}
2113void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2114 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2115}
2116void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2117 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2118}
2119void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2120 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2121}
2122void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2123 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2124}
2125void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2126 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2127}
2128void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2129 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2130}
2131void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2132 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2133}
John McCallcebee162009-10-18 09:09:24 +00002134void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2135 SubstTemplateTypeParmTypeLoc TL) {
2136 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2137}
John McCall17001972009-10-18 01:05:36 +00002138void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2139 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002140 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2141 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2142 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2143 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2144 TL.setArgLocInfo(i,
2145 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2146 Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002147}
2148void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2149 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2150}
2151void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2152 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2153}
2154void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2155 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002156 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2157 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2158 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2159 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002160}
John McCallfc93cf92009-10-22 22:37:11 +00002161void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2162 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2163 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2164 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2165 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2166 TL.setHasProtocolsAsWritten(Record[Idx++]);
2167 if (TL.hasProtocolsAsWritten())
2168 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2169 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2170}
John McCall8f115c62009-10-16 21:56:05 +00002171
John McCallbcd03502009-12-07 02:54:59 +00002172TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002173 unsigned &Idx) {
2174 QualType InfoTy = GetType(Record[Idx++]);
2175 if (InfoTy.isNull())
2176 return 0;
2177
John McCallbcd03502009-12-07 02:54:59 +00002178 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCall8f115c62009-10-16 21:56:05 +00002179 TypeLocReader TLR(*this, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002180 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002181 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002182 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002183}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002184
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002185QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002186 unsigned FastQuals = ID & Qualifiers::FastMask;
2187 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002188
2189 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2190 QualType T;
2191 switch ((pch::PredefinedTypeIDs)Index) {
2192 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002193 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2194 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002195
2196 case pch::PREDEF_TYPE_CHAR_U_ID:
2197 case pch::PREDEF_TYPE_CHAR_S_ID:
2198 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002199 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002200 break;
2201
Chris Lattner8575daa2009-04-27 21:45:14 +00002202 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2203 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2204 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2205 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2206 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002207 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002208 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2209 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2210 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2211 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2212 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2213 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002214 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002215 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2216 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2217 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2218 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2219 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002220 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002221 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2222 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002223 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2224 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002225 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002226 }
2227
2228 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002229 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002230 }
2231
2232 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002233 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall8ccfcb52009-09-24 19:53:00 +00002234 if (TypesLoaded[Index].isNull())
2235 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump11289f42009-09-09 15:08:12 +00002236
John McCall8ccfcb52009-09-24 19:53:00 +00002237 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002238}
2239
John McCall0ad16662009-10-29 08:12:44 +00002240TemplateArgumentLocInfo
2241PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2242 const RecordData &Record,
2243 unsigned &Index) {
2244 switch (Kind) {
2245 case TemplateArgument::Expression:
2246 return ReadDeclExpr();
2247 case TemplateArgument::Type:
John McCallbcd03502009-12-07 02:54:59 +00002248 return GetTypeSourceInfo(Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002249 case TemplateArgument::Template: {
2250 SourceLocation
2251 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2252 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2253 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2254 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2255 TemplateNameLoc);
2256 }
John McCall0ad16662009-10-29 08:12:44 +00002257 case TemplateArgument::Null:
2258 case TemplateArgument::Integral:
2259 case TemplateArgument::Declaration:
2260 case TemplateArgument::Pack:
2261 return TemplateArgumentLocInfo();
2262 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002263 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002264 return TemplateArgumentLocInfo();
2265}
2266
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002267Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002268 if (ID == 0)
2269 return 0;
2270
Douglas Gregor745ed142009-04-25 18:35:21 +00002271 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002272 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002273 return 0;
2274 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002275
Douglas Gregor745ed142009-04-25 18:35:21 +00002276 unsigned Index = ID - 1;
2277 if (!DeclsLoaded[Index])
2278 ReadDeclRecord(DeclOffsets[Index], Index);
2279
2280 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002281}
2282
Chris Lattner9c28af02009-04-27 05:46:25 +00002283/// \brief Resolve the offset of a statement into a statement.
2284///
2285/// This operation will read a new statement from the external
2286/// source each time it is called, and is meant to be used via a
2287/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2288Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002289 // Since we know tha this statement is part of a decl, make sure to use the
2290 // decl cursor to read it.
2291 DeclsCursor.JumpToBit(Offset);
2292 return ReadStmt(DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002293}
2294
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002295bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002296 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002297 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002298 "DeclContext has no lexical decls in storage");
2299 uint64_t Offset = DeclContextOffsets[DC].first;
2300 assert(Offset && "DeclContext has no lexical decls in storage");
2301
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002302 // Keep track of where we are in the stream, then jump back there
2303 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002304 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002305
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002306 // Load the record containing all of the declarations lexically in
2307 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002308 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002309 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002310 unsigned Code = DeclsCursor.ReadCode();
2311 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002312 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002313 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2314
2315 // Load all of the declaration IDs
2316 Decls.clear();
2317 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002318 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002319 return false;
2320}
2321
2322bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner72405d62009-04-27 07:35:40 +00002323 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002324 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002325 "DeclContext has no visible decls in storage");
2326 uint64_t Offset = DeclContextOffsets[DC].second;
2327 assert(Offset && "DeclContext has no visible decls in storage");
2328
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002329 // Keep track of where we are in the stream, then jump back there
2330 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002331 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002332
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002333 // Load the record containing all of the declarations visible in
2334 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002335 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002336 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002337 unsigned Code = DeclsCursor.ReadCode();
2338 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002339 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002340 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2341 if (Record.size() == 0)
Mike Stump11289f42009-09-09 15:08:12 +00002342 return false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002343
2344 Decls.clear();
2345
2346 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002347 while (Idx < Record.size()) {
2348 Decls.push_back(VisibleDeclaration());
2349 Decls.back().Name = ReadDeclarationName(Record, Idx);
2350
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002351 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002352 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002353 LoadedDecls.reserve(Size);
2354 for (unsigned I = 0; I < Size; ++I)
2355 LoadedDecls.push_back(Record[Idx++]);
2356 }
2357
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002358 ++NumVisibleDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002359 return false;
2360}
2361
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002362void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002363 this->Consumer = Consumer;
2364
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002365 if (!Consumer)
2366 return;
2367
2368 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002369 // Force deserialization of this decl, which will cause it to be passed to
2370 // the consumer (or queued).
2371 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002372 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002373
2374 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2375 DeclGroupRef DG(InterestingDecls[I]);
2376 Consumer->HandleTopLevelDecl(DG);
2377 }
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002378}
2379
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002380void PCHReader::PrintStats() {
2381 std::fprintf(stderr, "*** PCH Statistics:\n");
2382
Mike Stump11289f42009-09-09 15:08:12 +00002383 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002384 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00002385 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00002386 unsigned NumDeclsLoaded
2387 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2388 (Decl *)0);
2389 unsigned NumIdentifiersLoaded
2390 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2391 IdentifiersLoaded.end(),
2392 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002393 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002394 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2395 SelectorsLoaded.end(),
2396 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002397
Douglas Gregorc5046832009-04-27 18:38:38 +00002398 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2399 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002400 if (TotalNumSLocEntries)
2401 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2402 NumSLocEntriesRead, TotalNumSLocEntries,
2403 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002404 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002405 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002406 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2407 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2408 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002409 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002410 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2411 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002412 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002413 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002414 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2415 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002416 if (TotalNumSelectors)
2417 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2418 NumSelectorsLoaded, TotalNumSelectors,
2419 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2420 if (TotalNumStatements)
2421 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2422 NumStatementsRead, TotalNumStatements,
2423 ((float)NumStatementsRead/TotalNumStatements * 100));
2424 if (TotalNumMacros)
2425 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2426 NumMacrosRead, TotalNumMacros,
2427 ((float)NumMacrosRead/TotalNumMacros * 100));
2428 if (TotalLexicalDeclContexts)
2429 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2430 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2431 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2432 * 100));
2433 if (TotalVisibleDeclContexts)
2434 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2435 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2436 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2437 * 100));
2438 if (TotalSelectorsInMethodPool) {
2439 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2440 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2441 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2442 * 100));
2443 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2444 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002445 std::fprintf(stderr, "\n");
2446}
2447
Douglas Gregora868bbd2009-04-21 22:25:48 +00002448void PCHReader::InitializeSema(Sema &S) {
2449 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002450 S.ExternalSource = this;
2451
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002452 // Makes sure any declarations that were deserialized "too early"
2453 // still get added to the identifier's declaration chains.
2454 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2455 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2456 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002457 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002458 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002459
2460 // If there were any tentative definitions, deserialize them and add
2461 // them to Sema's table of tentative definitions.
2462 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2463 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2464 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner0c797362009-09-08 18:19:27 +00002465 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregord4df8652009-04-22 22:02:47 +00002466 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002467
2468 // If there were any locally-scoped external declarations,
2469 // deserialize them and add them to Sema's table of locally-scoped
2470 // external declarations.
2471 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2472 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2473 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2474 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002475
2476 // If there were any ext_vector type declarations, deserialize them
2477 // and add them to Sema's vector of such declarations.
2478 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2479 SemaObj->ExtVectorDecls.push_back(
2480 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00002481}
2482
2483IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2484 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00002485 PCHIdentifierLookupTable *IdTable
Douglas Gregora868bbd2009-04-21 22:25:48 +00002486 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2487 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2488 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2489 if (Pos == IdTable->end())
2490 return 0;
2491
2492 // Dereferencing the iterator has the effect of building the
2493 // IdentifierInfo node and populating it with the various
2494 // declarations it needs.
2495 return *Pos;
2496}
2497
Mike Stump11289f42009-09-09 15:08:12 +00002498std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00002499PCHReader::ReadMethodPool(Selector Sel) {
2500 if (!MethodPoolLookupTable)
2501 return std::pair<ObjCMethodList, ObjCMethodList>();
2502
2503 // Try to find this selector within our on-disk hash table.
2504 PCHMethodPoolLookupTable *PoolTable
2505 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2506 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00002507 if (Pos == PoolTable->end()) {
2508 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002509 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00002510 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00002511
Douglas Gregor95c13f52009-04-25 17:48:32 +00002512 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002513 return *Pos;
2514}
2515
Douglas Gregor0e149972009-04-25 19:10:14 +00002516void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00002517 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002518 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00002519 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00002520}
2521
Douglas Gregor1342e842009-07-06 18:54:52 +00002522/// \brief Set the globally-visible declarations associated with the given
2523/// identifier.
2524///
2525/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00002526/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00002527/// them.
2528///
2529/// \param II an IdentifierInfo that refers to one or more globally-visible
2530/// declarations.
2531///
2532/// \param DeclIDs the set of declaration IDs with the name @p II that are
2533/// visible at global scope.
2534///
2535/// \param Nonrecursive should be true to indicate that the caller knows that
2536/// this call is non-recursive, and therefore the globally-visible declarations
2537/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00002538void
2539PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00002540 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2541 bool Nonrecursive) {
2542 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2543 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2544 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2545 PII.II = II;
2546 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2547 PII.DeclIDs.push_back(DeclIDs[I]);
2548 return;
2549 }
Mike Stump11289f42009-09-09 15:08:12 +00002550
Douglas Gregor1342e842009-07-06 18:54:52 +00002551 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2552 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2553 if (SemaObj) {
2554 // Introduce this declaration into the translation-unit scope
2555 // and add it to the declaration chain for this identifier, so
2556 // that (unqualified) name lookup will find it.
2557 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2558 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2559 } else {
2560 // Queue this declaration so that it will be added to the
2561 // translation unit scope and identifier's declaration chain
2562 // once a Sema object is known.
2563 PreloadedDecls.push_back(D);
2564 }
2565 }
2566}
2567
Chris Lattnerc523d8e2009-04-11 21:15:38 +00002568IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002569 if (ID == 0)
2570 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002571
Douglas Gregor0e149972009-04-25 19:10:14 +00002572 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002573 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002574 return 0;
2575 }
Mike Stump11289f42009-09-09 15:08:12 +00002576
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002577 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00002578 if (!IdentifiersLoaded[ID - 1]) {
2579 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor95272492009-04-25 21:21:38 +00002580 const char *Str = IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00002581
Douglas Gregorab4df582009-04-28 20:01:51 +00002582 // All of the strings in the PCH file are preceded by a 16-bit
2583 // length. Extract that 16-bit length to avoid having to execute
2584 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00002585 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2586 // unsigned integers. This is important to avoid integer overflow when
2587 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00002588 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00002589 unsigned StrLen = (((unsigned) StrLenPtr[0])
2590 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00002591 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002592 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002593 }
Mike Stump11289f42009-09-09 15:08:12 +00002594
Douglas Gregor0e149972009-04-25 19:10:14 +00002595 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002596}
2597
Douglas Gregor258ae542009-04-27 06:38:32 +00002598void PCHReader::ReadSLocEntry(unsigned ID) {
2599 ReadSLocEntryRecord(ID);
2600}
2601
Steve Naroff2ddea052009-04-23 10:39:46 +00002602Selector PCHReader::DecodeSelector(unsigned ID) {
2603 if (ID == 0)
2604 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00002605
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002606 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00002607 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002608
2609 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002610 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00002611 return Selector();
2612 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00002613
2614 unsigned Index = ID - 1;
2615 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2616 // Load this selector from the selector table.
2617 // FIXME: endianness portability issues with SelectorOffsets table
2618 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002619 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00002620 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2621 }
2622
2623 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00002624}
2625
Mike Stump11289f42009-09-09 15:08:12 +00002626DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002627PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2628 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2629 switch (Kind) {
2630 case DeclarationName::Identifier:
2631 return DeclarationName(GetIdentifierInfo(Record, Idx));
2632
2633 case DeclarationName::ObjCZeroArgSelector:
2634 case DeclarationName::ObjCOneArgSelector:
2635 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00002636 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002637
2638 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002639 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002640 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002641
2642 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002643 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002644 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002645
2646 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002647 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002648 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002649
2650 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002651 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002652 (OverloadedOperatorKind)Record[Idx++]);
2653
Alexis Hunt3d221f22009-11-29 07:34:05 +00002654 case DeclarationName::CXXLiteralOperatorName:
2655 return Context->DeclarationNames.getCXXLiteralOperatorName(
2656 GetIdentifierInfo(Record, Idx));
2657
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002658 case DeclarationName::CXXUsingDirective:
2659 return DeclarationName::getUsingDirectiveName();
2660 }
2661
2662 // Required to silence GCC warning
2663 return DeclarationName();
2664}
Douglas Gregor55abb232009-04-10 20:39:37 +00002665
Douglas Gregor1daeb692009-04-13 18:14:40 +00002666/// \brief Read an integral value
2667llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2668 unsigned BitWidth = Record[Idx++];
2669 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2670 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2671 Idx += NumWords;
2672 return Result;
2673}
2674
2675/// \brief Read a signed integral value
2676llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2677 bool isUnsigned = Record[Idx++];
2678 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2679}
2680
Douglas Gregore0a3a512009-04-14 21:55:33 +00002681/// \brief Read a floating-point value
2682llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00002683 return llvm::APFloat(ReadAPInt(Record, Idx));
2684}
2685
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002686// \brief Read a string
2687std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2688 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00002689 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002690 Idx += Len;
2691 return Result;
2692}
2693
Douglas Gregor55abb232009-04-10 20:39:37 +00002694DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00002695 return Diag(SourceLocation(), DiagID);
2696}
2697
2698DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002699 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00002700}
Douglas Gregora9af1d12009-04-17 00:04:06 +00002701
Douglas Gregora868bbd2009-04-21 22:25:48 +00002702/// \brief Retrieve the identifier table associated with the
2703/// preprocessor.
2704IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002705 assert(PP && "Forgot to set Preprocessor ?");
2706 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00002707}
2708
Douglas Gregora9af1d12009-04-17 00:04:06 +00002709/// \brief Record that the given ID maps to the given switch-case
2710/// statement.
2711void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2712 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2713 SwitchCaseStmts[ID] = SC;
2714}
2715
2716/// \brief Retrieve the switch-case statement with the given ID.
2717SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2718 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2719 return SwitchCaseStmts[ID];
2720}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002721
2722/// \brief Record that the given label statement has been
2723/// deserialized and has the given ID.
2724void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00002725 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002726 "Deserialized label twice");
2727 LabelStmts[ID] = S;
2728
2729 // If we've already seen any goto statements that point to this
2730 // label, resolve them now.
2731 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2732 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2733 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2734 Goto->second->setLabel(S);
2735 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00002736
2737 // If we've already seen any address-label statements that point to
2738 // this label, resolve them now.
2739 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00002740 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00002741 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00002742 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00002743 AddrLabel != AddrLabels.second; ++AddrLabel)
2744 AddrLabel->second->setLabel(S);
2745 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002746}
2747
2748/// \brief Set the label of the given statement to the label
2749/// identified by ID.
2750///
2751/// Depending on the order in which the label and other statements
2752/// referencing that label occur, this operation may complete
2753/// immediately (updating the statement) or it may queue the
2754/// statement to be back-patched later.
2755void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2756 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2757 if (Label != LabelStmts.end()) {
2758 // We've already seen this label, so set the label of the goto and
2759 // we're done.
2760 S->setLabel(Label->second);
2761 } else {
2762 // We haven't seen this label yet, so add this goto to the set of
2763 // unresolved goto statements.
2764 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2765 }
2766}
Douglas Gregor779d8652009-04-17 18:58:21 +00002767
2768/// \brief Set the label of the given expression to the label
2769/// identified by ID.
2770///
2771/// Depending on the order in which the label and other statements
2772/// referencing that label occur, this operation may complete
2773/// immediately (updating the statement) or it may queue the
2774/// statement to be back-patched later.
2775void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2776 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2777 if (Label != LabelStmts.end()) {
2778 // We've already seen this label, so set the label of the
2779 // label-address expression and we're done.
2780 S->setLabel(Label->second);
2781 } else {
2782 // We haven't seen this label yet, so add this label-address
2783 // expression to the set of unresolved label-address expressions.
2784 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2785 }
2786}
Douglas Gregor1342e842009-07-06 18:54:52 +00002787
2788
Mike Stump11289f42009-09-09 15:08:12 +00002789PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00002790 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2791 Reader.CurrentlyLoadingTypeOrDecl = this;
2792}
2793
2794PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2795 if (!Parent) {
2796 // If any identifiers with corresponding top-level declarations have
2797 // been loaded, load those declarations now.
2798 while (!Reader.PendingIdentifierInfos.empty()) {
2799 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2800 Reader.PendingIdentifierInfos.front().DeclIDs,
2801 true);
2802 Reader.PendingIdentifierInfos.pop_front();
2803 }
2804 }
2805
Mike Stump11289f42009-09-09 15:08:12 +00002806 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00002807}