blob: 42aa43b81f7197391c00b03531fff4a1a2564dd5 [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"
Douglas Gregora868bbd2009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor1a0d0b92009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000021#include "clang/AST/TypeLocVisitor.h"
Chris Lattner34321bc2009-04-10 21:41:48 +000022#include "clang/Lex/MacroInfo.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000023#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000025#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000026#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000027#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000028#include "clang/Basic/FileManager.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregord54f3a12009-10-05 21:07:28 +000030#include "clang/Basic/Version.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000031#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000032#include "llvm/Bitcode/BitstreamReader.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/MemoryBuffer.h"
John McCall0ad16662009-10-29 08:12:44 +000035#include "llvm/Support/ErrorHandling.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000036#include <algorithm>
Douglas Gregorc379c072009-04-28 18:58:38 +000037#include <iterator>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000038#include <cstdio>
Douglas Gregorc5046832009-04-27 18:38:38 +000039#include <sys/stat.h>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000043// PCH reader validator implementation
44//===----------------------------------------------------------------------===//
45
46PCHReaderListener::~PCHReaderListener() {}
47
48bool
49PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
50 const LangOptions &PPLangOpts = PP.getLangOptions();
51#define PARSE_LANGOPT_BENIGN(Option)
52#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
53 if (PPLangOpts.Option != LangOpts.Option) { \
54 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
55 return true; \
56 }
57
58 PARSE_LANGOPT_BENIGN(Trigraphs);
59 PARSE_LANGOPT_BENIGN(BCPLComment);
60 PARSE_LANGOPT_BENIGN(DollarIdents);
61 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
62 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
63 PARSE_LANGOPT_BENIGN(ImplicitInt);
64 PARSE_LANGOPT_BENIGN(Digraphs);
65 PARSE_LANGOPT_BENIGN(HexFloats);
66 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
67 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
68 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
69 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
70 PARSE_LANGOPT_BENIGN(CXXOperatorName);
71 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
72 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
73 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
74 PARSE_LANGOPT_BENIGN(PascalStrings);
75 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump11289f42009-09-09 15:08:12 +000076 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000077 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +000078 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000079 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
80 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
81 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
82 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +000083 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000084 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000085 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000086 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
87 PARSE_LANGOPT_BENIGN(EmitAllDecls);
88 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
89 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump11289f42009-09-09 15:08:12 +000090 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000091 diag::warn_pch_heinous_extensions);
92 // FIXME: Most of the options below are benign if the macro wasn't
93 // used. Unfortunately, this means that a PCH compiled without
94 // optimization can't be used with optimization turned on, even
95 // though the only thing that changes is whether __OPTIMIZE__ was
96 // defined... but if __OPTIMIZE__ never showed up in the header, it
97 // doesn't matter. We could consider making this some special kind
98 // of check.
99 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
100 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
101 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
102 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
103 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
104 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
105 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
106 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsoned4e2952009-11-05 20:14:16 +0000107 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000108 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000109 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000110 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
111 return true;
112 }
113 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000114 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
115 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000116 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000117 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000118 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000119#undef PARSE_LANGOPT_IRRELEVANT
120#undef PARSE_LANGOPT_BENIGN
121
122 return false;
123}
124
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000125bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
126 if (Triple == PP.getTargetInfo().getTriple().str())
127 return false;
128
129 Reader.Diag(diag::warn_pch_target_triple)
130 << Triple << PP.getTargetInfo().getTriple().str();
131 return true;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000132}
133
134/// \brief Split the given string into a vector of lines, eliminating
135/// any empty lines in the process.
136///
137/// \param Str the string to split.
138/// \param Len the length of Str.
139/// \param KeepEmptyLines true if empty lines should be included
140/// \returns a vector of lines, with the line endings removed
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000141static std::vector<llvm::StringRef> splitLines(llvm::StringRef Str,
142 bool KeepEmptyLines = false) {
143 std::vector<llvm::StringRef> Lines;
144
145 while (!Str.empty()) {
146 std::pair<llvm::StringRef, llvm::StringRef> split = Str.split('\n');
147
148 if (KeepEmptyLines || !split.first.empty())
149 Lines.push_back(split.first);
150
151 Str = split.second;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000152 }
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000153
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000154 return Lines;
155}
156
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000157bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000158 FileID PCHBufferID,
159 std::string &SuggestedPredefines) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000160 // If the two predefines buffers compare equal, we're done!
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000161 if (PP.getPredefines() == PCHPredef)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000162 return false;
163
164 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000165
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000166 // The predefines buffers are different. Determine what the differences are,
167 // and whether they require us to reject the PCH file.
168 std::vector<llvm::StringRef> CmdLineLines = splitLines(PP.getPredefines());
169 std::vector<llvm::StringRef> PCHLines = splitLines(PCHPredef);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000170
Daniel Dunbar499baed2009-11-11 05:26:28 +0000171 // Sort both sets of predefined buffer lines, since we allow some extra
172 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000173 std::sort(CmdLineLines.begin(), CmdLineLines.end());
174 std::sort(PCHLines.begin(), PCHLines.end());
175
Daniel Dunbar499baed2009-11-11 05:26:28 +0000176 // Determine which predefines that were used to build the PCH file are missing
177 // from the command line.
178 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000179 std::set_difference(PCHLines.begin(), PCHLines.end(),
180 CmdLineLines.begin(), CmdLineLines.end(),
181 std::back_inserter(MissingPredefines));
182
183 bool MissingDefines = false;
184 bool ConflictingDefines = false;
185 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000186 llvm::StringRef Missing = MissingPredefines[I];
187 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000188 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
189 return true;
190 }
Mike Stump11289f42009-09-09 15:08:12 +0000191
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000192 // This is a macro definition. Determine the name of the macro we're
193 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000194 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000195 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000196 = Missing.find_first_of("( \n\r", StartOfMacroName);
197 assert(EndOfMacroName != std::string::npos &&
198 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000199 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000200
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000201 // Determine whether this macro was given a different definition on the
202 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000203 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000204 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000205 std::vector<llvm::StringRef>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000206 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
207 MacroDefStart);
208 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000209 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000210 // Different macro; we're done.
211 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000212 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000213 }
Mike Stump11289f42009-09-09 15:08:12 +0000214
215 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000216 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000217 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000218 (*ConflictPos)[MacroDefLen] != '(')
219 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000220
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000221 // We found a conflicting macro definition.
222 break;
223 }
Mike Stump11289f42009-09-09 15:08:12 +0000224
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000225 if (ConflictPos != CmdLineLines.end()) {
226 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
227 << MacroName;
228
229 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000230 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
231 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
232 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
233 .getFileLocWithOffset(Offset);
234 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000235
236 ConflictingDefines = true;
237 continue;
238 }
Mike Stump11289f42009-09-09 15:08:12 +0000239
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000240 // If the macro doesn't conflict, then we'll just pick up the macro
241 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000242 if (ConflictingDefines)
243 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000244
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000245 if (!MissingDefines) {
246 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
247 MissingDefines = true;
248 }
249
250 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000251 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
252 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
253 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000254 .getFileLocWithOffset(Offset);
255 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
256 }
Mike Stump11289f42009-09-09 15:08:12 +0000257
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000258 if (ConflictingDefines)
259 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000260
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000261 // Determine what predefines were introduced based on command-line
262 // parameters that were not present when building the PCH
263 // file. Extra #defines are okay, so long as the identifiers being
264 // defined were not used within the precompiled header.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000265 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000266 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
267 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000268 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000269 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000270 llvm::StringRef &Extra = ExtraPredefines[I];
271 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000272 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
273 return true;
274 }
275
276 // This is an extra macro definition. Determine the name of the
277 // macro we're defining.
278 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000279 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000280 = Extra.find_first_of("( \n\r", StartOfMacroName);
281 assert(EndOfMacroName != std::string::npos &&
282 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000283 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000284
285 // Check whether this name was used somewhere in the PCH file. If
286 // so, defining it as a macro could change behavior, so we reject
287 // the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000288 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000289 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000290 return true;
291 }
292
293 // Add this definition to the suggested predefines buffer.
294 SuggestedPredefines += Extra;
295 SuggestedPredefines += '\n';
296 }
297
298 // If we get here, it's because the predefines buffer had compatible
299 // contents. Accept the PCH file.
300 return false;
301}
302
303void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
304 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
305}
306
307void PCHValidator::ReadCounter(unsigned Value) {
308 PP.setCounterValue(Value);
309}
310
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000311//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000312// PCH reader implementation
313//===----------------------------------------------------------------------===//
314
Mike Stump11289f42009-09-09 15:08:12 +0000315PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
316 const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000317 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
318 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000319 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000320 IdentifierTableData(0), IdentifierLookupTable(0),
321 IdentifierOffsets(0),
322 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
323 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000324 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000325 NumStatHits(0), NumStatMisses(0),
326 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000327 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000328 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000329 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000330 RelocatablePCH = false;
331}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000332
333PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000334 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000335 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000336 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000337 IdentifierTableData(0), IdentifierLookupTable(0),
338 IdentifierOffsets(0),
339 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
340 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000341 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000342 NumStatHits(0), NumStatMisses(0),
343 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000344 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000345 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000346 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000347 RelocatablePCH = false;
348}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000349
350PCHReader::~PCHReader() {}
351
Chris Lattner1de76db2009-04-27 05:58:23 +0000352Expr *PCHReader::ReadDeclExpr() {
353 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
354}
355
356Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor12bfa382009-10-17 00:13:19 +0000357 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000358}
359
360
Douglas Gregora868bbd2009-04-21 22:25:48 +0000361namespace {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000362class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
363 PCHReader &Reader;
364
365public:
366 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
367
368 typedef Selector external_key_type;
369 typedef external_key_type internal_key_type;
370
371 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000372
Douglas Gregorc78d3462009-04-24 21:10:55 +0000373 static bool EqualKey(const internal_key_type& a,
374 const internal_key_type& b) {
375 return a == b;
376 }
Mike Stump11289f42009-09-09 15:08:12 +0000377
Douglas Gregorc78d3462009-04-24 21:10:55 +0000378 static unsigned ComputeHash(Selector Sel) {
379 unsigned N = Sel.getNumArgs();
380 if (N == 0)
381 ++N;
382 unsigned R = 5381;
383 for (unsigned I = 0; I != N; ++I)
384 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000385 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000386 return R;
387 }
Mike Stump11289f42009-09-09 15:08:12 +0000388
Douglas Gregorc78d3462009-04-24 21:10:55 +0000389 // This hopefully will just get inlined and removed by the optimizer.
390 static const internal_key_type&
391 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000392
Douglas Gregorc78d3462009-04-24 21:10:55 +0000393 static std::pair<unsigned, unsigned>
394 ReadKeyDataLength(const unsigned char*& d) {
395 using namespace clang::io;
396 unsigned KeyLen = ReadUnalignedLE16(d);
397 unsigned DataLen = ReadUnalignedLE16(d);
398 return std::make_pair(KeyLen, DataLen);
399 }
Mike Stump11289f42009-09-09 15:08:12 +0000400
Douglas Gregor95c13f52009-04-25 17:48:32 +0000401 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000402 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000403 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000404 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000405 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000406 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
407 if (N == 0)
408 return SelTable.getNullarySelector(FirstII);
409 else if (N == 1)
410 return SelTable.getUnarySelector(FirstII);
411
412 llvm::SmallVector<IdentifierInfo *, 16> Args;
413 Args.push_back(FirstII);
414 for (unsigned I = 1; I != N; ++I)
415 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
416
Douglas Gregor038c3382009-05-22 22:45:36 +0000417 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000418 }
Mike Stump11289f42009-09-09 15:08:12 +0000419
Douglas Gregorc78d3462009-04-24 21:10:55 +0000420 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
421 using namespace clang::io;
422 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
423 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
424
425 data_type Result;
426
427 // Load instance methods
428 ObjCMethodList *Prev = 0;
429 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000430 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000431 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
432 if (!Result.first.Method) {
433 // This is the first method, which is the easy case.
434 Result.first.Method = Method;
435 Prev = &Result.first;
436 continue;
437 }
438
439 Prev->Next = new ObjCMethodList(Method, 0);
440 Prev = Prev->Next;
441 }
442
443 // Load factory methods
444 Prev = 0;
445 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000446 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000447 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
448 if (!Result.second.Method) {
449 // This is the first method, which is the easy case.
450 Result.second.Method = Method;
451 Prev = &Result.second;
452 continue;
453 }
454
455 Prev->Next = new ObjCMethodList(Method, 0);
456 Prev = Prev->Next;
457 }
458
459 return Result;
460 }
461};
Mike Stump11289f42009-09-09 15:08:12 +0000462
463} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000464
465/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000466typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000467 PCHMethodPoolLookupTable;
468
469namespace {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000470class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
471 PCHReader &Reader;
472
473 // If we know the IdentifierInfo in advance, it is here and we will
474 // not build a new one. Used when deserializing information about an
475 // identifier that was constructed before the PCH file was read.
476 IdentifierInfo *KnownII;
477
478public:
479 typedef IdentifierInfo * data_type;
480
481 typedef const std::pair<const char*, unsigned> external_key_type;
482
483 typedef external_key_type internal_key_type;
484
Mike Stump11289f42009-09-09 15:08:12 +0000485 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregora868bbd2009-04-21 22:25:48 +0000486 : Reader(Reader), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000487
Douglas Gregora868bbd2009-04-21 22:25:48 +0000488 static bool EqualKey(const internal_key_type& a,
489 const internal_key_type& b) {
490 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
491 : false;
492 }
Mike Stump11289f42009-09-09 15:08:12 +0000493
Douglas Gregora868bbd2009-04-21 22:25:48 +0000494 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000495 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000496 }
Mike Stump11289f42009-09-09 15:08:12 +0000497
Douglas Gregora868bbd2009-04-21 22:25:48 +0000498 // This hopefully will just get inlined and removed by the optimizer.
499 static const internal_key_type&
500 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000501
Douglas Gregora868bbd2009-04-21 22:25:48 +0000502 static std::pair<unsigned, unsigned>
503 ReadKeyDataLength(const unsigned char*& d) {
504 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000505 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000506 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000507 return std::make_pair(KeyLen, DataLen);
508 }
Mike Stump11289f42009-09-09 15:08:12 +0000509
Douglas Gregora868bbd2009-04-21 22:25:48 +0000510 static std::pair<const char*, unsigned>
511 ReadKey(const unsigned char* d, unsigned n) {
512 assert(n >= 2 && d[n-1] == '\0');
513 return std::make_pair((const char*) d, n-1);
514 }
Mike Stump11289f42009-09-09 15:08:12 +0000515
516 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000517 const unsigned char* d,
518 unsigned DataLen) {
519 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000520 pch::IdentID ID = ReadUnalignedLE32(d);
521 bool IsInteresting = ID & 0x01;
522
523 // Wipe out the "is interesting" bit.
524 ID = ID >> 1;
525
526 if (!IsInteresting) {
527 // For unintersting identifiers, just build the IdentifierInfo
528 // and associate it with the persistent ID.
529 IdentifierInfo *II = KnownII;
530 if (!II)
531 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
532 k.first, k.first + k.second);
533 Reader.SetIdentifierInfo(ID, II);
534 return II;
535 }
536
Douglas Gregorb9256522009-04-28 21:32:13 +0000537 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000538 bool CPlusPlusOperatorKeyword = Bits & 0x01;
539 Bits >>= 1;
540 bool Poisoned = Bits & 0x01;
541 Bits >>= 1;
542 bool ExtensionToken = Bits & 0x01;
543 Bits >>= 1;
544 bool hasMacroDefinition = Bits & 0x01;
545 Bits >>= 1;
546 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
547 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000548
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000549 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000550 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000551
552 // Build the IdentifierInfo itself and link the identifier ID with
553 // the new IdentifierInfo.
554 IdentifierInfo *II = KnownII;
555 if (!II)
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000556 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
557 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000558 Reader.SetIdentifierInfo(ID, II);
559
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000560 // Set or check the various bits in the IdentifierInfo structure.
561 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000562 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000563 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000564 "Incorrect extension token flag");
565 (void)ExtensionToken;
566 II->setIsPoisoned(Poisoned);
567 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
568 "Incorrect C++ operator keyword flag");
569 (void)CPlusPlusOperatorKeyword;
570
Douglas Gregorc3366a52009-04-21 23:56:24 +0000571 // If this identifier is a macro, deserialize the macro
572 // definition.
573 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000574 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregorc3366a52009-04-21 23:56:24 +0000575 Reader.ReadMacroRecord(Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000576 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000577 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000578
579 // Read all of the declarations visible at global scope with this
580 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000581 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000582 if (DataLen > 0) {
583 llvm::SmallVector<uint32_t, 4> DeclIDs;
584 for (; DataLen > 0; DataLen -= 4)
585 DeclIDs.push_back(ReadUnalignedLE32(d));
586 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000587 }
Mike Stump11289f42009-09-09 15:08:12 +0000588
Douglas Gregora868bbd2009-04-21 22:25:48 +0000589 return II;
590 }
591};
Mike Stump11289f42009-09-09 15:08:12 +0000592
593} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000594
595/// \brief The on-disk hash table used to contain information about
596/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000597typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000598 PCHIdentifierLookupTable;
599
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000600bool PCHReader::Error(const char *Msg) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000601 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
602 Diag(DiagID);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000603 return true;
604}
605
Douglas Gregor92863e42009-04-10 23:10:45 +0000606/// \brief Check the contents of the predefines buffer against the
607/// contents of the predefines buffer used to build the PCH file.
608///
609/// The contents of the two predefines buffers should be the same. If
610/// not, then some command-line option changed the preprocessor state
611/// and we must reject the PCH file.
612///
613/// \param PCHPredef The start of the predefines buffer in the PCH
614/// file.
615///
616/// \param PCHPredefLen The length of the predefines buffer in the PCH
617/// file.
618///
619/// \param PCHBufferID The FileID for the PCH predefines buffer.
620///
621/// \returns true if there was a mismatch (in which case the PCH file
622/// should be ignored), or false otherwise.
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000623bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregor92863e42009-04-10 23:10:45 +0000624 FileID PCHBufferID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000625 if (Listener)
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000626 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000627 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000628 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000629}
630
Douglas Gregorc5046832009-04-27 18:38:38 +0000631//===----------------------------------------------------------------------===//
632// Source Manager Deserialization
633//===----------------------------------------------------------------------===//
634
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000635/// \brief Read the line table in the source manager block.
636/// \returns true if ther was an error.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000637bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000638 unsigned Idx = 0;
639 LineTableInfo &LineTable = SourceMgr.getLineTable();
640
641 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000642 std::map<int, int> FileIDs;
643 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000644 // Extract the file name
645 unsigned FilenameLen = Record[Idx++];
646 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
647 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000648 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000649 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000650 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000651 }
652
653 // Parse the line entries
654 std::vector<LineEntry> Entries;
655 while (Idx < Record.size()) {
Douglas Gregora8854652009-04-13 17:12:42 +0000656 int FID = FileIDs[Record[Idx++]];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000657
658 // Extract the line entries
659 unsigned NumEntries = Record[Idx++];
660 Entries.clear();
661 Entries.reserve(NumEntries);
662 for (unsigned I = 0; I != NumEntries; ++I) {
663 unsigned FileOffset = Record[Idx++];
664 unsigned LineNo = Record[Idx++];
665 int FilenameID = Record[Idx++];
Mike Stump11289f42009-09-09 15:08:12 +0000666 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000667 = (SrcMgr::CharacteristicKind)Record[Idx++];
668 unsigned IncludeOffset = Record[Idx++];
669 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
670 FileKind, IncludeOffset));
671 }
672 LineTable.AddEntry(FID, Entries);
673 }
674
675 return false;
676}
677
Douglas Gregorc5046832009-04-27 18:38:38 +0000678namespace {
679
680class VISIBILITY_HIDDEN PCHStatData {
681public:
682 const bool hasStat;
683 const ino_t ino;
684 const dev_t dev;
685 const mode_t mode;
686 const time_t mtime;
687 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000688
Douglas Gregorc5046832009-04-27 18:38:38 +0000689 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000690 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
691
Douglas Gregorc5046832009-04-27 18:38:38 +0000692 PCHStatData()
693 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
694};
695
696class VISIBILITY_HIDDEN PCHStatLookupTrait {
697 public:
698 typedef const char *external_key_type;
699 typedef const char *internal_key_type;
700
701 typedef PCHStatData data_type;
702
703 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000704 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000705 }
706
707 static internal_key_type GetInternalKey(const char *path) { return path; }
708
709 static bool EqualKey(internal_key_type a, internal_key_type b) {
710 return strcmp(a, b) == 0;
711 }
712
713 static std::pair<unsigned, unsigned>
714 ReadKeyDataLength(const unsigned char*& d) {
715 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
716 unsigned DataLen = (unsigned) *d++;
717 return std::make_pair(KeyLen + 1, DataLen);
718 }
719
720 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
721 return (const char *)d;
722 }
723
724 static data_type ReadData(const internal_key_type, const unsigned char *d,
725 unsigned /*DataLen*/) {
726 using namespace clang::io;
727
728 if (*d++ == 1)
729 return data_type();
730
731 ino_t ino = (ino_t) ReadUnalignedLE32(d);
732 dev_t dev = (dev_t) ReadUnalignedLE32(d);
733 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000734 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000735 off_t size = (off_t) ReadUnalignedLE64(d);
736 return data_type(ino, dev, mode, mtime, size);
737 }
738};
739
740/// \brief stat() cache for precompiled headers.
741///
742/// This cache is very similar to the stat cache used by pretokenized
743/// headers.
744class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
745 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
746 CacheTy *Cache;
747
748 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000749public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000750 PCHStatCache(const unsigned char *Buckets,
751 const unsigned char *Base,
752 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000753 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000754 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
755 Cache = CacheTy::Create(Buckets, Base);
756 }
757
758 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000759
Douglas Gregorc5046832009-04-27 18:38:38 +0000760 int stat(const char *path, struct stat *buf) {
761 // Do the lookup for the file's data in the PCH file.
762 CacheTy::iterator I = Cache->find(path);
763
764 // If we don't get a hit in the PCH file just forward to 'stat'.
765 if (I == Cache->end()) {
766 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000767 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000768 }
Mike Stump11289f42009-09-09 15:08:12 +0000769
Douglas Gregorc5046832009-04-27 18:38:38 +0000770 ++NumStatHits;
771 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000772
Douglas Gregorc5046832009-04-27 18:38:38 +0000773 if (!Data.hasStat)
774 return 1;
775
776 buf->st_ino = Data.ino;
777 buf->st_dev = Data.dev;
778 buf->st_mtime = Data.mtime;
779 buf->st_mode = Data.mode;
780 buf->st_size = Data.size;
781 return 0;
782 }
783};
784} // end anonymous namespace
785
786
Douglas Gregora7f71a92009-04-10 03:52:48 +0000787/// \brief Read the source manager block
Douglas Gregor92863e42009-04-10 23:10:45 +0000788PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000789 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000790
791 // Set the source-location entry cursor to the current position in
792 // the stream. This cursor will be used to read the contents of the
793 // source manager block initially, and then lazily read
794 // source-location entries as needed.
795 SLocEntryCursor = Stream;
796
797 // The stream itself is going to skip over the source manager block.
798 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000799 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000800 return Failure;
801 }
802
803 // Enter the source manager block.
804 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000805 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000806 return Failure;
807 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000808
Douglas Gregora7f71a92009-04-10 03:52:48 +0000809 RecordData Record;
810 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000811 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000812 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000813 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000814 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000815 return Failure;
816 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000817 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000818 }
Mike Stump11289f42009-09-09 15:08:12 +0000819
Douglas Gregora7f71a92009-04-10 03:52:48 +0000820 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
821 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000822 SLocEntryCursor.ReadSubBlockID();
823 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000824 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000825 return Failure;
826 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000827 continue;
828 }
Mike Stump11289f42009-09-09 15:08:12 +0000829
Douglas Gregora7f71a92009-04-10 03:52:48 +0000830 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000831 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000832 continue;
833 }
Mike Stump11289f42009-09-09 15:08:12 +0000834
Douglas Gregora7f71a92009-04-10 03:52:48 +0000835 // Read a record.
836 const char *BlobStart;
837 unsigned BlobLen;
838 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000839 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000840 default: // Default behavior: ignore.
841 break;
842
Chris Lattner184e65d2009-04-14 23:22:57 +0000843 case pch::SM_LINE_TABLE:
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000844 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000845 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000846 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000847
848 case pch::SM_HEADER_FILE_INFO: {
849 HeaderFileInfo HFI;
850 HFI.isImport = Record[0];
851 HFI.DirInfo = Record[1];
852 HFI.NumIncludes = Record[2];
853 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000854 if (Listener)
855 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregoreda6a892009-04-26 00:07:37 +0000856 break;
857 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000858
859 case pch::SM_SLOC_FILE_ENTRY:
860 case pch::SM_SLOC_BUFFER_ENTRY:
861 case pch::SM_SLOC_INSTANTIATION_ENTRY:
862 // Once we hit one of the source location entries, we're done.
863 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000864 }
865 }
866}
867
Douglas Gregor258ae542009-04-27 06:38:32 +0000868/// \brief Read in the source location entry with the given ID.
869PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
870 if (ID == 0)
871 return Success;
872
873 if (ID > TotalNumSLocEntries) {
874 Error("source location entry ID out-of-range for PCH file");
875 return Failure;
876 }
877
878 ++NumSLocEntriesRead;
879 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
880 unsigned Code = SLocEntryCursor.ReadCode();
881 if (Code == llvm::bitc::END_BLOCK ||
882 Code == llvm::bitc::ENTER_SUBBLOCK ||
883 Code == llvm::bitc::DEFINE_ABBREV) {
884 Error("incorrectly-formatted source location entry in PCH file");
885 return Failure;
886 }
887
Douglas Gregor258ae542009-04-27 06:38:32 +0000888 RecordData Record;
889 const char *BlobStart;
890 unsigned BlobLen;
891 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
892 default:
893 Error("incorrectly-formatted source location entry in PCH file");
894 return Failure;
895
896 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000897 std::string Filename(BlobStart, BlobStart + BlobLen);
898 MaybeAddSystemRootToFilename(Filename);
899 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000900 if (File == 0) {
901 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000902 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000903 ErrorStr += "' referenced by PCH file";
904 Error(ErrorStr.c_str());
905 return Failure;
906 }
Mike Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregor258ae542009-04-27 06:38:32 +0000908 FileID FID = SourceMgr.createFileID(File,
909 SourceLocation::getFromRawEncoding(Record[1]),
910 (SrcMgr::CharacteristicKind)Record[2],
911 ID, Record[0]);
912 if (Record[3])
913 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
914 .setHasLineDirectives();
915
916 break;
917 }
918
919 case pch::SM_SLOC_BUFFER_ENTRY: {
920 const char *Name = BlobStart;
921 unsigned Offset = Record[0];
922 unsigned Code = SLocEntryCursor.ReadCode();
923 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000924 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +0000925 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
926 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
927 (void)RecCode;
928 llvm::MemoryBuffer *Buffer
Mike Stump11289f42009-09-09 15:08:12 +0000929 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor258ae542009-04-27 06:38:32 +0000930 BlobStart + BlobLen - 1,
931 Name);
932 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000933
Douglas Gregore6648fb2009-04-28 20:33:11 +0000934 if (strcmp(Name, "<built-in>") == 0) {
935 PCHPredefinesBufferID = BufferID;
936 PCHPredefines = BlobStart;
937 PCHPredefinesLen = BlobLen - 1;
938 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000939
940 break;
941 }
942
943 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +0000944 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +0000945 = SourceLocation::getFromRawEncoding(Record[1]);
946 SourceMgr.createInstantiationLoc(SpellingLoc,
947 SourceLocation::getFromRawEncoding(Record[2]),
948 SourceLocation::getFromRawEncoding(Record[3]),
949 Record[4],
950 ID,
951 Record[0]);
952 break;
Mike Stump11289f42009-09-09 15:08:12 +0000953 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000954 }
955
956 return Success;
957}
958
Chris Lattnere78a6be2009-04-27 01:05:14 +0000959/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
960/// specified cursor. Read the abbreviations that are at the top of the block
961/// and then leave the cursor pointing into the block.
962bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
963 unsigned BlockID) {
964 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000965 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +0000966 return Failure;
967 }
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattnere78a6be2009-04-27 01:05:14 +0000969 while (true) {
970 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +0000971
Chris Lattnere78a6be2009-04-27 01:05:14 +0000972 // We expect all abbrevs to be at the start of the block.
973 if (Code != llvm::bitc::DEFINE_ABBREV)
974 return false;
975 Cursor.ReadAbbrevRecord();
976 }
977}
978
Douglas Gregorc3366a52009-04-21 23:56:24 +0000979void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000980 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +0000981
Douglas Gregorc3366a52009-04-21 23:56:24 +0000982 // Keep track of where we are in the stream, then jump back there
983 // after reading this macro.
984 SavedStreamPosition SavedPosition(Stream);
985
986 Stream.JumpToBit(Offset);
987 RecordData Record;
988 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
989 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000990
Douglas Gregorc3366a52009-04-21 23:56:24 +0000991 while (true) {
992 unsigned Code = Stream.ReadCode();
993 switch (Code) {
994 case llvm::bitc::END_BLOCK:
995 return;
996
997 case llvm::bitc::ENTER_SUBBLOCK:
998 // No known subblocks, always skip them.
999 Stream.ReadSubBlockID();
1000 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001001 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001002 return;
1003 }
1004 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001005
Douglas Gregorc3366a52009-04-21 23:56:24 +00001006 case llvm::bitc::DEFINE_ABBREV:
1007 Stream.ReadAbbrevRecord();
1008 continue;
1009 default: break;
1010 }
1011
1012 // Read a record.
1013 Record.clear();
1014 pch::PreprocessorRecordTypes RecType =
1015 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1016 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001017 case pch::PP_MACRO_OBJECT_LIKE:
1018 case pch::PP_MACRO_FUNCTION_LIKE: {
1019 // If we already have a macro, that means that we've hit the end
1020 // of the definition of the macro we were looking for. We're
1021 // done.
1022 if (Macro)
1023 return;
1024
1025 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1026 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001027 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001028 return;
1029 }
1030 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1031 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001032
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001033 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001034 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001035
Douglas Gregorc3366a52009-04-21 23:56:24 +00001036 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1037 // Decode function-like macro info.
1038 bool isC99VarArgs = Record[3];
1039 bool isGNUVarArgs = Record[4];
1040 MacroArgs.clear();
1041 unsigned NumArgs = Record[5];
1042 for (unsigned i = 0; i != NumArgs; ++i)
1043 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1044
1045 // Install function-like macro info.
1046 MI->setIsFunctionLike();
1047 if (isC99VarArgs) MI->setIsC99Varargs();
1048 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001049 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001050 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001051 }
1052
1053 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001054 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001055
1056 // Remember that we saw this macro last so that we add the tokens that
1057 // form its body to it.
1058 Macro = MI;
1059 ++NumMacrosRead;
1060 break;
1061 }
Mike Stump11289f42009-09-09 15:08:12 +00001062
Douglas Gregorc3366a52009-04-21 23:56:24 +00001063 case pch::PP_TOKEN: {
1064 // If we see a TOKEN before a PP_MACRO_*, then the file is
1065 // erroneous, just pretend we didn't see this.
1066 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001067
Douglas Gregorc3366a52009-04-21 23:56:24 +00001068 Token Tok;
1069 Tok.startToken();
1070 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1071 Tok.setLength(Record[1]);
1072 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1073 Tok.setIdentifierInfo(II);
1074 Tok.setKind((tok::TokenKind)Record[3]);
1075 Tok.setFlag((Token::TokenFlags)Record[4]);
1076 Macro->AddTokenToBody(Tok);
1077 break;
1078 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001079 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001080 }
1081}
1082
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001083/// \brief If we are loading a relocatable PCH file, and the filename is
1084/// not an absolute path, add the system root to the beginning of the file
1085/// name.
1086void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1087 // If this is not a relocatable PCH file, there's nothing to do.
1088 if (!RelocatablePCH)
1089 return;
Mike Stump11289f42009-09-09 15:08:12 +00001090
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001091 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1092 return;
1093
1094 std::string FIXME = Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001095
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001096 if (isysroot == 0) {
1097 // If no system root was given, default to '/'
1098 Filename.insert(Filename.begin(), '/');
1099 return;
1100 }
Mike Stump11289f42009-09-09 15:08:12 +00001101
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001102 unsigned Length = strlen(isysroot);
1103 if (isysroot[Length - 1] != '/')
1104 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001105
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001106 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1107}
1108
Mike Stump11289f42009-09-09 15:08:12 +00001109PCHReader::PCHReadResult
Douglas Gregoreda6a892009-04-26 00:07:37 +00001110PCHReader::ReadPCHBlock() {
Douglas Gregor55abb232009-04-10 20:39:37 +00001111 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001112 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001113 return Failure;
1114 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001115
1116 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001117 RecordData Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001118 while (!Stream.AtEndOfStream()) {
1119 unsigned Code = Stream.ReadCode();
1120 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001121 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001122 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001123 return Failure;
1124 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001125
Douglas Gregor55abb232009-04-10 20:39:37 +00001126 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001127 }
1128
1129 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1130 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001131 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001132 // We lazily load the decls block, but we want to set up the
1133 // DeclsCursor cursor to point into it. Clone our current bitcode
1134 // cursor to it, enter the block and read the abbrevs in that block.
1135 // With the main cursor, we just skip over it.
1136 DeclsCursor = Stream;
1137 if (Stream.SkipBlock() || // Skip with the main cursor.
1138 // Read the abbrevs.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001139 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001140 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001141 return Failure;
1142 }
1143 break;
Mike Stump11289f42009-09-09 15:08:12 +00001144
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001145 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001146 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001147 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001148 return Failure;
1149 }
1150 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001151
Douglas Gregora7f71a92009-04-10 03:52:48 +00001152 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001153 switch (ReadSourceManagerBlock()) {
1154 case Success:
1155 break;
1156
1157 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001158 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001159 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001160
1161 case IgnorePCH:
1162 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001163 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001164 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001165 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001166 continue;
1167 }
1168
1169 if (Code == llvm::bitc::DEFINE_ABBREV) {
1170 Stream.ReadAbbrevRecord();
1171 continue;
1172 }
1173
1174 // Read and process a record.
1175 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001176 const char *BlobStart = 0;
1177 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001178 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001179 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001180 default: // Default behavior: ignore.
1181 break;
1182
1183 case pch::TYPE_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001184 if (!TypesLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001185 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001186 return Failure;
1187 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001188 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001189 TypesLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001190 break;
1191
1192 case pch::DECL_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001193 if (!DeclsLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001194 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001195 return Failure;
1196 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001197 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001198 DeclsLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001199 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001200
1201 case pch::LANGUAGE_OPTIONS:
1202 if (ParseLanguageOptions(Record))
1203 return IgnorePCH;
1204 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001205
Douglas Gregor7b71e632009-04-27 22:23:34 +00001206 case pch::METADATA: {
1207 if (Record[0] != pch::VERSION_MAJOR) {
1208 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1209 : diag::warn_pch_version_too_new);
1210 return IgnorePCH;
1211 }
1212
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001213 RelocatablePCH = Record[4];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001214 if (Listener) {
1215 std::string TargetTriple(BlobStart, BlobLen);
1216 if (Listener->ReadTargetTriple(TargetTriple))
1217 return IgnorePCH;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001218 }
1219 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001220 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001221
1222 case pch::IDENTIFIER_TABLE:
Douglas Gregora868bbd2009-04-21 22:25:48 +00001223 IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001224 if (Record[0]) {
Mike Stump11289f42009-09-09 15:08:12 +00001225 IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001226 = PCHIdentifierLookupTable::Create(
Douglas Gregora868bbd2009-04-21 22:25:48 +00001227 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001228 (const unsigned char *)IdentifierTableData,
Douglas Gregora868bbd2009-04-21 22:25:48 +00001229 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001230 if (PP)
1231 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001232 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001233 break;
1234
1235 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001236 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001237 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001238 return Failure;
1239 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001240 IdentifierOffsets = (const uint32_t *)BlobStart;
1241 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001242 if (PP)
1243 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001244 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001245
1246 case pch::EXTERNAL_DEFINITIONS:
1247 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001248 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001249 return Failure;
1250 }
1251 ExternalDefinitions.swap(Record);
1252 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001253
Douglas Gregor652d82a2009-04-18 05:55:16 +00001254 case pch::SPECIAL_TYPES:
1255 SpecialTypes.swap(Record);
1256 break;
1257
Douglas Gregor08f01292009-04-17 22:13:46 +00001258 case pch::STATISTICS:
1259 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001260 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001261 TotalLexicalDeclContexts = Record[2];
1262 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001263 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001264
Douglas Gregord4df8652009-04-22 22:02:47 +00001265 case pch::TENTATIVE_DEFINITIONS:
1266 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001267 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001268 return Failure;
1269 }
1270 TentativeDefinitions.swap(Record);
1271 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001272
1273 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1274 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001275 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001276 return Failure;
1277 }
1278 LocallyScopedExternalDecls.swap(Record);
1279 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001280
Douglas Gregor95c13f52009-04-25 17:48:32 +00001281 case pch::SELECTOR_OFFSETS:
1282 SelectorOffsets = (const uint32_t *)BlobStart;
1283 TotalNumSelectors = Record[0];
1284 SelectorsLoaded.resize(TotalNumSelectors);
1285 break;
1286
Douglas Gregorc78d3462009-04-24 21:10:55 +00001287 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001288 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1289 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001290 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001291 = PCHMethodPoolLookupTable::Create(
1292 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001293 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001294 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001295 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001296 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001297
1298 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001299 if (!Record.empty() && Listener)
1300 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001301 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001302
1303 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001304 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001305 TotalNumSLocEntries = Record[0];
Douglas Gregord54f3a12009-10-05 21:07:28 +00001306 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001307 break;
1308
1309 case pch::SOURCE_LOCATION_PRELOADS:
1310 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1311 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1312 if (Result != Success)
1313 return Result;
1314 }
1315 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001316
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001317 case pch::STAT_CACHE: {
1318 PCHStatCache *MyStatCache =
1319 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1320 (const unsigned char *)BlobStart,
1321 NumStatHits, NumStatMisses);
1322 FileMgr.addStatCache(MyStatCache);
1323 StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001324 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001325 }
1326
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001327 case pch::EXT_VECTOR_DECLS:
1328 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001329 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001330 return Failure;
1331 }
1332 ExtVectorDecls.swap(Record);
1333 break;
1334
Douglas Gregor45fe0362009-05-12 01:31:05 +00001335 case pch::ORIGINAL_FILE_NAME:
1336 OriginalFileName.assign(BlobStart, BlobLen);
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001337 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001338 break;
Mike Stump11289f42009-09-09 15:08:12 +00001339
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001340 case pch::COMMENT_RANGES:
1341 Comments = (SourceRange *)BlobStart;
1342 NumComments = BlobLen / sizeof(SourceRange);
1343 break;
Douglas Gregord54f3a12009-10-05 21:07:28 +00001344
1345 case pch::SVN_BRANCH_REVISION: {
1346 unsigned CurRevision = getClangSubversionRevision();
1347 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1348 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1349 : diag::warn_pch_version_too_new);
1350 return IgnorePCH;
1351 }
1352
1353 const char *CurBranch = getClangSubversionPath();
1354 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1355 std::string PCHBranch(BlobStart, BlobLen);
1356 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1357 return IgnorePCH;
1358 }
1359 break;
1360 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001361 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001362 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001363 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001364 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001365}
1366
Douglas Gregor92863e42009-04-10 23:10:45 +00001367PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001368 // Set the PCH file name.
1369 this->FileName = FileName;
1370
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001371 // Open the PCH file.
Daniel Dunbar2d925eb2009-09-22 05:38:01 +00001372 //
1373 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001374 std::string ErrStr;
Daniel Dunbar69914f42009-11-10 00:46:19 +00001375 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregor92863e42009-04-10 23:10:45 +00001376 if (!Buffer) {
1377 Error(ErrStr.c_str());
1378 return IgnorePCH;
1379 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001380
1381 // Initialize the stream
Mike Stump11289f42009-09-09 15:08:12 +00001382 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattner9356ace2009-04-26 20:59:20 +00001383 (const unsigned char *)Buffer->getBufferEnd());
1384 Stream.init(StreamFile);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001385
1386 // Sniff for the signature.
1387 if (Stream.Read(8) != 'C' ||
1388 Stream.Read(8) != 'P' ||
1389 Stream.Read(8) != 'C' ||
Douglas Gregor92863e42009-04-10 23:10:45 +00001390 Stream.Read(8) != 'H') {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001391 Diag(diag::err_not_a_pch_file) << FileName;
1392 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001393 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001394
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001395 while (!Stream.AtEndOfStream()) {
1396 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001397
Douglas Gregor92863e42009-04-10 23:10:45 +00001398 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001399 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001400 return Failure;
1401 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001402
1403 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001404
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001405 // We only know the PCH subblock ID.
1406 switch (BlockID) {
1407 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001408 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001409 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001410 return Failure;
1411 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001412 break;
1413 case pch::PCH_BLOCK_ID:
Douglas Gregoreda6a892009-04-26 00:07:37 +00001414 switch (ReadPCHBlock()) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001415 case Success:
1416 break;
1417
1418 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001419 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001420
1421 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001422 // FIXME: We could consider reading through to the end of this
1423 // PCH block, skipping subblocks, to see if there are other
1424 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001425
1426 // Clear out any preallocated source location entries, so that
1427 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001428 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001429
1430 // Remove the stat cache.
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001431 if (StatCache)
1432 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001433
Douglas Gregor92863e42009-04-10 23:10:45 +00001434 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001435 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001436 break;
1437 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001438 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001439 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001440 return Failure;
1441 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001442 break;
1443 }
Mike Stump11289f42009-09-09 15:08:12 +00001444 }
1445
Douglas Gregore6648fb2009-04-28 20:33:11 +00001446 // Check the predefines buffer.
Daniel Dunbar20a682d2009-11-11 00:52:11 +00001447 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregore6648fb2009-04-28 20:33:11 +00001448 PCHPredefinesBufferID))
1449 return IgnorePCH;
Mike Stump11289f42009-09-09 15:08:12 +00001450
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001451 if (PP) {
Zhongxing Xu3f51f412009-07-18 09:26:51 +00001452 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001453 // PCH file is read, so there may be some identifiers that were
1454 // loaded into the IdentifierTable before we intercepted the
1455 // creation of identifiers. Iterate through the list of known
1456 // identifiers and determine whether we have to establish
1457 // preprocessor definitions or top-level identifier declaration
1458 // chains for those identifiers.
1459 //
1460 // We copy the IdentifierInfo pointers to a small vector first,
1461 // since de-serializing declarations or macro definitions can add
1462 // new entries into the identifier table, invalidating the
1463 // iterators.
1464 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1465 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1466 IdEnd = PP->getIdentifierTable().end();
1467 Id != IdEnd; ++Id)
1468 Identifiers.push_back(Id->second);
Mike Stump11289f42009-09-09 15:08:12 +00001469 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001470 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1471 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1472 IdentifierInfo *II = Identifiers[I];
1473 // Look in the on-disk hash table for an entry for
1474 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001475 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001476 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1477 if (Pos == IdTable->end())
1478 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001479
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001480 // Dereferencing the iterator has the effect of populating the
1481 // IdentifierInfo node with the various declarations it needs.
1482 (void)*Pos;
1483 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001484 }
1485
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001486 if (Context)
1487 InitializeContext(*Context);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001488
Douglas Gregora868bbd2009-04-21 22:25:48 +00001489 return Success;
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001490}
1491
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001492void PCHReader::InitializeContext(ASTContext &Ctx) {
1493 Context = &Ctx;
1494 assert(Context && "Passed null context!");
1495
1496 assert(PP && "Forgot to set Preprocessor ?");
1497 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1498 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump11289f42009-09-09 15:08:12 +00001499
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001500 // Load the translation unit declaration
1501 ReadDeclRecord(DeclOffsets[0], 0);
1502
1503 // Load the special types.
1504 Context->setBuiltinVaListType(
1505 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1506 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1507 Context->setObjCIdType(GetType(Id));
1508 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1509 Context->setObjCSelType(GetType(Sel));
1510 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1511 Context->setObjCProtoType(GetType(Proto));
1512 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1513 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001514
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001515 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1516 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001517 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001518 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1519 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001520 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1521 QualType FileType = GetType(File);
1522 assert(!FileType.isNull() && "FILE type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001523 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001524 Context->setFILEDecl(Typedef->getDecl());
1525 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001526 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregor27821ce2009-07-07 16:35:42 +00001527 assert(Tag && "Invalid FILE type in PCH file");
1528 Context->setFILEDecl(Tag->getDecl());
1529 }
1530 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001531 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1532 QualType Jmp_bufType = GetType(Jmp_buf);
1533 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001534 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001535 Context->setjmp_bufDecl(Typedef->getDecl());
1536 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001537 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001538 assert(Tag && "Invalid jmp_bug type in PCH file");
1539 Context->setjmp_bufDecl(Tag->getDecl());
1540 }
1541 }
1542 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1543 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1544 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001545 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001546 Context->setsigjmp_bufDecl(Typedef->getDecl());
1547 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001548 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001549 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1550 Context->setsigjmp_bufDecl(Tag->getDecl());
1551 }
1552 }
Mike Stump11289f42009-09-09 15:08:12 +00001553 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001554 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1555 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001556 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001557 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1558 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpd0153282009-10-20 02:12:22 +00001559 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1560 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00001561 if (unsigned String
1562 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1563 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001564}
1565
Douglas Gregor45fe0362009-05-12 01:31:05 +00001566/// \brief Retrieve the name of the original source file name
1567/// directly from the PCH file, without actually loading the PCH
1568/// file.
1569std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1570 // Open the PCH file.
1571 std::string ErrStr;
1572 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1573 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1574 if (!Buffer) {
1575 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1576 return std::string();
1577 }
1578
1579 // Initialize the stream
1580 llvm::BitstreamReader StreamFile;
1581 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001582 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001583 (const unsigned char *)Buffer->getBufferEnd());
1584 Stream.init(StreamFile);
1585
1586 // Sniff for the signature.
1587 if (Stream.Read(8) != 'C' ||
1588 Stream.Read(8) != 'P' ||
1589 Stream.Read(8) != 'C' ||
1590 Stream.Read(8) != 'H') {
Mike Stump11289f42009-09-09 15:08:12 +00001591 fprintf(stderr,
Douglas Gregor45fe0362009-05-12 01:31:05 +00001592 "error: '%s' does not appear to be a precompiled header file\n",
1593 PCHFileName.c_str());
1594 return std::string();
1595 }
1596
1597 RecordData Record;
1598 while (!Stream.AtEndOfStream()) {
1599 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001600
Douglas Gregor45fe0362009-05-12 01:31:05 +00001601 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1602 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001603
Douglas Gregor45fe0362009-05-12 01:31:05 +00001604 // We only know the PCH subblock ID.
1605 switch (BlockID) {
1606 case pch::PCH_BLOCK_ID:
1607 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1608 fprintf(stderr, "error: malformed block record in PCH file\n");
1609 return std::string();
1610 }
1611 break;
Mike Stump11289f42009-09-09 15:08:12 +00001612
Douglas Gregor45fe0362009-05-12 01:31:05 +00001613 default:
1614 if (Stream.SkipBlock()) {
1615 fprintf(stderr, "error: malformed block record in PCH file\n");
1616 return std::string();
1617 }
1618 break;
1619 }
1620 continue;
1621 }
1622
1623 if (Code == llvm::bitc::END_BLOCK) {
1624 if (Stream.ReadBlockEnd()) {
1625 fprintf(stderr, "error: error at end of module block in PCH file\n");
1626 return std::string();
1627 }
1628 continue;
1629 }
1630
1631 if (Code == llvm::bitc::DEFINE_ABBREV) {
1632 Stream.ReadAbbrevRecord();
1633 continue;
1634 }
1635
1636 Record.clear();
1637 const char *BlobStart = 0;
1638 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001639 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00001640 == pch::ORIGINAL_FILE_NAME)
1641 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00001642 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00001643
1644 return std::string();
1645}
1646
Douglas Gregor55abb232009-04-10 20:39:37 +00001647/// \brief Parse the record that corresponds to a LangOptions data
1648/// structure.
1649///
1650/// This routine compares the language options used to generate the
1651/// PCH file against the language options set for the current
1652/// compilation. For each option, we classify differences between the
1653/// two compiler states as either "benign" or "important". Benign
1654/// differences don't matter, and we accept them without complaint
1655/// (and without modifying the language options). Differences between
1656/// the states for important options cause the PCH file to be
1657/// unusable, so we emit a warning and return true to indicate that
1658/// there was an error.
1659///
1660/// \returns true if the PCH file is unacceptable, false otherwise.
1661bool PCHReader::ParseLanguageOptions(
1662 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001663 if (Listener) {
1664 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00001665
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001666 #define PARSE_LANGOPT(Option) \
1667 LangOpts.Option = Record[Idx]; \
1668 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00001669
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001670 unsigned Idx = 0;
1671 PARSE_LANGOPT(Trigraphs);
1672 PARSE_LANGOPT(BCPLComment);
1673 PARSE_LANGOPT(DollarIdents);
1674 PARSE_LANGOPT(AsmPreprocessor);
1675 PARSE_LANGOPT(GNUMode);
1676 PARSE_LANGOPT(ImplicitInt);
1677 PARSE_LANGOPT(Digraphs);
1678 PARSE_LANGOPT(HexFloats);
1679 PARSE_LANGOPT(C99);
1680 PARSE_LANGOPT(Microsoft);
1681 PARSE_LANGOPT(CPlusPlus);
1682 PARSE_LANGOPT(CPlusPlus0x);
1683 PARSE_LANGOPT(CXXOperatorNames);
1684 PARSE_LANGOPT(ObjC1);
1685 PARSE_LANGOPT(ObjC2);
1686 PARSE_LANGOPT(ObjCNonFragileABI);
1687 PARSE_LANGOPT(PascalStrings);
1688 PARSE_LANGOPT(WritableStrings);
1689 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00001690 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001691 PARSE_LANGOPT(Exceptions);
1692 PARSE_LANGOPT(NeXTRuntime);
1693 PARSE_LANGOPT(Freestanding);
1694 PARSE_LANGOPT(NoBuiltin);
1695 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00001696 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001697 PARSE_LANGOPT(Blocks);
1698 PARSE_LANGOPT(EmitAllDecls);
1699 PARSE_LANGOPT(MathErrno);
1700 PARSE_LANGOPT(OverflowChecking);
1701 PARSE_LANGOPT(HeinousExtensions);
1702 PARSE_LANGOPT(Optimize);
1703 PARSE_LANGOPT(OptimizeSize);
1704 PARSE_LANGOPT(Static);
1705 PARSE_LANGOPT(PICLevel);
1706 PARSE_LANGOPT(GNUInline);
1707 PARSE_LANGOPT(NoInline);
1708 PARSE_LANGOPT(AccessControl);
1709 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00001710 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001711 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1712 ++Idx;
1713 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1714 ++Idx;
Daniel Dunbar143021e2009-09-21 04:16:19 +00001715 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1716 Record[Idx]);
1717 ++Idx;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001718 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00001719 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001720 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00001721
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001722 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00001723 }
Douglas Gregor55abb232009-04-10 20:39:37 +00001724
1725 return false;
1726}
1727
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001728void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1729 Comments.resize(NumComments);
1730 std::copy(this->Comments, this->Comments + NumComments,
1731 Comments.begin());
1732}
1733
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001734/// \brief Read and return the type at the given offset.
1735///
1736/// This routine actually reads the record corresponding to the type
1737/// at the given offset in the bitstream. It is a helper routine for
1738/// GetType, which deals with reading type IDs.
1739QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001740 // Keep track of where we are in the stream, then jump back there
1741 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001742 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001743
Douglas Gregor1342e842009-07-06 18:54:52 +00001744 // Note that we are loading a type record.
1745 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00001746
Douglas Gregor12bfa382009-10-17 00:13:19 +00001747 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001748 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00001749 unsigned Code = DeclsCursor.ReadCode();
1750 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00001751 case pch::TYPE_EXT_QUAL: {
John McCall8ccfcb52009-09-24 19:53:00 +00001752 assert(Record.size() == 2 &&
Douglas Gregor455b8f42009-04-15 22:00:08 +00001753 "Incorrect encoding of extended qualifier type");
1754 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00001755 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1756 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00001757 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001758
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001759 case pch::TYPE_FIXED_WIDTH_INT: {
1760 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001761 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001762 }
1763
1764 case pch::TYPE_COMPLEX: {
1765 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1766 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001767 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001768 }
1769
1770 case pch::TYPE_POINTER: {
1771 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1772 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001773 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001774 }
1775
1776 case pch::TYPE_BLOCK_POINTER: {
1777 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1778 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001779 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001780 }
1781
1782 case pch::TYPE_LVALUE_REFERENCE: {
1783 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1784 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001785 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001786 }
1787
1788 case pch::TYPE_RVALUE_REFERENCE: {
1789 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1790 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001791 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001792 }
1793
1794 case pch::TYPE_MEMBER_POINTER: {
1795 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1796 QualType PointeeType = GetType(Record[0]);
1797 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001798 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001799 }
1800
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001801 case pch::TYPE_CONSTANT_ARRAY: {
1802 QualType ElementType = GetType(Record[0]);
1803 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1804 unsigned IndexTypeQuals = Record[2];
1805 unsigned Idx = 3;
1806 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00001807 return Context->getConstantArrayType(ElementType, Size,
1808 ASM, IndexTypeQuals);
1809 }
1810
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001811 case pch::TYPE_INCOMPLETE_ARRAY: {
1812 QualType ElementType = GetType(Record[0]);
1813 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1814 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00001815 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001816 }
1817
1818 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001819 QualType ElementType = GetType(Record[0]);
1820 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1821 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00001822 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1823 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001824 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00001825 ASM, IndexTypeQuals,
1826 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001827 }
1828
1829 case pch::TYPE_VECTOR: {
1830 if (Record.size() != 2) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001831 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001832 return QualType();
1833 }
1834
1835 QualType ElementType = GetType(Record[0]);
1836 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001837 return Context->getVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001838 }
1839
1840 case pch::TYPE_EXT_VECTOR: {
1841 if (Record.size() != 2) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001842 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001843 return QualType();
1844 }
1845
1846 QualType ElementType = GetType(Record[0]);
1847 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001848 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001849 }
1850
1851 case pch::TYPE_FUNCTION_NO_PROTO: {
1852 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001853 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001854 return QualType();
1855 }
1856 QualType ResultType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001857 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001858 }
1859
1860 case pch::TYPE_FUNCTION_PROTO: {
1861 QualType ResultType = GetType(Record[0]);
1862 unsigned Idx = 1;
1863 unsigned NumParams = Record[Idx++];
1864 llvm::SmallVector<QualType, 16> ParamTypes;
1865 for (unsigned I = 0; I != NumParams; ++I)
1866 ParamTypes.push_back(GetType(Record[Idx++]));
1867 bool isVariadic = Record[Idx++];
1868 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001869 bool hasExceptionSpec = Record[Idx++];
1870 bool hasAnyExceptionSpec = Record[Idx++];
1871 unsigned NumExceptions = Record[Idx++];
1872 llvm::SmallVector<QualType, 2> Exceptions;
1873 for (unsigned I = 0; I != NumExceptions; ++I)
1874 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00001875 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001876 isVariadic, Quals, hasExceptionSpec,
1877 hasAnyExceptionSpec, NumExceptions,
1878 Exceptions.data());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001879 }
1880
1881 case pch::TYPE_TYPEDEF:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001882 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001883 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001884
1885 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner8575daa2009-04-27 21:45:14 +00001886 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001887
1888 case pch::TYPE_TYPEOF: {
1889 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001890 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001891 return QualType();
1892 }
1893 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001894 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001895 }
Mike Stump11289f42009-09-09 15:08:12 +00001896
Anders Carlsson81df7b82009-06-24 19:06:50 +00001897 case pch::TYPE_DECLTYPE:
1898 return Context->getDecltypeType(ReadTypeExpr());
1899
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001900 case pch::TYPE_RECORD:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001901 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001902 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001903
Douglas Gregor1daeb692009-04-13 18:14:40 +00001904 case pch::TYPE_ENUM:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001905 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001906 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor1daeb692009-04-13 18:14:40 +00001907
John McCallfcc33b02009-09-05 00:15:47 +00001908 case pch::TYPE_ELABORATED: {
1909 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1910 unsigned Tag = Record[1];
1911 return Context->getElaboratedType(GetType(Record[0]),
1912 (ElaboratedType::TagKind) Tag);
1913 }
1914
Steve Naroffc277ad12009-07-18 15:33:26 +00001915 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00001916 unsigned Idx = 0;
1917 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1918 unsigned NumProtos = Record[Idx++];
1919 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1920 for (unsigned I = 0; I != NumProtos; ++I)
1921 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc277ad12009-07-18 15:33:26 +00001922 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00001923 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001924
Steve Narofffb4330f2009-06-17 22:40:22 +00001925 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00001926 unsigned Idx = 0;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001927 QualType OIT = GetType(Record[Idx++]);
Chris Lattner6e054af2009-04-22 06:40:03 +00001928 unsigned NumProtos = Record[Idx++];
1929 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1930 for (unsigned I = 0; I != NumProtos; ++I)
1931 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001932 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattner6e054af2009-04-22 06:40:03 +00001933 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00001934
John McCallcebee162009-10-18 09:09:24 +00001935 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
1936 unsigned Idx = 0;
1937 QualType Parm = GetType(Record[Idx++]);
1938 QualType Replacement = GetType(Record[Idx++]);
1939 return
1940 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
1941 Replacement);
1942 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001943 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001944 // Suppress a GCC warning
1945 return QualType();
1946}
1947
John McCall8f115c62009-10-16 21:56:05 +00001948namespace {
1949
1950class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
1951 PCHReader &Reader;
1952 const PCHReader::RecordData &Record;
1953 unsigned &Idx;
1954
1955public:
1956 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
1957 unsigned &Idx)
1958 : Reader(Reader), Record(Record), Idx(Idx) { }
1959
John McCall17001972009-10-18 01:05:36 +00001960 // We want compile-time assurance that we've enumerated all of
1961 // these, so unfortunately we have to declare them first, then
1962 // define them out-of-line.
1963#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00001964#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00001965 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00001966#include "clang/AST/TypeLocNodes.def"
1967
John McCall17001972009-10-18 01:05:36 +00001968 void VisitFunctionTypeLoc(FunctionTypeLoc);
1969 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00001970};
1971
1972}
1973
John McCall17001972009-10-18 01:05:36 +00001974void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00001975 // nothing to do
1976}
John McCall17001972009-10-18 01:05:36 +00001977void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1978 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001979}
John McCall17001972009-10-18 01:05:36 +00001980void TypeLocReader::VisitFixedWidthIntTypeLoc(FixedWidthIntTypeLoc TL) {
1981 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001982}
John McCall17001972009-10-18 01:05:36 +00001983void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
1984 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001985}
John McCall17001972009-10-18 01:05:36 +00001986void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
1987 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001988}
John McCall17001972009-10-18 01:05:36 +00001989void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1990 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001991}
John McCall17001972009-10-18 01:05:36 +00001992void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1993 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001994}
John McCall17001972009-10-18 01:05:36 +00001995void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1996 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001997}
John McCall17001972009-10-18 01:05:36 +00001998void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1999 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002000}
John McCall17001972009-10-18 01:05:36 +00002001void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2002 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2003 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002004 if (Record[Idx++])
John McCall17001972009-10-18 01:05:36 +00002005 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor12bfa382009-10-17 00:13:19 +00002006 else
John McCall17001972009-10-18 01:05:36 +00002007 TL.setSizeExpr(0);
2008}
2009void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2010 VisitArrayTypeLoc(TL);
2011}
2012void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2013 VisitArrayTypeLoc(TL);
2014}
2015void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2016 VisitArrayTypeLoc(TL);
2017}
2018void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2019 DependentSizedArrayTypeLoc TL) {
2020 VisitArrayTypeLoc(TL);
2021}
2022void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2023 DependentSizedExtVectorTypeLoc TL) {
2024 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2025}
2026void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2027 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2028}
2029void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2030 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2031}
2032void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2033 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2034 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2035 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002036 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002037 }
2038}
2039void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2040 VisitFunctionTypeLoc(TL);
2041}
2042void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2043 VisitFunctionTypeLoc(TL);
2044}
2045void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2046 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2047}
2048void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2049 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2050}
2051void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2052 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2053}
2054void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2055 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2056}
2057void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2058 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2059}
2060void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2061 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2062}
2063void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2064 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2065}
2066void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2067 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2068}
John McCallcebee162009-10-18 09:09:24 +00002069void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2070 SubstTemplateTypeParmTypeLoc TL) {
2071 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2072}
John McCall17001972009-10-18 01:05:36 +00002073void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2074 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002075 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2076 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2077 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2078 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2079 TL.setArgLocInfo(i,
2080 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2081 Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002082}
2083void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2084 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2085}
2086void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2087 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2088}
2089void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2090 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002091 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2092 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2093 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2094 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002095}
John McCallfc93cf92009-10-22 22:37:11 +00002096void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2097 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2098 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2099 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2100 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2101 TL.setHasProtocolsAsWritten(Record[Idx++]);
2102 if (TL.hasProtocolsAsWritten())
2103 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2104 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2105}
John McCall8f115c62009-10-16 21:56:05 +00002106
2107DeclaratorInfo *PCHReader::GetDeclaratorInfo(const RecordData &Record,
2108 unsigned &Idx) {
2109 QualType InfoTy = GetType(Record[Idx++]);
2110 if (InfoTy.isNull())
2111 return 0;
2112
2113 DeclaratorInfo *DInfo = getContext()->CreateDeclaratorInfo(InfoTy);
2114 TypeLocReader TLR(*this, Record, Idx);
2115 for (TypeLoc TL = DInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2116 TLR.Visit(TL);
2117 return DInfo;
2118}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002119
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002120QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002121 unsigned FastQuals = ID & Qualifiers::FastMask;
2122 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002123
2124 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2125 QualType T;
2126 switch ((pch::PredefinedTypeIDs)Index) {
2127 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002128 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2129 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002130
2131 case pch::PREDEF_TYPE_CHAR_U_ID:
2132 case pch::PREDEF_TYPE_CHAR_S_ID:
2133 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002134 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002135 break;
2136
Chris Lattner8575daa2009-04-27 21:45:14 +00002137 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2138 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2139 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2140 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2141 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002142 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002143 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2144 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2145 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2146 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2147 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2148 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002149 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002150 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2151 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2152 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2153 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2154 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002155 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002156 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2157 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002158 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2159 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002160 }
2161
2162 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002163 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002164 }
2165
2166 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002167 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall8ccfcb52009-09-24 19:53:00 +00002168 if (TypesLoaded[Index].isNull())
2169 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump11289f42009-09-09 15:08:12 +00002170
John McCall8ccfcb52009-09-24 19:53:00 +00002171 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002172}
2173
John McCall0ad16662009-10-29 08:12:44 +00002174TemplateArgumentLocInfo
2175PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2176 const RecordData &Record,
2177 unsigned &Index) {
2178 switch (Kind) {
2179 case TemplateArgument::Expression:
2180 return ReadDeclExpr();
2181 case TemplateArgument::Type:
2182 return GetDeclaratorInfo(Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002183 case TemplateArgument::Template: {
2184 SourceLocation
2185 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2186 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2187 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2188 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2189 TemplateNameLoc);
2190 }
John McCall0ad16662009-10-29 08:12:44 +00002191 case TemplateArgument::Null:
2192 case TemplateArgument::Integral:
2193 case TemplateArgument::Declaration:
2194 case TemplateArgument::Pack:
2195 return TemplateArgumentLocInfo();
2196 }
2197 llvm::llvm_unreachable("unexpected template argument loc");
2198 return TemplateArgumentLocInfo();
2199}
2200
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002201Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002202 if (ID == 0)
2203 return 0;
2204
Douglas Gregor745ed142009-04-25 18:35:21 +00002205 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002206 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002207 return 0;
2208 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002209
Douglas Gregor745ed142009-04-25 18:35:21 +00002210 unsigned Index = ID - 1;
2211 if (!DeclsLoaded[Index])
2212 ReadDeclRecord(DeclOffsets[Index], Index);
2213
2214 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002215}
2216
Chris Lattner9c28af02009-04-27 05:46:25 +00002217/// \brief Resolve the offset of a statement into a statement.
2218///
2219/// This operation will read a new statement from the external
2220/// source each time it is called, and is meant to be used via a
2221/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2222Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002223 // Since we know tha this statement is part of a decl, make sure to use the
2224 // decl cursor to read it.
2225 DeclsCursor.JumpToBit(Offset);
2226 return ReadStmt(DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002227}
2228
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002229bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002230 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002231 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002232 "DeclContext has no lexical decls in storage");
2233 uint64_t Offset = DeclContextOffsets[DC].first;
2234 assert(Offset && "DeclContext has no lexical decls in storage");
2235
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002236 // Keep track of where we are in the stream, then jump back there
2237 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002238 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002239
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002240 // Load the record containing all of the declarations lexically in
2241 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002242 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002243 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002244 unsigned Code = DeclsCursor.ReadCode();
2245 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002246 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002247 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2248
2249 // Load all of the declaration IDs
2250 Decls.clear();
2251 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002252 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002253 return false;
2254}
2255
2256bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner72405d62009-04-27 07:35:40 +00002257 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002258 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002259 "DeclContext has no visible decls in storage");
2260 uint64_t Offset = DeclContextOffsets[DC].second;
2261 assert(Offset && "DeclContext has no visible decls in storage");
2262
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002263 // Keep track of where we are in the stream, then jump back there
2264 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002265 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002266
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002267 // Load the record containing all of the declarations visible in
2268 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002269 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002270 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002271 unsigned Code = DeclsCursor.ReadCode();
2272 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002273 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002274 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2275 if (Record.size() == 0)
Mike Stump11289f42009-09-09 15:08:12 +00002276 return false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002277
2278 Decls.clear();
2279
2280 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002281 while (Idx < Record.size()) {
2282 Decls.push_back(VisibleDeclaration());
2283 Decls.back().Name = ReadDeclarationName(Record, Idx);
2284
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002285 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002286 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002287 LoadedDecls.reserve(Size);
2288 for (unsigned I = 0; I < Size; ++I)
2289 LoadedDecls.push_back(Record[Idx++]);
2290 }
2291
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002292 ++NumVisibleDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002293 return false;
2294}
2295
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002296void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002297 this->Consumer = Consumer;
2298
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002299 if (!Consumer)
2300 return;
2301
2302 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002303 // Force deserialization of this decl, which will cause it to be passed to
2304 // the consumer (or queued).
2305 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002306 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002307
2308 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2309 DeclGroupRef DG(InterestingDecls[I]);
2310 Consumer->HandleTopLevelDecl(DG);
2311 }
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002312}
2313
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002314void PCHReader::PrintStats() {
2315 std::fprintf(stderr, "*** PCH Statistics:\n");
2316
Mike Stump11289f42009-09-09 15:08:12 +00002317 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002318 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00002319 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00002320 unsigned NumDeclsLoaded
2321 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2322 (Decl *)0);
2323 unsigned NumIdentifiersLoaded
2324 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2325 IdentifiersLoaded.end(),
2326 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002327 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002328 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2329 SelectorsLoaded.end(),
2330 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002331
Douglas Gregorc5046832009-04-27 18:38:38 +00002332 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2333 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002334 if (TotalNumSLocEntries)
2335 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2336 NumSLocEntriesRead, TotalNumSLocEntries,
2337 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002338 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002339 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002340 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2341 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2342 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002343 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002344 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2345 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002346 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002347 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002348 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2349 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002350 if (TotalNumSelectors)
2351 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2352 NumSelectorsLoaded, TotalNumSelectors,
2353 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2354 if (TotalNumStatements)
2355 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2356 NumStatementsRead, TotalNumStatements,
2357 ((float)NumStatementsRead/TotalNumStatements * 100));
2358 if (TotalNumMacros)
2359 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2360 NumMacrosRead, TotalNumMacros,
2361 ((float)NumMacrosRead/TotalNumMacros * 100));
2362 if (TotalLexicalDeclContexts)
2363 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2364 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2365 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2366 * 100));
2367 if (TotalVisibleDeclContexts)
2368 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2369 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2370 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2371 * 100));
2372 if (TotalSelectorsInMethodPool) {
2373 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2374 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2375 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2376 * 100));
2377 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2378 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002379 std::fprintf(stderr, "\n");
2380}
2381
Douglas Gregora868bbd2009-04-21 22:25:48 +00002382void PCHReader::InitializeSema(Sema &S) {
2383 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002384 S.ExternalSource = this;
2385
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002386 // Makes sure any declarations that were deserialized "too early"
2387 // still get added to the identifier's declaration chains.
2388 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2389 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2390 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002391 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002392 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002393
2394 // If there were any tentative definitions, deserialize them and add
2395 // them to Sema's table of tentative definitions.
2396 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2397 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2398 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner0c797362009-09-08 18:19:27 +00002399 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregord4df8652009-04-22 22:02:47 +00002400 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002401
2402 // If there were any locally-scoped external declarations,
2403 // deserialize them and add them to Sema's table of locally-scoped
2404 // external declarations.
2405 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2406 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2407 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2408 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002409
2410 // If there were any ext_vector type declarations, deserialize them
2411 // and add them to Sema's vector of such declarations.
2412 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2413 SemaObj->ExtVectorDecls.push_back(
2414 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00002415}
2416
2417IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2418 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00002419 PCHIdentifierLookupTable *IdTable
Douglas Gregora868bbd2009-04-21 22:25:48 +00002420 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2421 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2422 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2423 if (Pos == IdTable->end())
2424 return 0;
2425
2426 // Dereferencing the iterator has the effect of building the
2427 // IdentifierInfo node and populating it with the various
2428 // declarations it needs.
2429 return *Pos;
2430}
2431
Mike Stump11289f42009-09-09 15:08:12 +00002432std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00002433PCHReader::ReadMethodPool(Selector Sel) {
2434 if (!MethodPoolLookupTable)
2435 return std::pair<ObjCMethodList, ObjCMethodList>();
2436
2437 // Try to find this selector within our on-disk hash table.
2438 PCHMethodPoolLookupTable *PoolTable
2439 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2440 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00002441 if (Pos == PoolTable->end()) {
2442 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002443 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00002444 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00002445
Douglas Gregor95c13f52009-04-25 17:48:32 +00002446 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002447 return *Pos;
2448}
2449
Douglas Gregor0e149972009-04-25 19:10:14 +00002450void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00002451 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002452 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00002453 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00002454}
2455
Douglas Gregor1342e842009-07-06 18:54:52 +00002456/// \brief Set the globally-visible declarations associated with the given
2457/// identifier.
2458///
2459/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00002460/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00002461/// them.
2462///
2463/// \param II an IdentifierInfo that refers to one or more globally-visible
2464/// declarations.
2465///
2466/// \param DeclIDs the set of declaration IDs with the name @p II that are
2467/// visible at global scope.
2468///
2469/// \param Nonrecursive should be true to indicate that the caller knows that
2470/// this call is non-recursive, and therefore the globally-visible declarations
2471/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00002472void
2473PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00002474 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2475 bool Nonrecursive) {
2476 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2477 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2478 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2479 PII.II = II;
2480 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2481 PII.DeclIDs.push_back(DeclIDs[I]);
2482 return;
2483 }
Mike Stump11289f42009-09-09 15:08:12 +00002484
Douglas Gregor1342e842009-07-06 18:54:52 +00002485 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2486 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2487 if (SemaObj) {
2488 // Introduce this declaration into the translation-unit scope
2489 // and add it to the declaration chain for this identifier, so
2490 // that (unqualified) name lookup will find it.
2491 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2492 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2493 } else {
2494 // Queue this declaration so that it will be added to the
2495 // translation unit scope and identifier's declaration chain
2496 // once a Sema object is known.
2497 PreloadedDecls.push_back(D);
2498 }
2499 }
2500}
2501
Chris Lattnerc523d8e2009-04-11 21:15:38 +00002502IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002503 if (ID == 0)
2504 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002505
Douglas Gregor0e149972009-04-25 19:10:14 +00002506 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002507 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002508 return 0;
2509 }
Mike Stump11289f42009-09-09 15:08:12 +00002510
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002511 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00002512 if (!IdentifiersLoaded[ID - 1]) {
2513 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor95272492009-04-25 21:21:38 +00002514 const char *Str = IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00002515
Douglas Gregorab4df582009-04-28 20:01:51 +00002516 // All of the strings in the PCH file are preceded by a 16-bit
2517 // length. Extract that 16-bit length to avoid having to execute
2518 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00002519 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2520 // unsigned integers. This is important to avoid integer overflow when
2521 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00002522 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00002523 unsigned StrLen = (((unsigned) StrLenPtr[0])
2524 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00002525 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002526 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002527 }
Mike Stump11289f42009-09-09 15:08:12 +00002528
Douglas Gregor0e149972009-04-25 19:10:14 +00002529 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002530}
2531
Douglas Gregor258ae542009-04-27 06:38:32 +00002532void PCHReader::ReadSLocEntry(unsigned ID) {
2533 ReadSLocEntryRecord(ID);
2534}
2535
Steve Naroff2ddea052009-04-23 10:39:46 +00002536Selector PCHReader::DecodeSelector(unsigned ID) {
2537 if (ID == 0)
2538 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00002539
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002540 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00002541 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002542
2543 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002544 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00002545 return Selector();
2546 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00002547
2548 unsigned Index = ID - 1;
2549 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2550 // Load this selector from the selector table.
2551 // FIXME: endianness portability issues with SelectorOffsets table
2552 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002553 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00002554 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2555 }
2556
2557 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00002558}
2559
Mike Stump11289f42009-09-09 15:08:12 +00002560DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002561PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2562 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2563 switch (Kind) {
2564 case DeclarationName::Identifier:
2565 return DeclarationName(GetIdentifierInfo(Record, Idx));
2566
2567 case DeclarationName::ObjCZeroArgSelector:
2568 case DeclarationName::ObjCOneArgSelector:
2569 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00002570 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002571
2572 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002573 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002574 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002575
2576 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002577 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002578 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002579
2580 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002581 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002582 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002583
2584 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002585 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002586 (OverloadedOperatorKind)Record[Idx++]);
2587
2588 case DeclarationName::CXXUsingDirective:
2589 return DeclarationName::getUsingDirectiveName();
2590 }
2591
2592 // Required to silence GCC warning
2593 return DeclarationName();
2594}
Douglas Gregor55abb232009-04-10 20:39:37 +00002595
Douglas Gregor1daeb692009-04-13 18:14:40 +00002596/// \brief Read an integral value
2597llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2598 unsigned BitWidth = Record[Idx++];
2599 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2600 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2601 Idx += NumWords;
2602 return Result;
2603}
2604
2605/// \brief Read a signed integral value
2606llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2607 bool isUnsigned = Record[Idx++];
2608 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2609}
2610
Douglas Gregore0a3a512009-04-14 21:55:33 +00002611/// \brief Read a floating-point value
2612llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00002613 return llvm::APFloat(ReadAPInt(Record, Idx));
2614}
2615
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002616// \brief Read a string
2617std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2618 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00002619 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002620 Idx += Len;
2621 return Result;
2622}
2623
Douglas Gregor55abb232009-04-10 20:39:37 +00002624DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00002625 return Diag(SourceLocation(), DiagID);
2626}
2627
2628DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002629 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00002630}
Douglas Gregora9af1d12009-04-17 00:04:06 +00002631
Douglas Gregora868bbd2009-04-21 22:25:48 +00002632/// \brief Retrieve the identifier table associated with the
2633/// preprocessor.
2634IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002635 assert(PP && "Forgot to set Preprocessor ?");
2636 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00002637}
2638
Douglas Gregora9af1d12009-04-17 00:04:06 +00002639/// \brief Record that the given ID maps to the given switch-case
2640/// statement.
2641void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2642 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2643 SwitchCaseStmts[ID] = SC;
2644}
2645
2646/// \brief Retrieve the switch-case statement with the given ID.
2647SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2648 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2649 return SwitchCaseStmts[ID];
2650}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002651
2652/// \brief Record that the given label statement has been
2653/// deserialized and has the given ID.
2654void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00002655 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002656 "Deserialized label twice");
2657 LabelStmts[ID] = S;
2658
2659 // If we've already seen any goto statements that point to this
2660 // label, resolve them now.
2661 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2662 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2663 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2664 Goto->second->setLabel(S);
2665 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00002666
2667 // If we've already seen any address-label statements that point to
2668 // this label, resolve them now.
2669 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00002670 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00002671 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00002672 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00002673 AddrLabel != AddrLabels.second; ++AddrLabel)
2674 AddrLabel->second->setLabel(S);
2675 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002676}
2677
2678/// \brief Set the label of the given statement to the label
2679/// identified by ID.
2680///
2681/// Depending on the order in which the label and other statements
2682/// referencing that label occur, this operation may complete
2683/// immediately (updating the statement) or it may queue the
2684/// statement to be back-patched later.
2685void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2686 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2687 if (Label != LabelStmts.end()) {
2688 // We've already seen this label, so set the label of the goto and
2689 // we're done.
2690 S->setLabel(Label->second);
2691 } else {
2692 // We haven't seen this label yet, so add this goto to the set of
2693 // unresolved goto statements.
2694 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2695 }
2696}
Douglas Gregor779d8652009-04-17 18:58:21 +00002697
2698/// \brief Set the label of the given expression to the label
2699/// identified by ID.
2700///
2701/// Depending on the order in which the label and other statements
2702/// referencing that label occur, this operation may complete
2703/// immediately (updating the statement) or it may queue the
2704/// statement to be back-patched later.
2705void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2706 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2707 if (Label != LabelStmts.end()) {
2708 // We've already seen this label, so set the label of the
2709 // label-address expression and we're done.
2710 S->setLabel(Label->second);
2711 } else {
2712 // We haven't seen this label yet, so add this label-address
2713 // expression to the set of unresolved label-address expressions.
2714 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2715 }
2716}
Douglas Gregor1342e842009-07-06 18:54:52 +00002717
2718
Mike Stump11289f42009-09-09 15:08:12 +00002719PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00002720 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2721 Reader.CurrentlyLoadingTypeOrDecl = this;
2722}
2723
2724PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2725 if (!Parent) {
2726 // If any identifiers with corresponding top-level declarations have
2727 // been loaded, load those declarations now.
2728 while (!Reader.PendingIdentifierInfos.empty()) {
2729 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2730 Reader.PendingIdentifierInfos.front().DeclIDs,
2731 true);
2732 Reader.PendingIdentifierInfos.pop_front();
2733 }
2734 }
2735
Mike Stump11289f42009-09-09 15:08:12 +00002736 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00002737}