Bug Summary

File:src/gnu/usr.bin/clang/libclangSerialization/../../../llvm/llvm/include/llvm/Bitstream/BitstreamReader.h
Warning:line 221, column 39
The result of the right shift is undefined due to shifting by '64', which is greater or equal to the width of type 'llvm::SimpleBitstreamCursor::word_t'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ASTReaderStmt.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSerialization/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libclangSerialization/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/libclangSerialization/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libclangSerialization/../include -I /usr/src/gnu/usr.bin/clang/libclangSerialization/obj -I /usr/src/gnu/usr.bin/clang/libclangSerialization/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSerialization/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libclangSerialization/../../../llvm/clang/lib/Serialization/ASTReaderStmt.cpp

/usr/src/gnu/usr.bin/clang/libclangSerialization/../../../llvm/clang/lib/Serialization/ASTReaderStmt.cpp

1//===- ASTReaderStmt.cpp - Stmt/Expr Deserialization ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Statement/expression deserialization. This implements the
10// ASTReader::ReadStmt method.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTConcept.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/AttrIterator.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclAccessPair.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclGroup.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/DependenceFlags.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/NestedNameSpecifier.h"
30#include "clang/AST/OpenMPClause.h"
31#include "clang/AST/OperationKinds.h"
32#include "clang/AST/Stmt.h"
33#include "clang/AST/StmtCXX.h"
34#include "clang/AST/StmtObjC.h"
35#include "clang/AST/StmtOpenMP.h"
36#include "clang/AST/StmtVisitor.h"
37#include "clang/AST/TemplateBase.h"
38#include "clang/AST/Type.h"
39#include "clang/AST/UnresolvedSet.h"
40#include "clang/Basic/CapturedStmt.h"
41#include "clang/Basic/ExpressionTraits.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/Lambda.h"
44#include "clang/Basic/LangOptions.h"
45#include "clang/Basic/OpenMPKinds.h"
46#include "clang/Basic/OperatorKinds.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/Specifiers.h"
49#include "clang/Basic/TypeTraits.h"
50#include "clang/Lex/Token.h"
51#include "clang/Serialization/ASTBitCodes.h"
52#include "clang/Serialization/ASTRecordReader.h"
53#include "llvm/ADT/BitmaskEnum.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/SmallString.h"
56#include "llvm/ADT/SmallVector.h"
57#include "llvm/ADT/StringRef.h"
58#include "llvm/Bitstream/BitstreamReader.h"
59#include "llvm/Support/Casting.h"
60#include "llvm/Support/ErrorHandling.h"
61#include <algorithm>
62#include <cassert>
63#include <cstdint>
64#include <string>
65
66using namespace clang;
67using namespace serialization;
68
69namespace clang {
70
71 class ASTStmtReader : public StmtVisitor<ASTStmtReader> {
72 ASTRecordReader &Record;
73 llvm::BitstreamCursor &DeclsCursor;
74
75 SourceLocation readSourceLocation() {
76 return Record.readSourceLocation();
77 }
78
79 SourceRange readSourceRange() {
80 return Record.readSourceRange();
81 }
82
83 std::string readString() {
84 return Record.readString();
85 }
86
87 TypeSourceInfo *readTypeSourceInfo() {
88 return Record.readTypeSourceInfo();
89 }
90
91 Decl *readDecl() {
92 return Record.readDecl();
93 }
94
95 template<typename T>
96 T *readDeclAs() {
97 return Record.readDeclAs<T>();
98 }
99
100 public:
101 ASTStmtReader(ASTRecordReader &Record, llvm::BitstreamCursor &Cursor)
102 : Record(Record), DeclsCursor(Cursor) {}
103
104 /// The number of record fields required for the Stmt class
105 /// itself.
106 static const unsigned NumStmtFields = 0;
107
108 /// The number of record fields required for the Expr class
109 /// itself.
110 static const unsigned NumExprFields =
111 NumStmtFields + llvm::BitWidth<ExprDependence> + 3;
112
113 /// Read and initialize a ExplicitTemplateArgumentList structure.
114 void ReadTemplateKWAndArgsInfo(ASTTemplateKWAndArgsInfo &Args,
115 TemplateArgumentLoc *ArgsLocArray,
116 unsigned NumTemplateArgs);
117
118 /// Read and initialize a ExplicitTemplateArgumentList structure.
119 void ReadExplicitTemplateArgumentList(ASTTemplateArgumentListInfo &ArgList,
120 unsigned NumTemplateArgs);
121
122 void VisitStmt(Stmt *S);
123#define STMT(Type, Base) \
124 void Visit##Type(Type *);
125#include "clang/AST/StmtNodes.inc"
126 };
127
128} // namespace clang
129
130void ASTStmtReader::ReadTemplateKWAndArgsInfo(ASTTemplateKWAndArgsInfo &Args,
131 TemplateArgumentLoc *ArgsLocArray,
132 unsigned NumTemplateArgs) {
133 SourceLocation TemplateKWLoc = readSourceLocation();
134 TemplateArgumentListInfo ArgInfo;
135 ArgInfo.setLAngleLoc(readSourceLocation());
136 ArgInfo.setRAngleLoc(readSourceLocation());
137 for (unsigned i = 0; i != NumTemplateArgs; ++i)
138 ArgInfo.addArgument(Record.readTemplateArgumentLoc());
139 Args.initializeFrom(TemplateKWLoc, ArgInfo, ArgsLocArray);
140}
141
142void ASTStmtReader::VisitStmt(Stmt *S) {
143 assert(Record.getIdx() == NumStmtFields && "Incorrect statement field count")((void)0);
144}
145
146void ASTStmtReader::VisitNullStmt(NullStmt *S) {
147 VisitStmt(S);
148 S->setSemiLoc(readSourceLocation());
149 S->NullStmtBits.HasLeadingEmptyMacro = Record.readInt();
150}
151
152void ASTStmtReader::VisitCompoundStmt(CompoundStmt *S) {
153 VisitStmt(S);
154 SmallVector<Stmt *, 16> Stmts;
155 unsigned NumStmts = Record.readInt();
156 while (NumStmts--)
157 Stmts.push_back(Record.readSubStmt());
158 S->setStmts(Stmts);
159 S->CompoundStmtBits.LBraceLoc = readSourceLocation();
160 S->RBraceLoc = readSourceLocation();
161}
162
163void ASTStmtReader::VisitSwitchCase(SwitchCase *S) {
164 VisitStmt(S);
165 Record.recordSwitchCaseID(S, Record.readInt());
166 S->setKeywordLoc(readSourceLocation());
167 S->setColonLoc(readSourceLocation());
168}
169
170void ASTStmtReader::VisitCaseStmt(CaseStmt *S) {
171 VisitSwitchCase(S);
172 bool CaseStmtIsGNURange = Record.readInt();
173 S->setLHS(Record.readSubExpr());
174 S->setSubStmt(Record.readSubStmt());
175 if (CaseStmtIsGNURange) {
176 S->setRHS(Record.readSubExpr());
177 S->setEllipsisLoc(readSourceLocation());
178 }
179}
180
181void ASTStmtReader::VisitDefaultStmt(DefaultStmt *S) {
182 VisitSwitchCase(S);
183 S->setSubStmt(Record.readSubStmt());
184}
185
186void ASTStmtReader::VisitLabelStmt(LabelStmt *S) {
187 VisitStmt(S);
188 bool IsSideEntry = Record.readInt();
189 auto *LD = readDeclAs<LabelDecl>();
190 LD->setStmt(S);
191 S->setDecl(LD);
192 S->setSubStmt(Record.readSubStmt());
193 S->setIdentLoc(readSourceLocation());
194 S->setSideEntry(IsSideEntry);
195}
196
197void ASTStmtReader::VisitAttributedStmt(AttributedStmt *S) {
198 VisitStmt(S);
199 // NumAttrs in AttributedStmt is set when creating an empty
200 // AttributedStmt in AttributedStmt::CreateEmpty, since it is needed
201 // to allocate the right amount of space for the trailing Attr *.
202 uint64_t NumAttrs = Record.readInt();
203 AttrVec Attrs;
204 Record.readAttributes(Attrs);
205 (void)NumAttrs;
206 assert(NumAttrs == S->AttributedStmtBits.NumAttrs)((void)0);
207 assert(NumAttrs == Attrs.size())((void)0);
208 std::copy(Attrs.begin(), Attrs.end(), S->getAttrArrayPtr());
209 S->SubStmt = Record.readSubStmt();
210 S->AttributedStmtBits.AttrLoc = readSourceLocation();
211}
212
213void ASTStmtReader::VisitIfStmt(IfStmt *S) {
214 VisitStmt(S);
215
216 S->setConstexpr(Record.readInt());
217 bool HasElse = Record.readInt();
218 bool HasVar = Record.readInt();
219 bool HasInit = Record.readInt();
220
221 S->setCond(Record.readSubExpr());
222 S->setThen(Record.readSubStmt());
223 if (HasElse)
224 S->setElse(Record.readSubStmt());
225 if (HasVar)
226 S->setConditionVariable(Record.getContext(), readDeclAs<VarDecl>());
227 if (HasInit)
228 S->setInit(Record.readSubStmt());
229
230 S->setIfLoc(readSourceLocation());
231 S->setLParenLoc(readSourceLocation());
232 S->setRParenLoc(readSourceLocation());
233 if (HasElse)
234 S->setElseLoc(readSourceLocation());
235}
236
237void ASTStmtReader::VisitSwitchStmt(SwitchStmt *S) {
238 VisitStmt(S);
239
240 bool HasInit = Record.readInt();
241 bool HasVar = Record.readInt();
242 bool AllEnumCasesCovered = Record.readInt();
243 if (AllEnumCasesCovered)
244 S->setAllEnumCasesCovered();
245
246 S->setCond(Record.readSubExpr());
247 S->setBody(Record.readSubStmt());
248 if (HasInit)
249 S->setInit(Record.readSubStmt());
250 if (HasVar)
251 S->setConditionVariable(Record.getContext(), readDeclAs<VarDecl>());
252
253 S->setSwitchLoc(readSourceLocation());
254 S->setLParenLoc(readSourceLocation());
255 S->setRParenLoc(readSourceLocation());
256
257 SwitchCase *PrevSC = nullptr;
258 for (auto E = Record.size(); Record.getIdx() != E; ) {
259 SwitchCase *SC = Record.getSwitchCaseWithID(Record.readInt());
260 if (PrevSC)
261 PrevSC->setNextSwitchCase(SC);
262 else
263 S->setSwitchCaseList(SC);
264
265 PrevSC = SC;
266 }
267}
268
269void ASTStmtReader::VisitWhileStmt(WhileStmt *S) {
270 VisitStmt(S);
271
272 bool HasVar = Record.readInt();
273
274 S->setCond(Record.readSubExpr());
275 S->setBody(Record.readSubStmt());
276 if (HasVar)
277 S->setConditionVariable(Record.getContext(), readDeclAs<VarDecl>());
278
279 S->setWhileLoc(readSourceLocation());
280 S->setLParenLoc(readSourceLocation());
281 S->setRParenLoc(readSourceLocation());
282}
283
284void ASTStmtReader::VisitDoStmt(DoStmt *S) {
285 VisitStmt(S);
286 S->setCond(Record.readSubExpr());
287 S->setBody(Record.readSubStmt());
288 S->setDoLoc(readSourceLocation());
289 S->setWhileLoc(readSourceLocation());
290 S->setRParenLoc(readSourceLocation());
291}
292
293void ASTStmtReader::VisitForStmt(ForStmt *S) {
294 VisitStmt(S);
295 S->setInit(Record.readSubStmt());
296 S->setCond(Record.readSubExpr());
297 S->setConditionVariable(Record.getContext(), readDeclAs<VarDecl>());
298 S->setInc(Record.readSubExpr());
299 S->setBody(Record.readSubStmt());
300 S->setForLoc(readSourceLocation());
301 S->setLParenLoc(readSourceLocation());
302 S->setRParenLoc(readSourceLocation());
303}
304
305void ASTStmtReader::VisitGotoStmt(GotoStmt *S) {
306 VisitStmt(S);
307 S->setLabel(readDeclAs<LabelDecl>());
308 S->setGotoLoc(readSourceLocation());
309 S->setLabelLoc(readSourceLocation());
310}
311
312void ASTStmtReader::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
313 VisitStmt(S);
314 S->setGotoLoc(readSourceLocation());
315 S->setStarLoc(readSourceLocation());
316 S->setTarget(Record.readSubExpr());
317}
318
319void ASTStmtReader::VisitContinueStmt(ContinueStmt *S) {
320 VisitStmt(S);
321 S->setContinueLoc(readSourceLocation());
322}
323
324void ASTStmtReader::VisitBreakStmt(BreakStmt *S) {
325 VisitStmt(S);
326 S->setBreakLoc(readSourceLocation());
327}
328
329void ASTStmtReader::VisitReturnStmt(ReturnStmt *S) {
330 VisitStmt(S);
331
332 bool HasNRVOCandidate = Record.readInt();
333
334 S->setRetValue(Record.readSubExpr());
335 if (HasNRVOCandidate)
336 S->setNRVOCandidate(readDeclAs<VarDecl>());
337
338 S->setReturnLoc(readSourceLocation());
339}
340
341void ASTStmtReader::VisitDeclStmt(DeclStmt *S) {
342 VisitStmt(S);
343 S->setStartLoc(readSourceLocation());
344 S->setEndLoc(readSourceLocation());
345
346 if (Record.size() - Record.getIdx() == 1) {
347 // Single declaration
348 S->setDeclGroup(DeclGroupRef(readDecl()));
349 } else {
350 SmallVector<Decl *, 16> Decls;
351 int N = Record.size() - Record.getIdx();
352 Decls.reserve(N);
353 for (int I = 0; I < N; ++I)
354 Decls.push_back(readDecl());
355 S->setDeclGroup(DeclGroupRef(DeclGroup::Create(Record.getContext(),
356 Decls.data(),
357 Decls.size())));
358 }
359}
360
361void ASTStmtReader::VisitAsmStmt(AsmStmt *S) {
362 VisitStmt(S);
363 S->NumOutputs = Record.readInt();
364 S->NumInputs = Record.readInt();
365 S->NumClobbers = Record.readInt();
366 S->setAsmLoc(readSourceLocation());
367 S->setVolatile(Record.readInt());
368 S->setSimple(Record.readInt());
369}
370
371void ASTStmtReader::VisitGCCAsmStmt(GCCAsmStmt *S) {
372 VisitAsmStmt(S);
373 S->NumLabels = Record.readInt();
374 S->setRParenLoc(readSourceLocation());
375 S->setAsmString(cast_or_null<StringLiteral>(Record.readSubStmt()));
376
377 unsigned NumOutputs = S->getNumOutputs();
378 unsigned NumInputs = S->getNumInputs();
379 unsigned NumClobbers = S->getNumClobbers();
380 unsigned NumLabels = S->getNumLabels();
381
382 // Outputs and inputs
383 SmallVector<IdentifierInfo *, 16> Names;
384 SmallVector<StringLiteral*, 16> Constraints;
385 SmallVector<Stmt*, 16> Exprs;
386 for (unsigned I = 0, N = NumOutputs + NumInputs; I != N; ++I) {
387 Names.push_back(Record.readIdentifier());
388 Constraints.push_back(cast_or_null<StringLiteral>(Record.readSubStmt()));
389 Exprs.push_back(Record.readSubStmt());
390 }
391
392 // Constraints
393 SmallVector<StringLiteral*, 16> Clobbers;
394 for (unsigned I = 0; I != NumClobbers; ++I)
395 Clobbers.push_back(cast_or_null<StringLiteral>(Record.readSubStmt()));
396
397 // Labels
398 for (unsigned I = 0, N = NumLabels; I != N; ++I)
399 Exprs.push_back(Record.readSubStmt());
400
401 S->setOutputsAndInputsAndClobbers(Record.getContext(),
402 Names.data(), Constraints.data(),
403 Exprs.data(), NumOutputs, NumInputs,
404 NumLabels,
405 Clobbers.data(), NumClobbers);
406}
407
408void ASTStmtReader::VisitMSAsmStmt(MSAsmStmt *S) {
409 VisitAsmStmt(S);
410 S->LBraceLoc = readSourceLocation();
411 S->EndLoc = readSourceLocation();
412 S->NumAsmToks = Record.readInt();
413 std::string AsmStr = readString();
414
415 // Read the tokens.
416 SmallVector<Token, 16> AsmToks;
417 AsmToks.reserve(S->NumAsmToks);
418 for (unsigned i = 0, e = S->NumAsmToks; i != e; ++i) {
419 AsmToks.push_back(Record.readToken());
420 }
421
422 // The calls to reserve() for the FooData vectors are mandatory to
423 // prevent dead StringRefs in the Foo vectors.
424
425 // Read the clobbers.
426 SmallVector<std::string, 16> ClobbersData;
427 SmallVector<StringRef, 16> Clobbers;
428 ClobbersData.reserve(S->NumClobbers);
429 Clobbers.reserve(S->NumClobbers);
430 for (unsigned i = 0, e = S->NumClobbers; i != e; ++i) {
431 ClobbersData.push_back(readString());
432 Clobbers.push_back(ClobbersData.back());
433 }
434
435 // Read the operands.
436 unsigned NumOperands = S->NumOutputs + S->NumInputs;
437 SmallVector<Expr*, 16> Exprs;
438 SmallVector<std::string, 16> ConstraintsData;
439 SmallVector<StringRef, 16> Constraints;
440 Exprs.reserve(NumOperands);
441 ConstraintsData.reserve(NumOperands);
442 Constraints.reserve(NumOperands);
443 for (unsigned i = 0; i != NumOperands; ++i) {
444 Exprs.push_back(cast<Expr>(Record.readSubStmt()));
445 ConstraintsData.push_back(readString());
446 Constraints.push_back(ConstraintsData.back());
447 }
448
449 S->initialize(Record.getContext(), AsmStr, AsmToks,
450 Constraints, Exprs, Clobbers);
451}
452
453void ASTStmtReader::VisitCoroutineBodyStmt(CoroutineBodyStmt *S) {
454 VisitStmt(S);
455 assert(Record.peekInt() == S->NumParams)((void)0);
456 Record.skipInts(1);
457 auto *StoredStmts = S->getStoredStmts();
458 for (unsigned i = 0;
459 i < CoroutineBodyStmt::SubStmt::FirstParamMove + S->NumParams; ++i)
460 StoredStmts[i] = Record.readSubStmt();
461}
462
463void ASTStmtReader::VisitCoreturnStmt(CoreturnStmt *S) {
464 VisitStmt(S);
465 S->CoreturnLoc = Record.readSourceLocation();
466 for (auto &SubStmt: S->SubStmts)
467 SubStmt = Record.readSubStmt();
468 S->IsImplicit = Record.readInt() != 0;
469}
470
471void ASTStmtReader::VisitCoawaitExpr(CoawaitExpr *E) {
472 VisitExpr(E);
473 E->KeywordLoc = readSourceLocation();
474 for (auto &SubExpr: E->SubExprs)
475 SubExpr = Record.readSubStmt();
476 E->OpaqueValue = cast_or_null<OpaqueValueExpr>(Record.readSubStmt());
477 E->setIsImplicit(Record.readInt() != 0);
478}
479
480void ASTStmtReader::VisitCoyieldExpr(CoyieldExpr *E) {
481 VisitExpr(E);
482 E->KeywordLoc = readSourceLocation();
483 for (auto &SubExpr: E->SubExprs)
484 SubExpr = Record.readSubStmt();
485 E->OpaqueValue = cast_or_null<OpaqueValueExpr>(Record.readSubStmt());
486}
487
488void ASTStmtReader::VisitDependentCoawaitExpr(DependentCoawaitExpr *E) {
489 VisitExpr(E);
490 E->KeywordLoc = readSourceLocation();
491 for (auto &SubExpr: E->SubExprs)
492 SubExpr = Record.readSubStmt();
493}
494
495void ASTStmtReader::VisitCapturedStmt(CapturedStmt *S) {
496 VisitStmt(S);
497 Record.skipInts(1);
498 S->setCapturedDecl(readDeclAs<CapturedDecl>());
499 S->setCapturedRegionKind(static_cast<CapturedRegionKind>(Record.readInt()));
500 S->setCapturedRecordDecl(readDeclAs<RecordDecl>());
501
502 // Capture inits
503 for (CapturedStmt::capture_init_iterator I = S->capture_init_begin(),
504 E = S->capture_init_end();
505 I != E; ++I)
506 *I = Record.readSubExpr();
507
508 // Body
509 S->setCapturedStmt(Record.readSubStmt());
510 S->getCapturedDecl()->setBody(S->getCapturedStmt());
511
512 // Captures
513 for (auto &I : S->captures()) {
514 I.VarAndKind.setPointer(readDeclAs<VarDecl>());
515 I.VarAndKind.setInt(
516 static_cast<CapturedStmt::VariableCaptureKind>(Record.readInt()));
517 I.Loc = readSourceLocation();
518 }
519}
520
521void ASTStmtReader::VisitExpr(Expr *E) {
522 VisitStmt(E);
523 E->setType(Record.readType());
524
525 // FIXME: write and read all DependentFlags with a single call.
526 bool TypeDependent = Record.readInt();
527 bool ValueDependent = Record.readInt();
528 bool InstantiationDependent = Record.readInt();
529 bool ContainsUnexpandedTemplateParameters = Record.readInt();
530 bool ContainsErrors = Record.readInt();
531 auto Deps = ExprDependence::None;
532 if (TypeDependent)
533 Deps |= ExprDependence::Type;
534 if (ValueDependent)
535 Deps |= ExprDependence::Value;
536 if (InstantiationDependent)
537 Deps |= ExprDependence::Instantiation;
538 if (ContainsUnexpandedTemplateParameters)
539 Deps |= ExprDependence::UnexpandedPack;
540 if (ContainsErrors)
541 Deps |= ExprDependence::Error;
542 E->setDependence(Deps);
543
544 E->setValueKind(static_cast<ExprValueKind>(Record.readInt()));
545 E->setObjectKind(static_cast<ExprObjectKind>(Record.readInt()));
546 assert(Record.getIdx() == NumExprFields &&((void)0)
547 "Incorrect expression field count")((void)0);
548}
549
550void ASTStmtReader::VisitConstantExpr(ConstantExpr *E) {
551 VisitExpr(E);
552
553 auto StorageKind = Record.readInt();
554 assert(E->ConstantExprBits.ResultKind == StorageKind && "Wrong ResultKind!")((void)0);
555
556 E->ConstantExprBits.APValueKind = Record.readInt();
557 E->ConstantExprBits.IsUnsigned = Record.readInt();
558 E->ConstantExprBits.BitWidth = Record.readInt();
559 E->ConstantExprBits.HasCleanup = false; // Not serialized, see below.
560 E->ConstantExprBits.IsImmediateInvocation = Record.readInt();
561
562 switch (StorageKind) {
563 case ConstantExpr::RSK_None:
564 break;
565
566 case ConstantExpr::RSK_Int64:
567 E->Int64Result() = Record.readInt();
568 break;
569
570 case ConstantExpr::RSK_APValue:
571 E->APValueResult() = Record.readAPValue();
572 if (E->APValueResult().needsCleanup()) {
573 E->ConstantExprBits.HasCleanup = true;
574 Record.getContext().addDestruction(&E->APValueResult());
575 }
576 break;
577 default:
578 llvm_unreachable("unexpected ResultKind!")__builtin_unreachable();
579 }
580
581 E->setSubExpr(Record.readSubExpr());
582}
583
584void ASTStmtReader::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E) {
585 VisitExpr(E);
586
587 E->setLocation(readSourceLocation());
588 E->setLParenLocation(readSourceLocation());
589 E->setRParenLocation(readSourceLocation());
590
591 E->setTypeSourceInfo(Record.readTypeSourceInfo());
592}
593
594void ASTStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
595 VisitExpr(E);
596 bool HasFunctionName = Record.readInt();
597 E->PredefinedExprBits.HasFunctionName = HasFunctionName;
598 E->PredefinedExprBits.Kind = Record.readInt();
599 E->setLocation(readSourceLocation());
600 if (HasFunctionName)
601 E->setFunctionName(cast<StringLiteral>(Record.readSubExpr()));
602}
603
604void ASTStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
605 VisitExpr(E);
606
607 E->DeclRefExprBits.HasQualifier = Record.readInt();
608 E->DeclRefExprBits.HasFoundDecl = Record.readInt();
609 E->DeclRefExprBits.HasTemplateKWAndArgsInfo = Record.readInt();
610 E->DeclRefExprBits.HadMultipleCandidates = Record.readInt();
611 E->DeclRefExprBits.RefersToEnclosingVariableOrCapture = Record.readInt();
612 E->DeclRefExprBits.NonOdrUseReason = Record.readInt();
613 unsigned NumTemplateArgs = 0;
614 if (E->hasTemplateKWAndArgsInfo())
615 NumTemplateArgs = Record.readInt();
616
617 if (E->hasQualifier())
618 new (E->getTrailingObjects<NestedNameSpecifierLoc>())
619 NestedNameSpecifierLoc(Record.readNestedNameSpecifierLoc());
620
621 if (E->hasFoundDecl())
622 *E->getTrailingObjects<NamedDecl *>() = readDeclAs<NamedDecl>();
623
624 if (E->hasTemplateKWAndArgsInfo())
625 ReadTemplateKWAndArgsInfo(
626 *E->getTrailingObjects<ASTTemplateKWAndArgsInfo>(),
627 E->getTrailingObjects<TemplateArgumentLoc>(), NumTemplateArgs);
628
629 E->D = readDeclAs<ValueDecl>();
630 E->setLocation(readSourceLocation());
631 E->DNLoc = Record.readDeclarationNameLoc(E->getDecl()->getDeclName());
632}
633
634void ASTStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
635 VisitExpr(E);
636 E->setLocation(readSourceLocation());
637 E->setValue(Record.getContext(), Record.readAPInt());
638}
639
640void ASTStmtReader::VisitFixedPointLiteral(FixedPointLiteral *E) {
641 VisitExpr(E);
642 E->setLocation(readSourceLocation());
643 E->setScale(Record.readInt());
644 E->setValue(Record.getContext(), Record.readAPInt());
645}
646
647void ASTStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
648 VisitExpr(E);
649 E->setRawSemantics(
650 static_cast<llvm::APFloatBase::Semantics>(Record.readInt()));
651 E->setExact(Record.readInt());
652 E->setValue(Record.getContext(), Record.readAPFloat(E->getSemantics()));
653 E->setLocation(readSourceLocation());
654}
655
656void ASTStmtReader::VisitImaginaryLiteral(ImaginaryLiteral *E) {
657 VisitExpr(E);
658 E->setSubExpr(Record.readSubExpr());
659}
660
661void ASTStmtReader::VisitStringLiteral(StringLiteral *E) {
662 VisitExpr(E);
663
664 // NumConcatenated, Length and CharByteWidth are set by the empty
665 // ctor since they are needed to allocate storage for the trailing objects.
666 unsigned NumConcatenated = Record.readInt();
667 unsigned Length = Record.readInt();
668 unsigned CharByteWidth = Record.readInt();
669 assert((NumConcatenated == E->getNumConcatenated()) &&((void)0)
670 "Wrong number of concatenated tokens!")((void)0);
671 assert((Length == E->getLength()) && "Wrong Length!")((void)0);
672 assert((CharByteWidth == E->getCharByteWidth()) && "Wrong character width!")((void)0);
673 E->StringLiteralBits.Kind = Record.readInt();
674 E->StringLiteralBits.IsPascal = Record.readInt();
675
676 // The character width is originally computed via mapCharByteWidth.
677 // Check that the deserialized character width is consistant with the result
678 // of calling mapCharByteWidth.
679 assert((CharByteWidth ==((void)0)
680 StringLiteral::mapCharByteWidth(Record.getContext().getTargetInfo(),((void)0)
681 E->getKind())) &&((void)0)
682 "Wrong character width!")((void)0);
683
684 // Deserialize the trailing array of SourceLocation.
685 for (unsigned I = 0; I < NumConcatenated; ++I)
686 E->setStrTokenLoc(I, readSourceLocation());
687
688 // Deserialize the trailing array of char holding the string data.
689 char *StrData = E->getStrDataAsChar();
690 for (unsigned I = 0; I < Length * CharByteWidth; ++I)
691 StrData[I] = Record.readInt();
692}
693
694void ASTStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
695 VisitExpr(E);
696 E->setValue(Record.readInt());
697 E->setLocation(readSourceLocation());
698 E->setKind(static_cast<CharacterLiteral::CharacterKind>(Record.readInt()));
699}
700
701void ASTStmtReader::VisitParenExpr(ParenExpr *E) {
702 VisitExpr(E);
703 E->setLParen(readSourceLocation());
704 E->setRParen(readSourceLocation());
705 E->setSubExpr(Record.readSubExpr());
706}
707
708void ASTStmtReader::VisitParenListExpr(ParenListExpr *E) {
709 VisitExpr(E);
710 unsigned NumExprs = Record.readInt();
711 assert((NumExprs == E->getNumExprs()) && "Wrong NumExprs!")((void)0);
712 for (unsigned I = 0; I != NumExprs; ++I)
713 E->getTrailingObjects<Stmt *>()[I] = Record.readSubStmt();
714 E->LParenLoc = readSourceLocation();
715 E->RParenLoc = readSourceLocation();
716}
717
718void ASTStmtReader::VisitUnaryOperator(UnaryOperator *E) {
719 VisitExpr(E);
720 bool hasFP_Features = Record.readInt();
721 assert(hasFP_Features == E->hasStoredFPFeatures())((void)0);
722 E->setSubExpr(Record.readSubExpr());
723 E->setOpcode((UnaryOperator::Opcode)Record.readInt());
724 E->setOperatorLoc(readSourceLocation());
725 E->setCanOverflow(Record.readInt());
726 if (hasFP_Features)
727 E->setStoredFPFeatures(
728 FPOptionsOverride::getFromOpaqueInt(Record.readInt()));
729}
730
731void ASTStmtReader::VisitOffsetOfExpr(OffsetOfExpr *E) {
732 VisitExpr(E);
733 assert(E->getNumComponents() == Record.peekInt())((void)0);
734 Record.skipInts(1);
735 assert(E->getNumExpressions() == Record.peekInt())((void)0);
736 Record.skipInts(1);
737 E->setOperatorLoc(readSourceLocation());
738 E->setRParenLoc(readSourceLocation());
739 E->setTypeSourceInfo(readTypeSourceInfo());
740 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
741 auto Kind = static_cast<OffsetOfNode::Kind>(Record.readInt());
742 SourceLocation Start = readSourceLocation();
743 SourceLocation End = readSourceLocation();
744 switch (Kind) {
745 case OffsetOfNode::Array:
746 E->setComponent(I, OffsetOfNode(Start, Record.readInt(), End));
747 break;
748
749 case OffsetOfNode::Field:
750 E->setComponent(
751 I, OffsetOfNode(Start, readDeclAs<FieldDecl>(), End));
752 break;
753
754 case OffsetOfNode::Identifier:
755 E->setComponent(
756 I,
757 OffsetOfNode(Start, Record.readIdentifier(), End));
758 break;
759
760 case OffsetOfNode::Base: {
761 auto *Base = new (Record.getContext()) CXXBaseSpecifier();
762 *Base = Record.readCXXBaseSpecifier();
763 E->setComponent(I, OffsetOfNode(Base));
764 break;
765 }
766 }
767 }
768
769 for (unsigned I = 0, N = E->getNumExpressions(); I != N; ++I)
770 E->setIndexExpr(I, Record.readSubExpr());
771}
772
773void ASTStmtReader::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) {
774 VisitExpr(E);
775 E->setKind(static_cast<UnaryExprOrTypeTrait>(Record.readInt()));
776 if (Record.peekInt() == 0) {
777 E->setArgument(Record.readSubExpr());
778 Record.skipInts(1);
779 } else {
780 E->setArgument(readTypeSourceInfo());
781 }
782 E->setOperatorLoc(readSourceLocation());
783 E->setRParenLoc(readSourceLocation());
784}
785
786static ConstraintSatisfaction
787readConstraintSatisfaction(ASTRecordReader &Record) {
788 ConstraintSatisfaction Satisfaction;
789 Satisfaction.IsSatisfied = Record.readInt();
790 if (!Satisfaction.IsSatisfied) {
791 unsigned NumDetailRecords = Record.readInt();
792 for (unsigned i = 0; i != NumDetailRecords; ++i) {
793 Expr *ConstraintExpr = Record.readExpr();
794 if (/* IsDiagnostic */Record.readInt()) {
795 SourceLocation DiagLocation = Record.readSourceLocation();
796 std::string DiagMessage = Record.readString();
797 Satisfaction.Details.emplace_back(
798 ConstraintExpr, new (Record.getContext())
799 ConstraintSatisfaction::SubstitutionDiagnostic{
800 DiagLocation, DiagMessage});
801 } else
802 Satisfaction.Details.emplace_back(ConstraintExpr, Record.readExpr());
803 }
804 }
805 return Satisfaction;
806}
807
808void ASTStmtReader::VisitConceptSpecializationExpr(
809 ConceptSpecializationExpr *E) {
810 VisitExpr(E);
811 unsigned NumTemplateArgs = Record.readInt();
812 E->NestedNameSpec = Record.readNestedNameSpecifierLoc();
813 E->TemplateKWLoc = Record.readSourceLocation();
814 E->ConceptName = Record.readDeclarationNameInfo();
815 E->NamedConcept = readDeclAs<ConceptDecl>();
816 E->FoundDecl = Record.readDeclAs<NamedDecl>();
817 E->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
818 llvm::SmallVector<TemplateArgument, 4> Args;
819 for (unsigned I = 0; I < NumTemplateArgs; ++I)
820 Args.push_back(Record.readTemplateArgument());
821 E->setTemplateArguments(Args);
822 E->Satisfaction = E->isValueDependent() ? nullptr :
823 ASTConstraintSatisfaction::Create(Record.getContext(),
824 readConstraintSatisfaction(Record));
825}
826
827static concepts::Requirement::SubstitutionDiagnostic *
828readSubstitutionDiagnostic(ASTRecordReader &Record) {
829 std::string SubstitutedEntity = Record.readString();
830 SourceLocation DiagLoc = Record.readSourceLocation();
831 std::string DiagMessage = Record.readString();
832 return new (Record.getContext())
833 concepts::Requirement::SubstitutionDiagnostic{SubstitutedEntity, DiagLoc,
834 DiagMessage};
835}
836
837void ASTStmtReader::VisitRequiresExpr(RequiresExpr *E) {
838 VisitExpr(E);
839 unsigned NumLocalParameters = Record.readInt();
840 unsigned NumRequirements = Record.readInt();
841 E->RequiresExprBits.RequiresKWLoc = Record.readSourceLocation();
842 E->RequiresExprBits.IsSatisfied = Record.readInt();
843 E->Body = Record.readDeclAs<RequiresExprBodyDecl>();
844 llvm::SmallVector<ParmVarDecl *, 4> LocalParameters;
845 for (unsigned i = 0; i < NumLocalParameters; ++i)
846 LocalParameters.push_back(cast<ParmVarDecl>(Record.readDecl()));
847 std::copy(LocalParameters.begin(), LocalParameters.end(),
848 E->getTrailingObjects<ParmVarDecl *>());
849 llvm::SmallVector<concepts::Requirement *, 4> Requirements;
850 for (unsigned i = 0; i < NumRequirements; ++i) {
851 auto RK =
852 static_cast<concepts::Requirement::RequirementKind>(Record.readInt());
853 concepts::Requirement *R = nullptr;
854 switch (RK) {
855 case concepts::Requirement::RK_Type: {
856 auto Status =
857 static_cast<concepts::TypeRequirement::SatisfactionStatus>(
858 Record.readInt());
859 if (Status == concepts::TypeRequirement::SS_SubstitutionFailure)
860 R = new (Record.getContext())
861 concepts::TypeRequirement(readSubstitutionDiagnostic(Record));
862 else
863 R = new (Record.getContext())
864 concepts::TypeRequirement(Record.readTypeSourceInfo());
865 } break;
866 case concepts::Requirement::RK_Simple:
867 case concepts::Requirement::RK_Compound: {
868 auto Status =
869 static_cast<concepts::ExprRequirement::SatisfactionStatus>(
870 Record.readInt());
871 llvm::PointerUnion<concepts::Requirement::SubstitutionDiagnostic *,
872 Expr *> E;
873 if (Status == concepts::ExprRequirement::SS_ExprSubstitutionFailure) {
874 E = readSubstitutionDiagnostic(Record);
875 } else
876 E = Record.readExpr();
877
878 llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> Req;
879 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
880 SourceLocation NoexceptLoc;
881 if (RK == concepts::Requirement::RK_Simple) {
882 Req.emplace();
883 } else {
884 NoexceptLoc = Record.readSourceLocation();
885 switch (/* returnTypeRequirementKind */Record.readInt()) {
886 case 0:
887 // No return type requirement.
888 Req.emplace();
889 break;
890 case 1: {
891 // type-constraint
892 TemplateParameterList *TPL = Record.readTemplateParameterList();
893 if (Status >=
894 concepts::ExprRequirement::SS_ConstraintsNotSatisfied)
895 SubstitutedConstraintExpr =
896 cast<ConceptSpecializationExpr>(Record.readExpr());
897 Req.emplace(TPL);
898 } break;
899 case 2:
900 // Substitution failure
901 Req.emplace(readSubstitutionDiagnostic(Record));
902 break;
903 }
904 }
905 if (Expr *Ex = E.dyn_cast<Expr *>())
906 R = new (Record.getContext()) concepts::ExprRequirement(
907 Ex, RK == concepts::Requirement::RK_Simple, NoexceptLoc,
908 std::move(*Req), Status, SubstitutedConstraintExpr);
909 else
910 R = new (Record.getContext()) concepts::ExprRequirement(
911 E.get<concepts::Requirement::SubstitutionDiagnostic *>(),
912 RK == concepts::Requirement::RK_Simple, NoexceptLoc,
913 std::move(*Req));
914 } break;
915 case concepts::Requirement::RK_Nested: {
916 if (/* IsSubstitutionDiagnostic */Record.readInt()) {
917 R = new (Record.getContext()) concepts::NestedRequirement(
918 readSubstitutionDiagnostic(Record));
919 break;
920 }
921 Expr *E = Record.readExpr();
922 if (E->isInstantiationDependent())
923 R = new (Record.getContext()) concepts::NestedRequirement(E);
924 else
925 R = new (Record.getContext())
926 concepts::NestedRequirement(Record.getContext(), E,
927 readConstraintSatisfaction(Record));
928 } break;
929 }
930 if (!R)
931 continue;
932 Requirements.push_back(R);
933 }
934 std::copy(Requirements.begin(), Requirements.end(),
935 E->getTrailingObjects<concepts::Requirement *>());
936 E->RBraceLoc = Record.readSourceLocation();
937}
938
939void ASTStmtReader::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
940 VisitExpr(E);
941 E->setLHS(Record.readSubExpr());
942 E->setRHS(Record.readSubExpr());
943 E->setRBracketLoc(readSourceLocation());
944}
945
946void ASTStmtReader::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
947 VisitExpr(E);
948 E->setBase(Record.readSubExpr());
949 E->setRowIdx(Record.readSubExpr());
950 E->setColumnIdx(Record.readSubExpr());
951 E->setRBracketLoc(readSourceLocation());
952}
953
954void ASTStmtReader::VisitOMPArraySectionExpr(OMPArraySectionExpr *E) {
955 VisitExpr(E);
956 E->setBase(Record.readSubExpr());
957 E->setLowerBound(Record.readSubExpr());
958 E->setLength(Record.readSubExpr());
959 E->setStride(Record.readSubExpr());
960 E->setColonLocFirst(readSourceLocation());
961 E->setColonLocSecond(readSourceLocation());
962 E->setRBracketLoc(readSourceLocation());
963}
964
965void ASTStmtReader::VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
966 VisitExpr(E);
967 unsigned NumDims = Record.readInt();
968 E->setBase(Record.readSubExpr());
969 SmallVector<Expr *, 4> Dims(NumDims);
970 for (unsigned I = 0; I < NumDims; ++I)
971 Dims[I] = Record.readSubExpr();
972 E->setDimensions(Dims);
973 SmallVector<SourceRange, 4> SRs(NumDims);
974 for (unsigned I = 0; I < NumDims; ++I)
975 SRs[I] = readSourceRange();
976 E->setBracketsRanges(SRs);
977 E->setLParenLoc(readSourceLocation());
978 E->setRParenLoc(readSourceLocation());
979}
980
981void ASTStmtReader::VisitOMPIteratorExpr(OMPIteratorExpr *E) {
982 VisitExpr(E);
983 unsigned NumIters = Record.readInt();
984 E->setIteratorKwLoc(readSourceLocation());
985 E->setLParenLoc(readSourceLocation());
986 E->setRParenLoc(readSourceLocation());
987 for (unsigned I = 0; I < NumIters; ++I) {
988 E->setIteratorDeclaration(I, Record.readDeclRef());
989 E->setAssignmentLoc(I, readSourceLocation());
990 Expr *Begin = Record.readSubExpr();
991 Expr *End = Record.readSubExpr();
992 Expr *Step = Record.readSubExpr();
993 SourceLocation ColonLoc = readSourceLocation();
994 SourceLocation SecColonLoc;
995 if (Step)
996 SecColonLoc = readSourceLocation();
997 E->setIteratorRange(I, Begin, ColonLoc, End, SecColonLoc, Step);
998 // Deserialize helpers
999 OMPIteratorHelperData HD;
1000 HD.CounterVD = cast_or_null<VarDecl>(Record.readDeclRef());
1001 HD.Upper = Record.readSubExpr();
1002 HD.Update = Record.readSubExpr();
1003 HD.CounterUpdate = Record.readSubExpr();
1004 E->setHelper(I, HD);
1005 }
1006}
1007
1008void ASTStmtReader::VisitCallExpr(CallExpr *E) {
1009 VisitExpr(E);
1010 unsigned NumArgs = Record.readInt();
1011 bool HasFPFeatures = Record.readInt();
1012 assert((NumArgs == E->getNumArgs()) && "Wrong NumArgs!")((void)0);
1013 E->setRParenLoc(readSourceLocation());
1014 E->setCallee(Record.readSubExpr());
1015 for (unsigned I = 0; I != NumArgs; ++I)
1016 E->setArg(I, Record.readSubExpr());
1017 E->setADLCallKind(static_cast<CallExpr::ADLCallKind>(Record.readInt()));
1018 if (HasFPFeatures)
1019 E->setStoredFPFeatures(
1020 FPOptionsOverride::getFromOpaqueInt(Record.readInt()));
1021}
1022
1023void ASTStmtReader::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1024 VisitCallExpr(E);
1025}
1026
1027void ASTStmtReader::VisitMemberExpr(MemberExpr *E) {
1028 VisitExpr(E);
1029
1030 bool HasQualifier = Record.readInt();
1031 bool HasFoundDecl = Record.readInt();
1032 bool HasTemplateInfo = Record.readInt();
1033 unsigned NumTemplateArgs = Record.readInt();
1034
1035 E->Base = Record.readSubExpr();
1036 E->MemberDecl = Record.readDeclAs<ValueDecl>();
1037 E->MemberDNLoc = Record.readDeclarationNameLoc(E->MemberDecl->getDeclName());
1038 E->MemberLoc = Record.readSourceLocation();
1039 E->MemberExprBits.IsArrow = Record.readInt();
1040 E->MemberExprBits.HasQualifierOrFoundDecl = HasQualifier || HasFoundDecl;
1041 E->MemberExprBits.HasTemplateKWAndArgsInfo = HasTemplateInfo;
1042 E->MemberExprBits.HadMultipleCandidates = Record.readInt();
1043 E->MemberExprBits.NonOdrUseReason = Record.readInt();
1044 E->MemberExprBits.OperatorLoc = Record.readSourceLocation();
1045
1046 if (HasQualifier || HasFoundDecl) {
1047 DeclAccessPair FoundDecl;
1048 if (HasFoundDecl) {
1049 auto *FoundD = Record.readDeclAs<NamedDecl>();
1050 auto AS = (AccessSpecifier)Record.readInt();
1051 FoundDecl = DeclAccessPair::make(FoundD, AS);
1052 } else {
1053 FoundDecl = DeclAccessPair::make(E->MemberDecl,
1054 E->MemberDecl->getAccess());
1055 }
1056 E->getTrailingObjects<MemberExprNameQualifier>()->FoundDecl = FoundDecl;
1057
1058 NestedNameSpecifierLoc QualifierLoc;
1059 if (HasQualifier)
1060 QualifierLoc = Record.readNestedNameSpecifierLoc();
1061 E->getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc =
1062 QualifierLoc;
1063 }
1064
1065 if (HasTemplateInfo)
1066 ReadTemplateKWAndArgsInfo(
1067 *E->getTrailingObjects<ASTTemplateKWAndArgsInfo>(),
1068 E->getTrailingObjects<TemplateArgumentLoc>(), NumTemplateArgs);
1069}
1070
1071void ASTStmtReader::VisitObjCIsaExpr(ObjCIsaExpr *E) {
1072 VisitExpr(E);
1073 E->setBase(Record.readSubExpr());
1074 E->setIsaMemberLoc(readSourceLocation());
1075 E->setOpLoc(readSourceLocation());
1076 E->setArrow(Record.readInt());
1077}
1078
1079void ASTStmtReader::
1080VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
1081 VisitExpr(E);
1082 E->Operand = Record.readSubExpr();
1083 E->setShouldCopy(Record.readInt());
1084}
1085
1086void ASTStmtReader::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
1087 VisitExplicitCastExpr(E);
1088 E->LParenLoc = readSourceLocation();
1089 E->BridgeKeywordLoc = readSourceLocation();
1090 E->Kind = Record.readInt();
1091}
1092
1093void ASTStmtReader::VisitCastExpr(CastExpr *E) {
1094 VisitExpr(E);
1095 unsigned NumBaseSpecs = Record.readInt();
1096 assert(NumBaseSpecs == E->path_size())((void)0);
1097 unsigned HasFPFeatures = Record.readInt();
1098 assert(E->hasStoredFPFeatures() == HasFPFeatures)((void)0);
1099 E->setSubExpr(Record.readSubExpr());
1100 E->setCastKind((CastKind)Record.readInt());
1101 CastExpr::path_iterator BaseI = E->path_begin();
1102 while (NumBaseSpecs--) {
1103 auto *BaseSpec = new (Record.getContext()) CXXBaseSpecifier;
1104 *BaseSpec = Record.readCXXBaseSpecifier();
1105 *BaseI++ = BaseSpec;
1106 }
1107 if (HasFPFeatures)
1108 *E->getTrailingFPFeatures() =
1109 FPOptionsOverride::getFromOpaqueInt(Record.readInt());
1110}
1111
1112void ASTStmtReader::VisitBinaryOperator(BinaryOperator *E) {
1113 bool hasFP_Features;
1114 VisitExpr(E);
1115 E->setHasStoredFPFeatures(hasFP_Features = Record.readInt());
1116 E->setOpcode((BinaryOperator::Opcode)Record.readInt());
1117 E->setLHS(Record.readSubExpr());
1118 E->setRHS(Record.readSubExpr());
1119 E->setOperatorLoc(readSourceLocation());
1120 if (hasFP_Features)
1121 E->setStoredFPFeatures(
1122 FPOptionsOverride::getFromOpaqueInt(Record.readInt()));
1123}
1124
1125void ASTStmtReader::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
1126 VisitBinaryOperator(E);
1127 E->setComputationLHSType(Record.readType());
1128 E->setComputationResultType(Record.readType());
1129}
1130
1131void ASTStmtReader::VisitConditionalOperator(ConditionalOperator *E) {
1132 VisitExpr(E);
1133 E->SubExprs[ConditionalOperator::COND] = Record.readSubExpr();
1134 E->SubExprs[ConditionalOperator::LHS] = Record.readSubExpr();
1135 E->SubExprs[ConditionalOperator::RHS] = Record.readSubExpr();
1136 E->QuestionLoc = readSourceLocation();
1137 E->ColonLoc = readSourceLocation();
1138}
1139
1140void
1141ASTStmtReader::VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1142 VisitExpr(E);
1143 E->OpaqueValue = cast<OpaqueValueExpr>(Record.readSubExpr());
1144 E->SubExprs[BinaryConditionalOperator::COMMON] = Record.readSubExpr();
1145 E->SubExprs[BinaryConditionalOperator::COND] = Record.readSubExpr();
1146 E->SubExprs[BinaryConditionalOperator::LHS] = Record.readSubExpr();
1147 E->SubExprs[BinaryConditionalOperator::RHS] = Record.readSubExpr();
1148 E->QuestionLoc = readSourceLocation();
1149 E->ColonLoc = readSourceLocation();
1150}
1151
1152void ASTStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
1153 VisitCastExpr(E);
1154 E->setIsPartOfExplicitCast(Record.readInt());
1155}
1156
1157void ASTStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1158 VisitCastExpr(E);
1159 E->setTypeInfoAsWritten(readTypeSourceInfo());
1160}
1161
1162void ASTStmtReader::VisitCStyleCastExpr(CStyleCastExpr *E) {
1163 VisitExplicitCastExpr(E);
1164 E->setLParenLoc(readSourceLocation());
1165 E->setRParenLoc(readSourceLocation());
1166}
1167
1168void ASTStmtReader::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1169 VisitExpr(E);
1170 E->setLParenLoc(readSourceLocation());
1171 E->setTypeSourceInfo(readTypeSourceInfo());
1172 E->setInitializer(Record.readSubExpr());
1173 E->setFileScope(Record.readInt());
1174}
1175
1176void ASTStmtReader::VisitExtVectorElementExpr(ExtVectorElementExpr *E) {
1177 VisitExpr(E);
1178 E->setBase(Record.readSubExpr());
1179 E->setAccessor(Record.readIdentifier());
1180 E->setAccessorLoc(readSourceLocation());
1181}
1182
1183void ASTStmtReader::VisitInitListExpr(InitListExpr *E) {
1184 VisitExpr(E);
1185 if (auto *SyntForm = cast_or_null<InitListExpr>(Record.readSubStmt()))
1186 E->setSyntacticForm(SyntForm);
1187 E->setLBraceLoc(readSourceLocation());
1188 E->setRBraceLoc(readSourceLocation());
1189 bool isArrayFiller = Record.readInt();
1190 Expr *filler = nullptr;
1191 if (isArrayFiller) {
1192 filler = Record.readSubExpr();
1193 E->ArrayFillerOrUnionFieldInit = filler;
1194 } else
1195 E->ArrayFillerOrUnionFieldInit = readDeclAs<FieldDecl>();
1196 E->sawArrayRangeDesignator(Record.readInt());
1197 unsigned NumInits = Record.readInt();
1198 E->reserveInits(Record.getContext(), NumInits);
1199 if (isArrayFiller) {
1200 for (unsigned I = 0; I != NumInits; ++I) {
1201 Expr *init = Record.readSubExpr();
1202 E->updateInit(Record.getContext(), I, init ? init : filler);
1203 }
1204 } else {
1205 for (unsigned I = 0; I != NumInits; ++I)
1206 E->updateInit(Record.getContext(), I, Record.readSubExpr());
1207 }
1208}
1209
1210void ASTStmtReader::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1211 using Designator = DesignatedInitExpr::Designator;
1212
1213 VisitExpr(E);
1214 unsigned NumSubExprs = Record.readInt();
1215 assert(NumSubExprs == E->getNumSubExprs() && "Wrong number of subexprs")((void)0);
1216 for (unsigned I = 0; I != NumSubExprs; ++I)
1217 E->setSubExpr(I, Record.readSubExpr());
1218 E->setEqualOrColonLoc(readSourceLocation());
1219 E->setGNUSyntax(Record.readInt());
1220
1221 SmallVector<Designator, 4> Designators;
1222 while (Record.getIdx() < Record.size()) {
1223 switch ((DesignatorTypes)Record.readInt()) {
1224 case DESIG_FIELD_DECL: {
1225 auto *Field = readDeclAs<FieldDecl>();
1226 SourceLocation DotLoc = readSourceLocation();
1227 SourceLocation FieldLoc = readSourceLocation();
1228 Designators.push_back(Designator(Field->getIdentifier(), DotLoc,
1229 FieldLoc));
1230 Designators.back().setField(Field);
1231 break;
1232 }
1233
1234 case DESIG_FIELD_NAME: {
1235 const IdentifierInfo *Name = Record.readIdentifier();
1236 SourceLocation DotLoc = readSourceLocation();
1237 SourceLocation FieldLoc = readSourceLocation();
1238 Designators.push_back(Designator(Name, DotLoc, FieldLoc));
1239 break;
1240 }
1241
1242 case DESIG_ARRAY: {
1243 unsigned Index = Record.readInt();
1244 SourceLocation LBracketLoc = readSourceLocation();
1245 SourceLocation RBracketLoc = readSourceLocation();
1246 Designators.push_back(Designator(Index, LBracketLoc, RBracketLoc));
1247 break;
1248 }
1249
1250 case DESIG_ARRAY_RANGE: {
1251 unsigned Index = Record.readInt();
1252 SourceLocation LBracketLoc = readSourceLocation();
1253 SourceLocation EllipsisLoc = readSourceLocation();
1254 SourceLocation RBracketLoc = readSourceLocation();
1255 Designators.push_back(Designator(Index, LBracketLoc, EllipsisLoc,
1256 RBracketLoc));
1257 break;
1258 }
1259 }
1260 }
1261 E->setDesignators(Record.getContext(),
1262 Designators.data(), Designators.size());
1263}
1264
1265void ASTStmtReader::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
1266 VisitExpr(E);
1267 E->setBase(Record.readSubExpr());
1268 E->setUpdater(Record.readSubExpr());
1269}
1270
1271void ASTStmtReader::VisitNoInitExpr(NoInitExpr *E) {
1272 VisitExpr(E);
1273}
1274
1275void ASTStmtReader::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) {
1276 VisitExpr(E);
1277 E->SubExprs[0] = Record.readSubExpr();
1278 E->SubExprs[1] = Record.readSubExpr();
1279}
1280
1281void ASTStmtReader::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
1282 VisitExpr(E);
1283}
1284
1285void ASTStmtReader::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
1286 VisitExpr(E);
1287}
1288
1289void ASTStmtReader::VisitVAArgExpr(VAArgExpr *E) {
1290 VisitExpr(E);
1291 E->setSubExpr(Record.readSubExpr());
1292 E->setWrittenTypeInfo(readTypeSourceInfo());
1293 E->setBuiltinLoc(readSourceLocation());
1294 E->setRParenLoc(readSourceLocation());
1295 E->setIsMicrosoftABI(Record.readInt());
1296}
1297
1298void ASTStmtReader::VisitSourceLocExpr(SourceLocExpr *E) {
1299 VisitExpr(E);
1300 E->ParentContext = readDeclAs<DeclContext>();
1301 E->BuiltinLoc = readSourceLocation();
1302 E->RParenLoc = readSourceLocation();
1303 E->SourceLocExprBits.Kind =
1304 static_cast<SourceLocExpr::IdentKind>(Record.readInt());
1305}
1306
1307void ASTStmtReader::VisitAddrLabelExpr(AddrLabelExpr *E) {
1308 VisitExpr(E);
1309 E->setAmpAmpLoc(readSourceLocation());
1310 E->setLabelLoc(readSourceLocation());
1311 E->setLabel(readDeclAs<LabelDecl>());
1312}
1313
1314void ASTStmtReader::VisitStmtExpr(StmtExpr *E) {
1315 VisitExpr(E);
1316 E->setLParenLoc(readSourceLocation());
1317 E->setRParenLoc(readSourceLocation());
1318 E->setSubStmt(cast_or_null<CompoundStmt>(Record.readSubStmt()));
1319 E->StmtExprBits.TemplateDepth = Record.readInt();
1320}
1321
1322void ASTStmtReader::VisitChooseExpr(ChooseExpr *E) {
1323 VisitExpr(E);
1324 E->setCond(Record.readSubExpr());
1325 E->setLHS(Record.readSubExpr());
1326 E->setRHS(Record.readSubExpr());
1327 E->setBuiltinLoc(readSourceLocation());
1328 E->setRParenLoc(readSourceLocation());
1329 E->setIsConditionTrue(Record.readInt());
1330}
1331
1332void ASTStmtReader::VisitGNUNullExpr(GNUNullExpr *E) {
1333 VisitExpr(E);
1334 E->setTokenLocation(readSourceLocation());
1335}
1336
1337void ASTStmtReader::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
1338 VisitExpr(E);
1339 SmallVector<Expr *, 16> Exprs;
1340 unsigned NumExprs = Record.readInt();
1341 while (NumExprs--)
1342 Exprs.push_back(Record.readSubExpr());
1343 E->setExprs(Record.getContext(), Exprs);
1344 E->setBuiltinLoc(readSourceLocation());
1345 E->setRParenLoc(readSourceLocation());
1346}
1347
1348void ASTStmtReader::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1349 VisitExpr(E);
1350 E->BuiltinLoc = readSourceLocation();
1351 E->RParenLoc = readSourceLocation();
1352 E->TInfo = readTypeSourceInfo();
1353 E->SrcExpr = Record.readSubExpr();
1354}
1355
1356void ASTStmtReader::VisitBlockExpr(BlockExpr *E) {
1357 VisitExpr(E);
1358 E->setBlockDecl(readDeclAs<BlockDecl>());
1359}
1360
1361void ASTStmtReader::VisitGenericSelectionExpr(GenericSelectionExpr *E) {
1362 VisitExpr(E);
1363
1364 unsigned NumAssocs = Record.readInt();
1365 assert(NumAssocs == E->getNumAssocs() && "Wrong NumAssocs!")((void)0);
1366 E->ResultIndex = Record.readInt();
1367 E->GenericSelectionExprBits.GenericLoc = readSourceLocation();
1368 E->DefaultLoc = readSourceLocation();
1369 E->RParenLoc = readSourceLocation();
1370
1371 Stmt **Stmts = E->getTrailingObjects<Stmt *>();
1372 // Add 1 to account for the controlling expression which is the first
1373 // expression in the trailing array of Stmt *. This is not needed for
1374 // the trailing array of TypeSourceInfo *.
1375 for (unsigned I = 0, N = NumAssocs + 1; I < N; ++I)
1376 Stmts[I] = Record.readSubExpr();
1377
1378 TypeSourceInfo **TSIs = E->getTrailingObjects<TypeSourceInfo *>();
1379 for (unsigned I = 0, N = NumAssocs; I < N; ++I)
1380 TSIs[I] = readTypeSourceInfo();
1381}
1382
1383void ASTStmtReader::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
1384 VisitExpr(E);
1385 unsigned numSemanticExprs = Record.readInt();
1386 assert(numSemanticExprs + 1 == E->PseudoObjectExprBits.NumSubExprs)((void)0);
1387 E->PseudoObjectExprBits.ResultIndex = Record.readInt();
1388
1389 // Read the syntactic expression.
1390 E->getSubExprsBuffer()[0] = Record.readSubExpr();
1391
1392 // Read all the semantic expressions.
1393 for (unsigned i = 0; i != numSemanticExprs; ++i) {
1394 Expr *subExpr = Record.readSubExpr();
1395 E->getSubExprsBuffer()[i+1] = subExpr;
1396 }
1397}
1398
1399void ASTStmtReader::VisitAtomicExpr(AtomicExpr *E) {
1400 VisitExpr(E);
1401 E->Op = AtomicExpr::AtomicOp(Record.readInt());
1402 E->NumSubExprs = AtomicExpr::getNumSubExprs(E->Op);
1403 for (unsigned I = 0; I != E->NumSubExprs; ++I)
1404 E->SubExprs[I] = Record.readSubExpr();
1405 E->BuiltinLoc = readSourceLocation();
1406 E->RParenLoc = readSourceLocation();
1407}
1408
1409//===----------------------------------------------------------------------===//
1410// Objective-C Expressions and Statements
1411
1412void ASTStmtReader::VisitObjCStringLiteral(ObjCStringLiteral *E) {
1413 VisitExpr(E);
1414 E->setString(cast<StringLiteral>(Record.readSubStmt()));
1415 E->setAtLoc(readSourceLocation());
1416}
1417
1418void ASTStmtReader::VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
1419 VisitExpr(E);
1420 // could be one of several IntegerLiteral, FloatLiteral, etc.
1421 E->SubExpr = Record.readSubStmt();
1422 E->BoxingMethod = readDeclAs<ObjCMethodDecl>();
1423 E->Range = readSourceRange();
1424}
1425
1426void ASTStmtReader::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
1427 VisitExpr(E);
1428 unsigned NumElements = Record.readInt();
1429 assert(NumElements == E->getNumElements() && "Wrong number of elements")((void)0);
1430 Expr **Elements = E->getElements();
1431 for (unsigned I = 0, N = NumElements; I != N; ++I)
1432 Elements[I] = Record.readSubExpr();
1433 E->ArrayWithObjectsMethod = readDeclAs<ObjCMethodDecl>();
1434 E->Range = readSourceRange();
1435}
1436
1437void ASTStmtReader::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
1438 VisitExpr(E);
1439 unsigned NumElements = Record.readInt();
1440 assert(NumElements == E->getNumElements() && "Wrong number of elements")((void)0);
1441 bool HasPackExpansions = Record.readInt();
1442 assert(HasPackExpansions == E->HasPackExpansions &&"Pack expansion mismatch")((void)0);
1443 auto *KeyValues =
1444 E->getTrailingObjects<ObjCDictionaryLiteral::KeyValuePair>();
1445 auto *Expansions =
1446 E->getTrailingObjects<ObjCDictionaryLiteral::ExpansionData>();
1447 for (unsigned I = 0; I != NumElements; ++I) {
1448 KeyValues[I].Key = Record.readSubExpr();
1449 KeyValues[I].Value = Record.readSubExpr();
1450 if (HasPackExpansions) {
1451 Expansions[I].EllipsisLoc = readSourceLocation();
1452 Expansions[I].NumExpansionsPlusOne = Record.readInt();
1453 }
1454 }
1455 E->DictWithObjectsMethod = readDeclAs<ObjCMethodDecl>();
1456 E->Range = readSourceRange();
1457}
1458
1459void ASTStmtReader::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1460 VisitExpr(E);
1461 E->setEncodedTypeSourceInfo(readTypeSourceInfo());
1462 E->setAtLoc(readSourceLocation());
1463 E->setRParenLoc(readSourceLocation());
1464}
1465
1466void ASTStmtReader::VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
1467 VisitExpr(E);
1468 E->setSelector(Record.readSelector());
1469 E->setAtLoc(readSourceLocation());
1470 E->setRParenLoc(readSourceLocation());
1471}
1472
1473void ASTStmtReader::VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
1474 VisitExpr(E);
1475 E->setProtocol(readDeclAs<ObjCProtocolDecl>());
1476 E->setAtLoc(readSourceLocation());
1477 E->ProtoLoc = readSourceLocation();
1478 E->setRParenLoc(readSourceLocation());
1479}
1480
1481void ASTStmtReader::VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
1482 VisitExpr(E);
1483 E->setDecl(readDeclAs<ObjCIvarDecl>());
1484 E->setLocation(readSourceLocation());
1485 E->setOpLoc(readSourceLocation());
1486 E->setBase(Record.readSubExpr());
1487 E->setIsArrow(Record.readInt());
1488 E->setIsFreeIvar(Record.readInt());
1489}
1490
1491void ASTStmtReader::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
1492 VisitExpr(E);
1493 unsigned MethodRefFlags = Record.readInt();
1494 bool Implicit = Record.readInt() != 0;
1495 if (Implicit) {
1496 auto *Getter = readDeclAs<ObjCMethodDecl>();
1497 auto *Setter = readDeclAs<ObjCMethodDecl>();
1498 E->setImplicitProperty(Getter, Setter, MethodRefFlags);
1499 } else {
1500 E->setExplicitProperty(readDeclAs<ObjCPropertyDecl>(), MethodRefFlags);
1501 }
1502 E->setLocation(readSourceLocation());
1503 E->setReceiverLocation(readSourceLocation());
1504 switch (Record.readInt()) {
1505 case 0:
1506 E->setBase(Record.readSubExpr());
1507 break;
1508 case 1:
1509 E->setSuperReceiver(Record.readType());
1510 break;
1511 case 2:
1512 E->setClassReceiver(readDeclAs<ObjCInterfaceDecl>());
1513 break;
1514 }
1515}
1516
1517void ASTStmtReader::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
1518 VisitExpr(E);
1519 E->setRBracket(readSourceLocation());
1520 E->setBaseExpr(Record.readSubExpr());
1521 E->setKeyExpr(Record.readSubExpr());
1522 E->GetAtIndexMethodDecl = readDeclAs<ObjCMethodDecl>();
1523 E->SetAtIndexMethodDecl = readDeclAs<ObjCMethodDecl>();
1524}
1525
1526void ASTStmtReader::VisitObjCMessageExpr(ObjCMessageExpr *E) {
1527 VisitExpr(E);
1528 assert(Record.peekInt() == E->getNumArgs())((void)0);
1529 Record.skipInts(1);
1530 unsigned NumStoredSelLocs = Record.readInt();
1531 E->SelLocsKind = Record.readInt();
1532 E->setDelegateInitCall(Record.readInt());
1533 E->IsImplicit = Record.readInt();
1534 auto Kind = static_cast<ObjCMessageExpr::ReceiverKind>(Record.readInt());
1535 switch (Kind) {
1536 case ObjCMessageExpr::Instance:
1537 E->setInstanceReceiver(Record.readSubExpr());
1538 break;
1539
1540 case ObjCMessageExpr::Class:
1541 E->setClassReceiver(readTypeSourceInfo());
1542 break;
1543
1544 case ObjCMessageExpr::SuperClass:
1545 case ObjCMessageExpr::SuperInstance: {
1546 QualType T = Record.readType();
1547 SourceLocation SuperLoc = readSourceLocation();
1548 E->setSuper(SuperLoc, T, Kind == ObjCMessageExpr::SuperInstance);
1549 break;
1550 }
1551 }
1552
1553 assert(Kind == E->getReceiverKind())((void)0);
1554
1555 if (Record.readInt())
1556 E->setMethodDecl(readDeclAs<ObjCMethodDecl>());
1557 else
1558 E->setSelector(Record.readSelector());
1559
1560 E->LBracLoc = readSourceLocation();
1561 E->RBracLoc = readSourceLocation();
1562
1563 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
1564 E->setArg(I, Record.readSubExpr());
1565
1566 SourceLocation *Locs = E->getStoredSelLocs();
1567 for (unsigned I = 0; I != NumStoredSelLocs; ++I)
1568 Locs[I] = readSourceLocation();
1569}
1570
1571void ASTStmtReader::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
1572 VisitStmt(S);
1573 S->setElement(Record.readSubStmt());
1574 S->setCollection(Record.readSubExpr());
1575 S->setBody(Record.readSubStmt());
1576 S->setForLoc(readSourceLocation());
1577 S->setRParenLoc(readSourceLocation());
1578}
1579
1580void ASTStmtReader::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
1581 VisitStmt(S);
1582 S->setCatchBody(Record.readSubStmt());
1583 S->setCatchParamDecl(readDeclAs<VarDecl>());
1584 S->setAtCatchLoc(readSourceLocation());
1585 S->setRParenLoc(readSourceLocation());
1586}
1587
1588void ASTStmtReader::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
1589 VisitStmt(S);
1590 S->setFinallyBody(Record.readSubStmt());
1591 S->setAtFinallyLoc(readSourceLocation());
1592}
1593
1594void ASTStmtReader::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1595 VisitStmt(S); // FIXME: no test coverage.
1596 S->setSubStmt(Record.readSubStmt());
1597 S->setAtLoc(readSourceLocation());
1598}
1599
1600void ASTStmtReader::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
1601 VisitStmt(S);
1602 assert(Record.peekInt() == S->getNumCatchStmts())((void)0);
1603 Record.skipInts(1);
1604 bool HasFinally = Record.readInt();
1605 S->setTryBody(Record.readSubStmt());
1606 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I)
1607 S->setCatchStmt(I, cast_or_null<ObjCAtCatchStmt>(Record.readSubStmt()));
1608
1609 if (HasFinally)
1610 S->setFinallyStmt(Record.readSubStmt());
1611 S->setAtTryLoc(readSourceLocation());
1612}
1613
1614void ASTStmtReader::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1615 VisitStmt(S); // FIXME: no test coverage.
1616 S->setSynchExpr(Record.readSubStmt());
1617 S->setSynchBody(Record.readSubStmt());
1618 S->setAtSynchronizedLoc(readSourceLocation());
1619}
1620
1621void ASTStmtReader::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
1622 VisitStmt(S); // FIXME: no test coverage.
1623 S->setThrowExpr(Record.readSubStmt());
1624 S->setThrowLoc(readSourceLocation());
1625}
1626
1627void ASTStmtReader::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
1628 VisitExpr(E);
1629 E->setValue(Record.readInt());
1630 E->setLocation(readSourceLocation());
1631}
1632
1633void ASTStmtReader::VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
1634 VisitExpr(E);
1635 SourceRange R = Record.readSourceRange();
1636 E->AtLoc = R.getBegin();
1637 E->RParen = R.getEnd();
1638 E->VersionToCheck = Record.readVersionTuple();
1639}
1640
1641//===----------------------------------------------------------------------===//
1642// C++ Expressions and Statements
1643//===----------------------------------------------------------------------===//
1644
1645void ASTStmtReader::VisitCXXCatchStmt(CXXCatchStmt *S) {
1646 VisitStmt(S);
1647 S->CatchLoc = readSourceLocation();
1648 S->ExceptionDecl = readDeclAs<VarDecl>();
1649 S->HandlerBlock = Record.readSubStmt();
1650}
1651
1652void ASTStmtReader::VisitCXXTryStmt(CXXTryStmt *S) {
1653 VisitStmt(S);
1654 assert(Record.peekInt() == S->getNumHandlers() && "NumStmtFields is wrong ?")((void)0);
1655 Record.skipInts(1);
1656 S->TryLoc = readSourceLocation();
1657 S->getStmts()[0] = Record.readSubStmt();
1658 for (unsigned i = 0, e = S->getNumHandlers(); i != e; ++i)
1659 S->getStmts()[i + 1] = Record.readSubStmt();
1660}
1661
1662void ASTStmtReader::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
1663 VisitStmt(S);
1664 S->ForLoc = readSourceLocation();
1665 S->CoawaitLoc = readSourceLocation();
1666 S->ColonLoc = readSourceLocation();
1667 S->RParenLoc = readSourceLocation();
1668 S->setInit(Record.readSubStmt());
1669 S->setRangeStmt(Record.readSubStmt());
1670 S->setBeginStmt(Record.readSubStmt());
1671 S->setEndStmt(Record.readSubStmt());
1672 S->setCond(Record.readSubExpr());
1673 S->setInc(Record.readSubExpr());
1674 S->setLoopVarStmt(Record.readSubStmt());
1675 S->setBody(Record.readSubStmt());
1676}
1677
1678void ASTStmtReader::VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1679 VisitStmt(S);
1680 S->KeywordLoc = readSourceLocation();
1681 S->IsIfExists = Record.readInt();
1682 S->QualifierLoc = Record.readNestedNameSpecifierLoc();
1683 S->NameInfo = Record.readDeclarationNameInfo();
1684 S->SubStmt = Record.readSubStmt();
1685}
1686
1687void ASTStmtReader::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1688 VisitCallExpr(E);
1689 E->CXXOperatorCallExprBits.OperatorKind = Record.readInt();
1690 E->Range = Record.readSourceRange();
1691}
1692
1693void ASTStmtReader::VisitCXXRewrittenBinaryOperator(
1694 CXXRewrittenBinaryOperator *E) {
1695 VisitExpr(E);
1696 E->CXXRewrittenBinaryOperatorBits.IsReversed = Record.readInt();
1697 E->SemanticForm = Record.readSubExpr();
1698}
1699
1700void ASTStmtReader::VisitCXXConstructExpr(CXXConstructExpr *E) {
1701 VisitExpr(E);
1702
1703 unsigned NumArgs = Record.readInt();
1704 assert((NumArgs == E->getNumArgs()) && "Wrong NumArgs!")((void)0);
1705
1706 E->CXXConstructExprBits.Elidable = Record.readInt();
1707 E->CXXConstructExprBits.HadMultipleCandidates = Record.readInt();
1708 E->CXXConstructExprBits.ListInitialization = Record.readInt();
1709 E->CXXConstructExprBits.StdInitListInitialization = Record.readInt();
1710 E->CXXConstructExprBits.ZeroInitialization = Record.readInt();
1711 E->CXXConstructExprBits.ConstructionKind = Record.readInt();
1712 E->CXXConstructExprBits.Loc = readSourceLocation();
1713 E->Constructor = readDeclAs<CXXConstructorDecl>();
1714 E->ParenOrBraceRange = readSourceRange();
1715
1716 for (unsigned I = 0; I != NumArgs; ++I)
1717 E->setArg(I, Record.readSubExpr());
1718}
1719
1720void ASTStmtReader::VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E) {
1721 VisitExpr(E);
1722 E->Constructor = readDeclAs<CXXConstructorDecl>();
1723 E->Loc = readSourceLocation();
1724 E->ConstructsVirtualBase = Record.readInt();
1725 E->InheritedFromVirtualBase = Record.readInt();
1726}
1727
1728void ASTStmtReader::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1729 VisitCXXConstructExpr(E);
1730 E->TSI = readTypeSourceInfo();
1731}
1732
1733void ASTStmtReader::VisitLambdaExpr(LambdaExpr *E) {
1734 VisitExpr(E);
1735 unsigned NumCaptures = Record.readInt();
1736 (void)NumCaptures;
1737 assert(NumCaptures == E->LambdaExprBits.NumCaptures)((void)0);
1738 E->IntroducerRange = readSourceRange();
1739 E->LambdaExprBits.CaptureDefault = Record.readInt();
1740 E->CaptureDefaultLoc = readSourceLocation();
1741 E->LambdaExprBits.ExplicitParams = Record.readInt();
1742 E->LambdaExprBits.ExplicitResultType = Record.readInt();
1743 E->ClosingBrace = readSourceLocation();
1744
1745 // Read capture initializers.
1746 for (LambdaExpr::capture_init_iterator C = E->capture_init_begin(),
1747 CEnd = E->capture_init_end();
1748 C != CEnd; ++C)
1749 *C = Record.readSubExpr();
1750
1751 // The body will be lazily deserialized when needed from the call operator
1752 // declaration.
1753}
1754
1755void
1756ASTStmtReader::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
1757 VisitExpr(E);
1758 E->SubExpr = Record.readSubExpr();
1759}
1760
1761void ASTStmtReader::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
1762 VisitExplicitCastExpr(E);
1763 SourceRange R = readSourceRange();
1764 E->Loc = R.getBegin();
1765 E->RParenLoc = R.getEnd();
1766 R = readSourceRange();
1767 E->AngleBrackets = R;
1768}
1769
1770void ASTStmtReader::VisitCXXStaticCastExpr(CXXStaticCastExpr *E) {
1771 return VisitCXXNamedCastExpr(E);
1772}
1773
1774void ASTStmtReader::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
1775 return VisitCXXNamedCastExpr(E);
1776}
1777
1778void ASTStmtReader::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *E) {
1779 return VisitCXXNamedCastExpr(E);
1780}
1781
1782void ASTStmtReader::VisitCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
1783 return VisitCXXNamedCastExpr(E);
1784}
1785
1786void ASTStmtReader::VisitCXXConstCastExpr(CXXConstCastExpr *E) {
1787 return VisitCXXNamedCastExpr(E);
1788}
1789
1790void ASTStmtReader::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E) {
1791 VisitExplicitCastExpr(E);
1792 E->setLParenLoc(readSourceLocation());
1793 E->setRParenLoc(readSourceLocation());
1794}
1795
1796void ASTStmtReader::VisitBuiltinBitCastExpr(BuiltinBitCastExpr *E) {
1797 VisitExplicitCastExpr(E);
1798 E->KWLoc = readSourceLocation();
1799 E->RParenLoc = readSourceLocation();
1800}
1801
1802void ASTStmtReader::VisitUserDefinedLiteral(UserDefinedLiteral *E) {
1803 VisitCallExpr(E);
1804 E->UDSuffixLoc = readSourceLocation();
1805}
1806
1807void ASTStmtReader::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
1808 VisitExpr(E);
1809 E->setValue(Record.readInt());
1810 E->setLocation(readSourceLocation());
1811}
1812
1813void ASTStmtReader::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
1814 VisitExpr(E);
1815 E->setLocation(readSourceLocation());
1816}
1817
1818void ASTStmtReader::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1819 VisitExpr(E);
1820 E->setSourceRange(readSourceRange());
1821 if (E->isTypeOperand())
1822 E->Operand = readTypeSourceInfo();
1823 else
1824 E->Operand = Record.readSubExpr();
1825}
1826
1827void ASTStmtReader::VisitCXXThisExpr(CXXThisExpr *E) {
1828 VisitExpr(E);
1829 E->setLocation(readSourceLocation());
1830 E->setImplicit(Record.readInt());
1831}
1832
1833void ASTStmtReader::VisitCXXThrowExpr(CXXThrowExpr *E) {
1834 VisitExpr(E);
1835 E->CXXThrowExprBits.ThrowLoc = readSourceLocation();
1836 E->Operand = Record.readSubExpr();
1837 E->CXXThrowExprBits.IsThrownVariableInScope = Record.readInt();
1838}
1839
1840void ASTStmtReader::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
1841 VisitExpr(E);
1842 E->Param = readDeclAs<ParmVarDecl>();
1843 E->UsedContext = readDeclAs<DeclContext>();
1844 E->CXXDefaultArgExprBits.Loc = readSourceLocation();
1845}
1846
1847void ASTStmtReader::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
1848 VisitExpr(E);
1849 E->Field = readDeclAs<FieldDecl>();
1850 E->UsedContext = readDeclAs<DeclContext>();
1851 E->CXXDefaultInitExprBits.Loc = readSourceLocation();
1852}
1853
1854void ASTStmtReader::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1855 VisitExpr(E);
1856 E->setTemporary(Record.readCXXTemporary());
1857 E->setSubExpr(Record.readSubExpr());
1858}
1859
1860void ASTStmtReader::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1861 VisitExpr(E);
1862 E->TypeInfo = readTypeSourceInfo();
1863 E->CXXScalarValueInitExprBits.RParenLoc = readSourceLocation();
1864}
1865
1866void ASTStmtReader::VisitCXXNewExpr(CXXNewExpr *E) {
1867 VisitExpr(E);
1868
1869 bool IsArray = Record.readInt();
1870 bool HasInit = Record.readInt();
1871 unsigned NumPlacementArgs = Record.readInt();
1872 bool IsParenTypeId = Record.readInt();
1873
1874 E->CXXNewExprBits.IsGlobalNew = Record.readInt();
1875 E->CXXNewExprBits.ShouldPassAlignment = Record.readInt();
1876 E->CXXNewExprBits.UsualArrayDeleteWantsSize = Record.readInt();
1877 E->CXXNewExprBits.StoredInitializationStyle = Record.readInt();
1878
1879 assert((IsArray == E->isArray()) && "Wrong IsArray!")((void)0);
1880 assert((HasInit == E->hasInitializer()) && "Wrong HasInit!")((void)0);
1881 assert((NumPlacementArgs == E->getNumPlacementArgs()) &&((void)0)
1882 "Wrong NumPlacementArgs!")((void)0);
1883 assert((IsParenTypeId == E->isParenTypeId()) && "Wrong IsParenTypeId!")((void)0);
1884 (void)IsArray;
1885 (void)HasInit;
1886 (void)NumPlacementArgs;
1887
1888 E->setOperatorNew(readDeclAs<FunctionDecl>());
1889 E->setOperatorDelete(readDeclAs<FunctionDecl>());
1890 E->AllocatedTypeInfo = readTypeSourceInfo();
1891 if (IsParenTypeId)
1892 E->getTrailingObjects<SourceRange>()[0] = readSourceRange();
1893 E->Range = readSourceRange();
1894 E->DirectInitRange = readSourceRange();
1895
1896 // Install all the subexpressions.
1897 for (CXXNewExpr::raw_arg_iterator I = E->raw_arg_begin(),
1898 N = E->raw_arg_end();
1899 I != N; ++I)
1900 *I = Record.readSubStmt();
1901}
1902
1903void ASTStmtReader::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1904 VisitExpr(E);
1905 E->CXXDeleteExprBits.GlobalDelete = Record.readInt();
1906 E->CXXDeleteExprBits.ArrayForm = Record.readInt();
1907 E->CXXDeleteExprBits.ArrayFormAsWritten = Record.readInt();
1908 E->CXXDeleteExprBits.UsualArrayDeleteWantsSize = Record.readInt();
1909 E->OperatorDelete = readDeclAs<FunctionDecl>();
1910 E->Argument = Record.readSubExpr();
1911 E->CXXDeleteExprBits.Loc = readSourceLocation();
1912}
1913
1914void ASTStmtReader::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1915 VisitExpr(E);
1916
1917 E->Base = Record.readSubExpr();
1918 E->IsArrow = Record.readInt();
1919 E->OperatorLoc = readSourceLocation();
1920 E->QualifierLoc = Record.readNestedNameSpecifierLoc();
1921 E->ScopeType = readTypeSourceInfo();
1922 E->ColonColonLoc = readSourceLocation();
1923 E->TildeLoc = readSourceLocation();
1924
1925 IdentifierInfo *II = Record.readIdentifier();
1926 if (II)
1927 E->setDestroyedType(II, readSourceLocation());
1928 else
1929 E->setDestroyedType(readTypeSourceInfo());
1930}
1931
1932void ASTStmtReader::VisitExprWithCleanups(ExprWithCleanups *E) {
1933 VisitExpr(E);
1934
1935 unsigned NumObjects = Record.readInt();
1936 assert(NumObjects == E->getNumObjects())((void)0);
1937 for (unsigned i = 0; i != NumObjects; ++i) {
1938 unsigned CleanupKind = Record.readInt();
1939 ExprWithCleanups::CleanupObject Obj;
1940 if (CleanupKind == COK_Block)
1941 Obj = readDeclAs<BlockDecl>();
1942 else if (CleanupKind == COK_CompoundLiteral)
1943 Obj = cast<CompoundLiteralExpr>(Record.readSubExpr());
1944 else
1945 llvm_unreachable("unexpected cleanup object type")__builtin_unreachable();
1946 E->getTrailingObjects<ExprWithCleanups::CleanupObject>()[i] = Obj;
1947 }
1948
1949 E->ExprWithCleanupsBits.CleanupsHaveSideEffects = Record.readInt();
1950 E->SubExpr = Record.readSubExpr();
1951}
1952
1953void ASTStmtReader::VisitCXXDependentScopeMemberExpr(
1954 CXXDependentScopeMemberExpr *E) {
1955 VisitExpr(E);
1956
1957 bool HasTemplateKWAndArgsInfo = Record.readInt();
1958 unsigned NumTemplateArgs = Record.readInt();
1959 bool HasFirstQualifierFoundInScope = Record.readInt();
1960
1961 assert((HasTemplateKWAndArgsInfo == E->hasTemplateKWAndArgsInfo()) &&((void)0)
1962 "Wrong HasTemplateKWAndArgsInfo!")((void)0);
1963 assert(((void)0)
1964 (HasFirstQualifierFoundInScope == E->hasFirstQualifierFoundInScope()) &&((void)0)
1965 "Wrong HasFirstQualifierFoundInScope!")((void)0);
1966
1967 if (HasTemplateKWAndArgsInfo)
1968 ReadTemplateKWAndArgsInfo(
1969 *E->getTrailingObjects<ASTTemplateKWAndArgsInfo>(),
1970 E->getTrailingObjects<TemplateArgumentLoc>(), NumTemplateArgs);
1971
1972 assert((NumTemplateArgs == E->getNumTemplateArgs()) &&((void)0)
1973 "Wrong NumTemplateArgs!")((void)0);
1974
1975 E->CXXDependentScopeMemberExprBits.IsArrow = Record.readInt();
1976 E->CXXDependentScopeMemberExprBits.OperatorLoc = readSourceLocation();
1977 E->BaseType = Record.readType();
1978 E->QualifierLoc = Record.readNestedNameSpecifierLoc();
1979 E->Base = Record.readSubExpr();
1980
1981 if (HasFirstQualifierFoundInScope)
1982 *E->getTrailingObjects<NamedDecl *>() = readDeclAs<NamedDecl>();
1983
1984 E->MemberNameInfo = Record.readDeclarationNameInfo();
1985}
1986
1987void
1988ASTStmtReader::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1989 VisitExpr(E);
1990
1991 if (Record.readInt()) // HasTemplateKWAndArgsInfo
1992 ReadTemplateKWAndArgsInfo(
1993 *E->getTrailingObjects<ASTTemplateKWAndArgsInfo>(),
1994 E->getTrailingObjects<TemplateArgumentLoc>(),
1995 /*NumTemplateArgs=*/Record.readInt());
1996
1997 E->QualifierLoc = Record.readNestedNameSpecifierLoc();
1998 E->NameInfo = Record.readDeclarationNameInfo();
1999}
2000
2001void
2002ASTStmtReader::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E) {
2003 VisitExpr(E);
2004 assert(Record.peekInt() == E->getNumArgs() &&((void)0)
2005 "Read wrong record during creation ?")((void)0);
2006 Record.skipInts(1);
2007 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
2008 E->setArg(I, Record.readSubExpr());
2009 E->TSI = readTypeSourceInfo();
2010 E->setLParenLoc(readSourceLocation());
2011 E->setRParenLoc(readSourceLocation());
2012}
2013
2014void ASTStmtReader::VisitOverloadExpr(OverloadExpr *E) {
2015 VisitExpr(E);
2016
2017 unsigned NumResults = Record.readInt();
2018 bool HasTemplateKWAndArgsInfo = Record.readInt();
2019 assert((E->getNumDecls() == NumResults) && "Wrong NumResults!")((void)0);
2020 assert((E->hasTemplateKWAndArgsInfo() == HasTemplateKWAndArgsInfo) &&((void)0)
2021 "Wrong HasTemplateKWAndArgsInfo!")((void)0);
2022
2023 if (HasTemplateKWAndArgsInfo) {
2024 unsigned NumTemplateArgs = Record.readInt();
2025 ReadTemplateKWAndArgsInfo(*E->getTrailingASTTemplateKWAndArgsInfo(),
2026 E->getTrailingTemplateArgumentLoc(),
2027 NumTemplateArgs);
2028 assert((E->getNumTemplateArgs() == NumTemplateArgs) &&((void)0)
2029 "Wrong NumTemplateArgs!")((void)0);
2030 }
2031
2032 UnresolvedSet<8> Decls;
2033 for (unsigned I = 0; I != NumResults; ++I) {
2034 auto *D = readDeclAs<NamedDecl>();
2035 auto AS = (AccessSpecifier)Record.readInt();
2036 Decls.addDecl(D, AS);
2037 }
2038
2039 DeclAccessPair *Results = E->getTrailingResults();
2040 UnresolvedSetIterator Iter = Decls.begin();
2041 for (unsigned I = 0; I != NumResults; ++I) {
2042 Results[I] = (Iter + I).getPair();
2043 }
2044
2045 E->NameInfo = Record.readDeclarationNameInfo();
2046 E->QualifierLoc = Record.readNestedNameSpecifierLoc();
2047}
2048
2049void ASTStmtReader::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
2050 VisitOverloadExpr(E);
2051 E->UnresolvedMemberExprBits.IsArrow = Record.readInt();
2052 E->UnresolvedMemberExprBits.HasUnresolvedUsing = Record.readInt();
2053 E->Base = Record.readSubExpr();
2054 E->BaseType = Record.readType();
2055 E->OperatorLoc = readSourceLocation();
2056}
2057
2058void ASTStmtReader::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
2059 VisitOverloadExpr(E);
2060 E->UnresolvedLookupExprBits.RequiresADL = Record.readInt();
2061 E->UnresolvedLookupExprBits.Overloaded = Record.readInt();
2062 E->NamingClass = readDeclAs<CXXRecordDecl>();
2063}
2064
2065void ASTStmtReader::VisitTypeTraitExpr(TypeTraitExpr *E) {
2066 VisitExpr(E);
2067 E->TypeTraitExprBits.NumArgs = Record.readInt();
2068 E->TypeTraitExprBits.Kind = Record.readInt();
2069 E->TypeTraitExprBits.Value = Record.readInt();
2070 SourceRange Range = readSourceRange();
2071 E->Loc = Range.getBegin();
2072 E->RParenLoc = Range.getEnd();
2073
2074 auto **Args = E->getTrailingObjects<TypeSourceInfo *>();
2075 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
2076 Args[I] = readTypeSourceInfo();
2077}
2078
2079void ASTStmtReader::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2080 VisitExpr(E);
2081 E->ATT = (ArrayTypeTrait)Record.readInt();
2082 E->Value = (unsigned int)Record.readInt();
2083 SourceRange Range = readSourceRange();
2084 E->Loc = Range.getBegin();
2085 E->RParen = Range.getEnd();
2086 E->QueriedType = readTypeSourceInfo();
2087 E->Dimension = Record.readSubExpr();
2088}
2089
2090void ASTStmtReader::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2091 VisitExpr(E);
2092 E->ET = (ExpressionTrait)Record.readInt();
2093 E->Value = (bool)Record.readInt();
2094 SourceRange Range = readSourceRange();
2095 E->QueriedExpression = Record.readSubExpr();
2096 E->Loc = Range.getBegin();
2097 E->RParen = Range.getEnd();
2098}
2099
2100void ASTStmtReader::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
2101 VisitExpr(E);
2102 E->CXXNoexceptExprBits.Value = Record.readInt();
2103 E->Range = readSourceRange();
2104 E->Operand = Record.readSubExpr();
2105}
2106
2107void ASTStmtReader::VisitPackExpansionExpr(PackExpansionExpr *E) {
2108 VisitExpr(E);
2109 E->EllipsisLoc = readSourceLocation();
2110 E->NumExpansions = Record.readInt();
2111 E->Pattern = Record.readSubExpr();
2112}
2113
2114void ASTStmtReader::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2115 VisitExpr(E);
2116 unsigned NumPartialArgs = Record.readInt();
2117 E->OperatorLoc = readSourceLocation();
2118 E->PackLoc = readSourceLocation();
2119 E->RParenLoc = readSourceLocation();
2120 E->Pack = Record.readDeclAs<NamedDecl>();
2121 if (E->isPartiallySubstituted()) {
2122 assert(E->Length == NumPartialArgs)((void)0);
2123 for (auto *I = E->getTrailingObjects<TemplateArgument>(),
2124 *E = I + NumPartialArgs;
2125 I != E; ++I)
2126 new (I) TemplateArgument(Record.readTemplateArgument());
2127 } else if (!E->isValueDependent()) {
2128 E->Length = Record.readInt();
2129 }
2130}
2131
2132void ASTStmtReader::VisitSubstNonTypeTemplateParmExpr(
2133 SubstNonTypeTemplateParmExpr *E) {
2134 VisitExpr(E);
2135 E->ParamAndRef.setPointer(readDeclAs<NonTypeTemplateParmDecl>());
2136 E->ParamAndRef.setInt(Record.readInt());
2137 E->SubstNonTypeTemplateParmExprBits.NameLoc = readSourceLocation();
2138 E->Replacement = Record.readSubExpr();
2139}
2140
2141void ASTStmtReader::VisitSubstNonTypeTemplateParmPackExpr(
2142 SubstNonTypeTemplateParmPackExpr *E) {
2143 VisitExpr(E);
2144 E->Param = readDeclAs<NonTypeTemplateParmDecl>();
2145 TemplateArgument ArgPack = Record.readTemplateArgument();
2146 if (ArgPack.getKind() != TemplateArgument::Pack)
2147 return;
2148
2149 E->Arguments = ArgPack.pack_begin();
2150 E->NumArguments = ArgPack.pack_size();
2151 E->NameLoc = readSourceLocation();
2152}
2153
2154void ASTStmtReader::VisitFunctionParmPackExpr(FunctionParmPackExpr *E) {
2155 VisitExpr(E);
2156 E->NumParameters = Record.readInt();
2157 E->ParamPack = readDeclAs<ParmVarDecl>();
2158 E->NameLoc = readSourceLocation();
2159 auto **Parms = E->getTrailingObjects<VarDecl *>();
2160 for (unsigned i = 0, n = E->NumParameters; i != n; ++i)
2161 Parms[i] = readDeclAs<VarDecl>();
2162}
2163
2164void ASTStmtReader::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
2165 VisitExpr(E);
2166 bool HasMaterialzedDecl = Record.readInt();
2167 if (HasMaterialzedDecl)
2168 E->State = cast<LifetimeExtendedTemporaryDecl>(Record.readDecl());
2169 else
2170 E->State = Record.readSubExpr();
2171}
2172
2173void ASTStmtReader::VisitCXXFoldExpr(CXXFoldExpr *E) {
2174 VisitExpr(E);
2175 E->LParenLoc = readSourceLocation();
2176 E->EllipsisLoc = readSourceLocation();
2177 E->RParenLoc = readSourceLocation();
2178 E->NumExpansions = Record.readInt();
2179 E->SubExprs[0] = Record.readSubExpr();
2180 E->SubExprs[1] = Record.readSubExpr();
2181 E->SubExprs[2] = Record.readSubExpr();
2182 E->Opcode = (BinaryOperatorKind)Record.readInt();
2183}
2184
2185void ASTStmtReader::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2186 VisitExpr(E);
2187 E->SourceExpr = Record.readSubExpr();
2188 E->OpaqueValueExprBits.Loc = readSourceLocation();
2189 E->setIsUnique(Record.readInt());
2190}
2191
2192void ASTStmtReader::VisitTypoExpr(TypoExpr *E) {
2193 llvm_unreachable("Cannot read TypoExpr nodes")__builtin_unreachable();
2194}
2195
2196void ASTStmtReader::VisitRecoveryExpr(RecoveryExpr *E) {
2197 VisitExpr(E);
2198 unsigned NumArgs = Record.readInt();
2199 E->BeginLoc = readSourceLocation();
2200 E->EndLoc = readSourceLocation();
2201 assert((NumArgs + 0LL ==((void)0)
2202 std::distance(E->children().begin(), E->children().end())) &&((void)0)
2203 "Wrong NumArgs!")((void)0);
2204 (void)NumArgs;
2205 for (Stmt *&Child : E->children())
2206 Child = Record.readSubStmt();
2207}
2208
2209//===----------------------------------------------------------------------===//
2210// Microsoft Expressions and Statements
2211//===----------------------------------------------------------------------===//
2212void ASTStmtReader::VisitMSPropertyRefExpr(MSPropertyRefExpr *E) {
2213 VisitExpr(E);
2214 E->IsArrow = (Record.readInt() != 0);
2215 E->BaseExpr = Record.readSubExpr();
2216 E->QualifierLoc = Record.readNestedNameSpecifierLoc();
2217 E->MemberLoc = readSourceLocation();
2218 E->TheDecl = readDeclAs<MSPropertyDecl>();
2219}
2220
2221void ASTStmtReader::VisitMSPropertySubscriptExpr(MSPropertySubscriptExpr *E) {
2222 VisitExpr(E);
2223 E->setBase(Record.readSubExpr());
2224 E->setIdx(Record.readSubExpr());
2225 E->setRBracketLoc(readSourceLocation());
2226}
2227
2228void ASTStmtReader::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
2229 VisitExpr(E);
2230 E->setSourceRange(readSourceRange());
2231 E->Guid = readDeclAs<MSGuidDecl>();
2232 if (E->isTypeOperand())
2233 E->Operand = readTypeSourceInfo();
2234 else
2235 E->Operand = Record.readSubExpr();
2236}
2237
2238void ASTStmtReader::VisitSEHLeaveStmt(SEHLeaveStmt *S) {
2239 VisitStmt(S);
2240 S->setLeaveLoc(readSourceLocation());
2241}
2242
2243void ASTStmtReader::VisitSEHExceptStmt(SEHExceptStmt *S) {
2244 VisitStmt(S);
2245 S->Loc = readSourceLocation();
2246 S->Children[SEHExceptStmt::FILTER_EXPR] = Record.readSubStmt();
2247 S->Children[SEHExceptStmt::BLOCK] = Record.readSubStmt();
2248}
2249
2250void ASTStmtReader::VisitSEHFinallyStmt(SEHFinallyStmt *S) {
2251 VisitStmt(S);
2252 S->Loc = readSourceLocation();
2253 S->Block = Record.readSubStmt();
2254}
2255
2256void ASTStmtReader::VisitSEHTryStmt(SEHTryStmt *S) {
2257 VisitStmt(S);
2258 S->IsCXXTry = Record.readInt();
2259 S->TryLoc = readSourceLocation();
2260 S->Children[SEHTryStmt::TRY] = Record.readSubStmt();
2261 S->Children[SEHTryStmt::HANDLER] = Record.readSubStmt();
2262}
2263
2264//===----------------------------------------------------------------------===//
2265// CUDA Expressions and Statements
2266//===----------------------------------------------------------------------===//
2267
2268void ASTStmtReader::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
2269 VisitCallExpr(E);
2270 E->setPreArg(CUDAKernelCallExpr::CONFIG, Record.readSubExpr());
2271}
2272
2273//===----------------------------------------------------------------------===//
2274// OpenCL Expressions and Statements.
2275//===----------------------------------------------------------------------===//
2276void ASTStmtReader::VisitAsTypeExpr(AsTypeExpr *E) {
2277 VisitExpr(E);
2278 E->BuiltinLoc = readSourceLocation();
2279 E->RParenLoc = readSourceLocation();
2280 E->SrcExpr = Record.readSubExpr();
2281}
2282
2283//===----------------------------------------------------------------------===//
2284// OpenMP Directives.
2285//===----------------------------------------------------------------------===//
2286
2287void ASTStmtReader::VisitOMPCanonicalLoop(OMPCanonicalLoop *S) {
2288 VisitStmt(S);
2289 for (Stmt *&SubStmt : S->SubStmts)
2290 SubStmt = Record.readSubStmt();
2291}
2292
2293void ASTStmtReader::VisitOMPExecutableDirective(OMPExecutableDirective *E) {
2294 Record.readOMPChildren(E->Data);
2295 E->setLocStart(readSourceLocation());
2296 E->setLocEnd(readSourceLocation());
2297}
2298
2299void ASTStmtReader::VisitOMPLoopBasedDirective(OMPLoopBasedDirective *D) {
2300 VisitStmt(D);
2301 // Field CollapsedNum was read in ReadStmtFromStream.
2302 Record.skipInts(1);
2303 VisitOMPExecutableDirective(D);
2304}
2305
2306void ASTStmtReader::VisitOMPLoopDirective(OMPLoopDirective *D) {
2307 VisitOMPLoopBasedDirective(D);
2308}
2309
2310void ASTStmtReader::VisitOMPParallelDirective(OMPParallelDirective *D) {
2311 VisitStmt(D);
2312 VisitOMPExecutableDirective(D);
2313 D->setHasCancel(Record.readBool());
2314}
2315
2316void ASTStmtReader::VisitOMPSimdDirective(OMPSimdDirective *D) {
2317 VisitOMPLoopDirective(D);
2318}
2319
2320void ASTStmtReader::VisitOMPTileDirective(OMPTileDirective *D) {
2321 VisitOMPLoopBasedDirective(D);
2322}
2323
2324void ASTStmtReader::VisitOMPUnrollDirective(OMPUnrollDirective *D) {
2325 VisitOMPLoopBasedDirective(D);
2326}
2327
2328void ASTStmtReader::VisitOMPForDirective(OMPForDirective *D) {
2329 VisitOMPLoopDirective(D);
2330 D->setHasCancel(Record.readBool());
2331}
2332
2333void ASTStmtReader::VisitOMPForSimdDirective(OMPForSimdDirective *D) {
2334 VisitOMPLoopDirective(D);
2335}
2336
2337void ASTStmtReader::VisitOMPSectionsDirective(OMPSectionsDirective *D) {
2338 VisitStmt(D);
2339 VisitOMPExecutableDirective(D);
2340 D->setHasCancel(Record.readBool());
2341}
2342
2343void ASTStmtReader::VisitOMPSectionDirective(OMPSectionDirective *D) {
2344 VisitStmt(D);
2345 VisitOMPExecutableDirective(D);
2346 D->setHasCancel(Record.readBool());
2347}
2348
2349void ASTStmtReader::VisitOMPSingleDirective(OMPSingleDirective *D) {
2350 VisitStmt(D);
2351 VisitOMPExecutableDirective(D);
2352}
2353
2354void ASTStmtReader::VisitOMPMasterDirective(OMPMasterDirective *D) {
2355 VisitStmt(D);
2356 VisitOMPExecutableDirective(D);
2357}
2358
2359void ASTStmtReader::VisitOMPCriticalDirective(OMPCriticalDirective *D) {
2360 VisitStmt(D);
2361 VisitOMPExecutableDirective(D);
2362 D->DirName = Record.readDeclarationNameInfo();
2363}
2364
2365void ASTStmtReader::VisitOMPParallelForDirective(OMPParallelForDirective *D) {
2366 VisitOMPLoopDirective(D);
2367 D->setHasCancel(Record.readBool());
2368}
2369
2370void ASTStmtReader::VisitOMPParallelForSimdDirective(
2371 OMPParallelForSimdDirective *D) {
2372 VisitOMPLoopDirective(D);
2373}
2374
2375void ASTStmtReader::VisitOMPParallelMasterDirective(
2376 OMPParallelMasterDirective *D) {
2377 VisitStmt(D);
2378 VisitOMPExecutableDirective(D);
2379}
2380
2381void ASTStmtReader::VisitOMPParallelSectionsDirective(
2382 OMPParallelSectionsDirective *D) {
2383 VisitStmt(D);
2384 VisitOMPExecutableDirective(D);
2385 D->setHasCancel(Record.readBool());
2386}
2387
2388void ASTStmtReader::VisitOMPTaskDirective(OMPTaskDirective *D) {
2389 VisitStmt(D);
2390 VisitOMPExecutableDirective(D);
2391 D->setHasCancel(Record.readBool());
2392}
2393
2394void ASTStmtReader::VisitOMPTaskyieldDirective(OMPTaskyieldDirective *D) {
2395 VisitStmt(D);
2396 VisitOMPExecutableDirective(D);
2397}
2398
2399void ASTStmtReader::VisitOMPBarrierDirective(OMPBarrierDirective *D) {
2400 VisitStmt(D);
2401 VisitOMPExecutableDirective(D);
2402}
2403
2404void ASTStmtReader::VisitOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
2405 VisitStmt(D);
2406 VisitOMPExecutableDirective(D);
2407}
2408
2409void ASTStmtReader::VisitOMPTaskgroupDirective(OMPTaskgroupDirective *D) {
2410 VisitStmt(D);
2411 VisitOMPExecutableDirective(D);
2412}
2413
2414void ASTStmtReader::VisitOMPFlushDirective(OMPFlushDirective *D) {
2415 VisitStmt(D);
2416 VisitOMPExecutableDirective(D);
2417}
2418
2419void ASTStmtReader::VisitOMPDepobjDirective(OMPDepobjDirective *D) {
2420 VisitStmt(D);
2421 VisitOMPExecutableDirective(D);
2422}
2423
2424void ASTStmtReader::VisitOMPScanDirective(OMPScanDirective *D) {
2425 VisitStmt(D);
2426 VisitOMPExecutableDirective(D);
2427}
2428
2429void ASTStmtReader::VisitOMPOrderedDirective(OMPOrderedDirective *D) {
2430 VisitStmt(D);
2431 VisitOMPExecutableDirective(D);
2432}
2433
2434void ASTStmtReader::VisitOMPAtomicDirective(OMPAtomicDirective *D) {
2435 VisitStmt(D);
2436 VisitOMPExecutableDirective(D);
2437 D->IsXLHSInRHSPart = Record.readBool();
2438 D->IsPostfixUpdate = Record.readBool();
2439}
2440
2441void ASTStmtReader::VisitOMPTargetDirective(OMPTargetDirective *D) {
2442 VisitStmt(D);
2443 VisitOMPExecutableDirective(D);
2444}
2445
2446void ASTStmtReader::VisitOMPTargetDataDirective(OMPTargetDataDirective *D) {
2447 VisitStmt(D);
2448 VisitOMPExecutableDirective(D);
2449}
2450
2451void ASTStmtReader::VisitOMPTargetEnterDataDirective(
2452 OMPTargetEnterDataDirective *D) {
2453 VisitStmt(D);
2454 VisitOMPExecutableDirective(D);
2455}
2456
2457void ASTStmtReader::VisitOMPTargetExitDataDirective(
2458 OMPTargetExitDataDirective *D) {
2459 VisitStmt(D);
2460 VisitOMPExecutableDirective(D);
2461}
2462
2463void ASTStmtReader::VisitOMPTargetParallelDirective(
2464 OMPTargetParallelDirective *D) {
2465 VisitStmt(D);
2466 VisitOMPExecutableDirective(D);
2467 D->setHasCancel(Record.readBool());
2468}
2469
2470void ASTStmtReader::VisitOMPTargetParallelForDirective(
2471 OMPTargetParallelForDirective *D) {
2472 VisitOMPLoopDirective(D);
2473 D->setHasCancel(Record.readBool());
2474}
2475
2476void ASTStmtReader::VisitOMPTeamsDirective(OMPTeamsDirective *D) {
2477 VisitStmt(D);
2478 VisitOMPExecutableDirective(D);
2479}
2480
2481void ASTStmtReader::VisitOMPCancellationPointDirective(
2482 OMPCancellationPointDirective *D) {
2483 VisitStmt(D);
2484 VisitOMPExecutableDirective(D);
2485 D->setCancelRegion(Record.readEnum<OpenMPDirectiveKind>());
2486}
2487
2488void ASTStmtReader::VisitOMPCancelDirective(OMPCancelDirective *D) {
2489 VisitStmt(D);
2490 VisitOMPExecutableDirective(D);
2491 D->setCancelRegion(Record.readEnum<OpenMPDirectiveKind>());
2492}
2493
2494void ASTStmtReader::VisitOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
2495 VisitOMPLoopDirective(D);
2496 D->setHasCancel(Record.readBool());
2497}
2498
2499void ASTStmtReader::VisitOMPTaskLoopSimdDirective(OMPTaskLoopSimdDirective *D) {
2500 VisitOMPLoopDirective(D);
2501}
2502
2503void ASTStmtReader::VisitOMPMasterTaskLoopDirective(
2504 OMPMasterTaskLoopDirective *D) {
2505 VisitOMPLoopDirective(D);
2506 D->setHasCancel(Record.readBool());
2507}
2508
2509void ASTStmtReader::VisitOMPMasterTaskLoopSimdDirective(
2510 OMPMasterTaskLoopSimdDirective *D) {
2511 VisitOMPLoopDirective(D);
2512}
2513
2514void ASTStmtReader::VisitOMPParallelMasterTaskLoopDirective(
2515 OMPParallelMasterTaskLoopDirective *D) {
2516 VisitOMPLoopDirective(D);
2517 D->setHasCancel(Record.readBool());
2518}
2519
2520void ASTStmtReader::VisitOMPParallelMasterTaskLoopSimdDirective(
2521 OMPParallelMasterTaskLoopSimdDirective *D) {
2522 VisitOMPLoopDirective(D);
2523}
2524
2525void ASTStmtReader::VisitOMPDistributeDirective(OMPDistributeDirective *D) {
2526 VisitOMPLoopDirective(D);
2527}
2528
2529void ASTStmtReader::VisitOMPTargetUpdateDirective(OMPTargetUpdateDirective *D) {
2530 VisitStmt(D);
2531 VisitOMPExecutableDirective(D);
2532}
2533
2534void ASTStmtReader::VisitOMPDistributeParallelForDirective(
2535 OMPDistributeParallelForDirective *D) {
2536 VisitOMPLoopDirective(D);
2537 D->setHasCancel(Record.readBool());
2538}
2539
2540void ASTStmtReader::VisitOMPDistributeParallelForSimdDirective(
2541 OMPDistributeParallelForSimdDirective *D) {
2542 VisitOMPLoopDirective(D);
2543}
2544
2545void ASTStmtReader::VisitOMPDistributeSimdDirective(
2546 OMPDistributeSimdDirective *D) {
2547 VisitOMPLoopDirective(D);
2548}
2549
2550void ASTStmtReader::VisitOMPTargetParallelForSimdDirective(
2551 OMPTargetParallelForSimdDirective *D) {
2552 VisitOMPLoopDirective(D);
2553}
2554
2555void ASTStmtReader::VisitOMPTargetSimdDirective(OMPTargetSimdDirective *D) {
2556 VisitOMPLoopDirective(D);
2557}
2558
2559void ASTStmtReader::VisitOMPTeamsDistributeDirective(
2560 OMPTeamsDistributeDirective *D) {
2561 VisitOMPLoopDirective(D);
2562}
2563
2564void ASTStmtReader::VisitOMPTeamsDistributeSimdDirective(
2565 OMPTeamsDistributeSimdDirective *D) {
2566 VisitOMPLoopDirective(D);
2567}
2568
2569void ASTStmtReader::VisitOMPTeamsDistributeParallelForSimdDirective(
2570 OMPTeamsDistributeParallelForSimdDirective *D) {
2571 VisitOMPLoopDirective(D);
2572}
2573
2574void ASTStmtReader::VisitOMPTeamsDistributeParallelForDirective(
2575 OMPTeamsDistributeParallelForDirective *D) {
2576 VisitOMPLoopDirective(D);
2577 D->setHasCancel(Record.readBool());
2578}
2579
2580void ASTStmtReader::VisitOMPTargetTeamsDirective(OMPTargetTeamsDirective *D) {
2581 VisitStmt(D);
2582 VisitOMPExecutableDirective(D);
2583}
2584
2585void ASTStmtReader::VisitOMPTargetTeamsDistributeDirective(
2586 OMPTargetTeamsDistributeDirective *D) {
2587 VisitOMPLoopDirective(D);
2588}
2589
2590void ASTStmtReader::VisitOMPTargetTeamsDistributeParallelForDirective(
2591 OMPTargetTeamsDistributeParallelForDirective *D) {
2592 VisitOMPLoopDirective(D);
2593 D->setHasCancel(Record.readBool());
2594}
2595
2596void ASTStmtReader::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2597 OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2598 VisitOMPLoopDirective(D);
2599}
2600
2601void ASTStmtReader::VisitOMPTargetTeamsDistributeSimdDirective(
2602 OMPTargetTeamsDistributeSimdDirective *D) {
2603 VisitOMPLoopDirective(D);
2604}
2605
2606void ASTStmtReader::VisitOMPInteropDirective(OMPInteropDirective *D) {
2607 VisitStmt(D);
2608 VisitOMPExecutableDirective(D);
2609}
2610
2611void ASTStmtReader::VisitOMPDispatchDirective(OMPDispatchDirective *D) {
2612 VisitStmt(D);
2613 VisitOMPExecutableDirective(D);
2614 D->setTargetCallLoc(Record.readSourceLocation());
2615}
2616
2617void ASTStmtReader::VisitOMPMaskedDirective(OMPMaskedDirective *D) {
2618 VisitStmt(D);
2619 VisitOMPExecutableDirective(D);
2620}
2621
2622//===----------------------------------------------------------------------===//
2623// ASTReader Implementation
2624//===----------------------------------------------------------------------===//
2625
2626Stmt *ASTReader::ReadStmt(ModuleFile &F) {
2627 switch (ReadingKind) {
2628 case Read_None:
2629 llvm_unreachable("should not call this when not reading anything")__builtin_unreachable();
2630 case Read_Decl:
2631 case Read_Type:
2632 return ReadStmtFromStream(F);
2633 case Read_Stmt:
2634 return ReadSubStmt();
2635 }
2636
2637 llvm_unreachable("ReadingKind not set ?")__builtin_unreachable();
2638}
2639
2640Expr *ASTReader::ReadExpr(ModuleFile &F) {
2641 return cast_or_null<Expr>(ReadStmt(F));
2642}
2643
2644Expr *ASTReader::ReadSubExpr() {
2645 return cast_or_null<Expr>(ReadSubStmt());
2646}
2647
2648// Within the bitstream, expressions are stored in Reverse Polish
2649// Notation, with each of the subexpressions preceding the
2650// expression they are stored in. Subexpressions are stored from last to first.
2651// To evaluate expressions, we continue reading expressions and placing them on
2652// the stack, with expressions having operands removing those operands from the
2653// stack. Evaluation terminates when we see a STMT_STOP record, and
2654// the single remaining expression on the stack is our result.
2655Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) {
2656 ReadingKindTracker ReadingKind(Read_Stmt, *this);
2657 llvm::BitstreamCursor &Cursor = F.DeclsCursor;
2658
2659 // Map of offset to previously deserialized stmt. The offset points
2660 // just after the stmt record.
2661 llvm::DenseMap<uint64_t, Stmt *> StmtEntries;
2662
2663#ifndef NDEBUG1
2664 unsigned PrevNumStmts = StmtStack.size();
2665#endif
2666
2667 ASTRecordReader Record(*this, F);
2668 ASTStmtReader Reader(Record, Cursor);
2669 Stmt::EmptyShell Empty;
2670
2671 while (true) {
1
Loop condition is true. Entering loop body
2672 llvm::Expected<llvm::BitstreamEntry> MaybeEntry =
2673 Cursor.advanceSkippingSubblocks();
2
Calling 'BitstreamCursor::advanceSkippingSubblocks'
2674 if (!MaybeEntry) {
2675 Error(toString(MaybeEntry.takeError()));
2676 return nullptr;
2677 }
2678 llvm::BitstreamEntry Entry = MaybeEntry.get();
2679
2680 switch (Entry.Kind) {
2681 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2682 case llvm::BitstreamEntry::Error:
2683 Error("malformed block record in AST file");
2684 return nullptr;
2685 case llvm::BitstreamEntry::EndBlock:
2686 goto Done;
2687 case llvm::BitstreamEntry::Record:
2688 // The interesting case.
2689 break;
2690 }
2691
2692 ASTContext &Context = getContext();
2693 Stmt *S = nullptr;
2694 bool Finished = false;
2695 bool IsStmtReference = false;
2696 Expected<unsigned> MaybeStmtCode = Record.readRecord(Cursor, Entry.ID);
2697 if (!MaybeStmtCode) {
2698 Error(toString(MaybeStmtCode.takeError()));
2699 return nullptr;
2700 }
2701 switch ((StmtCode)MaybeStmtCode.get()) {
2702 case STMT_STOP:
2703 Finished = true;
2704 break;
2705
2706 case STMT_REF_PTR:
2707 IsStmtReference = true;
2708 assert(StmtEntries.find(Record[0]) != StmtEntries.end() &&((void)0)
2709 "No stmt was recorded for this offset reference!")((void)0);
2710 S = StmtEntries[Record.readInt()];
2711 break;
2712
2713 case STMT_NULL_PTR:
2714 S = nullptr;
2715 break;
2716
2717 case STMT_NULL:
2718 S = new (Context) NullStmt(Empty);
2719 break;
2720
2721 case STMT_COMPOUND:
2722 S = CompoundStmt::CreateEmpty(
2723 Context, /*NumStmts=*/Record[ASTStmtReader::NumStmtFields]);
2724 break;
2725
2726 case STMT_CASE:
2727 S = CaseStmt::CreateEmpty(
2728 Context,
2729 /*CaseStmtIsGNURange*/ Record[ASTStmtReader::NumStmtFields + 3]);
2730 break;
2731
2732 case STMT_DEFAULT:
2733 S = new (Context) DefaultStmt(Empty);
2734 break;
2735
2736 case STMT_LABEL:
2737 S = new (Context) LabelStmt(Empty);
2738 break;
2739
2740 case STMT_ATTRIBUTED:
2741 S = AttributedStmt::CreateEmpty(
2742 Context,
2743 /*NumAttrs*/Record[ASTStmtReader::NumStmtFields]);
2744 break;
2745
2746 case STMT_IF:
2747 S = IfStmt::CreateEmpty(
2748 Context,
2749 /* HasElse=*/Record[ASTStmtReader::NumStmtFields + 1],
2750 /* HasVar=*/Record[ASTStmtReader::NumStmtFields + 2],
2751 /* HasInit=*/Record[ASTStmtReader::NumStmtFields + 3]);
2752 break;
2753
2754 case STMT_SWITCH:
2755 S = SwitchStmt::CreateEmpty(
2756 Context,
2757 /* HasInit=*/Record[ASTStmtReader::NumStmtFields],
2758 /* HasVar=*/Record[ASTStmtReader::NumStmtFields + 1]);
2759 break;
2760
2761 case STMT_WHILE:
2762 S = WhileStmt::CreateEmpty(
2763 Context,
2764 /* HasVar=*/Record[ASTStmtReader::NumStmtFields]);
2765 break;
2766
2767 case STMT_DO:
2768 S = new (Context) DoStmt(Empty);
2769 break;
2770
2771 case STMT_FOR:
2772 S = new (Context) ForStmt(Empty);
2773 break;
2774
2775 case STMT_GOTO:
2776 S = new (Context) GotoStmt(Empty);
2777 break;
2778
2779 case STMT_INDIRECT_GOTO:
2780 S = new (Context) IndirectGotoStmt(Empty);
2781 break;
2782
2783 case STMT_CONTINUE:
2784 S = new (Context) ContinueStmt(Empty);
2785 break;
2786
2787 case STMT_BREAK:
2788 S = new (Context) BreakStmt(Empty);
2789 break;
2790
2791 case STMT_RETURN:
2792 S = ReturnStmt::CreateEmpty(
2793 Context, /* HasNRVOCandidate=*/Record[ASTStmtReader::NumStmtFields]);
2794 break;
2795
2796 case STMT_DECL:
2797 S = new (Context) DeclStmt(Empty);
2798 break;
2799
2800 case STMT_GCCASM:
2801 S = new (Context) GCCAsmStmt(Empty);
2802 break;
2803
2804 case STMT_MSASM:
2805 S = new (Context) MSAsmStmt(Empty);
2806 break;
2807
2808 case STMT_CAPTURED:
2809 S = CapturedStmt::CreateDeserialized(
2810 Context, Record[ASTStmtReader::NumStmtFields]);
2811 break;
2812
2813 case EXPR_CONSTANT:
2814 S = ConstantExpr::CreateEmpty(
2815 Context, static_cast<ConstantExpr::ResultStorageKind>(
2816 /*StorageKind=*/Record[ASTStmtReader::NumExprFields]));
2817 break;
2818
2819 case EXPR_SYCL_UNIQUE_STABLE_NAME:
2820 S = SYCLUniqueStableNameExpr::CreateEmpty(Context);
2821 break;
2822
2823 case EXPR_PREDEFINED:
2824 S = PredefinedExpr::CreateEmpty(
2825 Context,
2826 /*HasFunctionName*/ Record[ASTStmtReader::NumExprFields]);
2827 break;
2828
2829 case EXPR_DECL_REF:
2830 S = DeclRefExpr::CreateEmpty(
2831 Context,
2832 /*HasQualifier=*/Record[ASTStmtReader::NumExprFields],
2833 /*HasFoundDecl=*/Record[ASTStmtReader::NumExprFields + 1],
2834 /*HasTemplateKWAndArgsInfo=*/Record[ASTStmtReader::NumExprFields + 2],
2835 /*NumTemplateArgs=*/Record[ASTStmtReader::NumExprFields + 2] ?
2836 Record[ASTStmtReader::NumExprFields + 6] : 0);
2837 break;
2838
2839 case EXPR_INTEGER_LITERAL:
2840 S = IntegerLiteral::Create(Context, Empty);
2841 break;
2842
2843 case EXPR_FIXEDPOINT_LITERAL:
2844 S = FixedPointLiteral::Create(Context, Empty);
2845 break;
2846
2847 case EXPR_FLOATING_LITERAL:
2848 S = FloatingLiteral::Create(Context, Empty);
2849 break;
2850
2851 case EXPR_IMAGINARY_LITERAL:
2852 S = new (Context) ImaginaryLiteral(Empty);
2853 break;
2854
2855 case EXPR_STRING_LITERAL:
2856 S = StringLiteral::CreateEmpty(
2857 Context,
2858 /* NumConcatenated=*/Record[ASTStmtReader::NumExprFields],
2859 /* Length=*/Record[ASTStmtReader::NumExprFields + 1],
2860 /* CharByteWidth=*/Record[ASTStmtReader::NumExprFields + 2]);
2861 break;
2862
2863 case EXPR_CHARACTER_LITERAL:
2864 S = new (Context) CharacterLiteral(Empty);
2865 break;
2866
2867 case EXPR_PAREN:
2868 S = new (Context) ParenExpr(Empty);
2869 break;
2870
2871 case EXPR_PAREN_LIST:
2872 S = ParenListExpr::CreateEmpty(
2873 Context,
2874 /* NumExprs=*/Record[ASTStmtReader::NumExprFields]);
2875 break;
2876
2877 case EXPR_UNARY_OPERATOR:
2878 S = UnaryOperator::CreateEmpty(Context,
2879 Record[ASTStmtReader::NumExprFields]);
2880 break;
2881
2882 case EXPR_OFFSETOF:
2883 S = OffsetOfExpr::CreateEmpty(Context,
2884 Record[ASTStmtReader::NumExprFields],
2885 Record[ASTStmtReader::NumExprFields + 1]);
2886 break;
2887
2888 case EXPR_SIZEOF_ALIGN_OF:
2889 S = new (Context) UnaryExprOrTypeTraitExpr(Empty);
2890 break;
2891
2892 case EXPR_ARRAY_SUBSCRIPT:
2893 S = new (Context) ArraySubscriptExpr(Empty);
2894 break;
2895
2896 case EXPR_MATRIX_SUBSCRIPT:
2897 S = new (Context) MatrixSubscriptExpr(Empty);
2898 break;
2899
2900 case EXPR_OMP_ARRAY_SECTION:
2901 S = new (Context) OMPArraySectionExpr(Empty);
2902 break;
2903
2904 case EXPR_OMP_ARRAY_SHAPING:
2905 S = OMPArrayShapingExpr::CreateEmpty(
2906 Context, Record[ASTStmtReader::NumExprFields]);
2907 break;
2908
2909 case EXPR_OMP_ITERATOR:
2910 S = OMPIteratorExpr::CreateEmpty(Context,
2911 Record[ASTStmtReader::NumExprFields]);
2912 break;
2913
2914 case EXPR_CALL:
2915 S = CallExpr::CreateEmpty(
2916 Context, /*NumArgs=*/Record[ASTStmtReader::NumExprFields],
2917 /*HasFPFeatures=*/Record[ASTStmtReader::NumExprFields + 1], Empty);
2918 break;
2919
2920 case EXPR_RECOVERY:
2921 S = RecoveryExpr::CreateEmpty(
2922 Context, /*NumArgs=*/Record[ASTStmtReader::NumExprFields]);
2923 break;
2924
2925 case EXPR_MEMBER:
2926 S = MemberExpr::CreateEmpty(Context, Record[ASTStmtReader::NumExprFields],
2927 Record[ASTStmtReader::NumExprFields + 1],
2928 Record[ASTStmtReader::NumExprFields + 2],
2929 Record[ASTStmtReader::NumExprFields + 3]);
2930 break;
2931
2932 case EXPR_BINARY_OPERATOR:
2933 S = BinaryOperator::CreateEmpty(Context,
2934 Record[ASTStmtReader::NumExprFields]);
2935 break;
2936
2937 case EXPR_COMPOUND_ASSIGN_OPERATOR:
2938 S = CompoundAssignOperator::CreateEmpty(
2939 Context, Record[ASTStmtReader::NumExprFields]);
2940 break;
2941
2942 case EXPR_CONDITIONAL_OPERATOR:
2943 S = new (Context) ConditionalOperator(Empty);
2944 break;
2945
2946 case EXPR_BINARY_CONDITIONAL_OPERATOR:
2947 S = new (Context) BinaryConditionalOperator(Empty);
2948 break;
2949
2950 case EXPR_IMPLICIT_CAST:
2951 S = ImplicitCastExpr::CreateEmpty(
2952 Context,
2953 /*PathSize*/ Record[ASTStmtReader::NumExprFields],
2954 /*HasFPFeatures*/ Record[ASTStmtReader::NumExprFields + 1]);
2955 break;
2956
2957 case EXPR_CSTYLE_CAST:
2958 S = CStyleCastExpr::CreateEmpty(
2959 Context,
2960 /*PathSize*/ Record[ASTStmtReader::NumExprFields],
2961 /*HasFPFeatures*/ Record[ASTStmtReader::NumExprFields + 1]);
2962 break;
2963
2964 case EXPR_COMPOUND_LITERAL:
2965 S = new (Context) CompoundLiteralExpr(Empty);
2966 break;
2967
2968 case EXPR_EXT_VECTOR_ELEMENT:
2969 S = new (Context) ExtVectorElementExpr(Empty);
2970 break;
2971
2972 case EXPR_INIT_LIST:
2973 S = new (Context) InitListExpr(Empty);
2974 break;
2975
2976 case EXPR_DESIGNATED_INIT:
2977 S = DesignatedInitExpr::CreateEmpty(Context,
2978 Record[ASTStmtReader::NumExprFields] - 1);
2979
2980 break;
2981
2982 case EXPR_DESIGNATED_INIT_UPDATE:
2983 S = new (Context) DesignatedInitUpdateExpr(Empty);
2984 break;
2985
2986 case EXPR_IMPLICIT_VALUE_INIT:
2987 S = new (Context) ImplicitValueInitExpr(Empty);
2988 break;
2989
2990 case EXPR_NO_INIT:
2991 S = new (Context) NoInitExpr(Empty);
2992 break;
2993
2994 case EXPR_ARRAY_INIT_LOOP:
2995 S = new (Context) ArrayInitLoopExpr(Empty);
2996 break;
2997
2998 case EXPR_ARRAY_INIT_INDEX:
2999 S = new (Context) ArrayInitIndexExpr(Empty);
3000 break;
3001
3002 case EXPR_VA_ARG:
3003 S = new (Context) VAArgExpr(Empty);
3004 break;
3005
3006 case EXPR_SOURCE_LOC:
3007 S = new (Context) SourceLocExpr(Empty);
3008 break;
3009
3010 case EXPR_ADDR_LABEL:
3011 S = new (Context) AddrLabelExpr(Empty);
3012 break;
3013
3014 case EXPR_STMT:
3015 S = new (Context) StmtExpr(Empty);
3016 break;
3017
3018 case EXPR_CHOOSE:
3019 S = new (Context) ChooseExpr(Empty);
3020 break;
3021
3022 case EXPR_GNU_NULL:
3023 S = new (Context) GNUNullExpr(Empty);
3024 break;
3025
3026 case EXPR_SHUFFLE_VECTOR:
3027 S = new (Context) ShuffleVectorExpr(Empty);
3028 break;
3029
3030 case EXPR_CONVERT_VECTOR:
3031 S = new (Context) ConvertVectorExpr(Empty);
3032 break;
3033
3034 case EXPR_BLOCK:
3035 S = new (Context) BlockExpr(Empty);
3036 break;
3037
3038 case EXPR_GENERIC_SELECTION:
3039 S = GenericSelectionExpr::CreateEmpty(
3040 Context,
3041 /*NumAssocs=*/Record[ASTStmtReader::NumExprFields]);
3042 break;
3043
3044 case EXPR_OBJC_STRING_LITERAL:
3045 S = new (Context) ObjCStringLiteral(Empty);
3046 break;
3047
3048 case EXPR_OBJC_BOXED_EXPRESSION:
3049 S = new (Context) ObjCBoxedExpr(Empty);
3050 break;
3051
3052 case EXPR_OBJC_ARRAY_LITERAL:
3053 S = ObjCArrayLiteral::CreateEmpty(Context,
3054 Record[ASTStmtReader::NumExprFields]);
3055 break;
3056
3057 case EXPR_OBJC_DICTIONARY_LITERAL:
3058 S = ObjCDictionaryLiteral::CreateEmpty(Context,
3059 Record[ASTStmtReader::NumExprFields],
3060 Record[ASTStmtReader::NumExprFields + 1]);
3061 break;
3062
3063 case EXPR_OBJC_ENCODE:
3064 S = new (Context) ObjCEncodeExpr(Empty);
3065 break;
3066
3067 case EXPR_OBJC_SELECTOR_EXPR:
3068 S = new (Context) ObjCSelectorExpr(Empty);
3069 break;
3070
3071 case EXPR_OBJC_PROTOCOL_EXPR:
3072 S = new (Context) ObjCProtocolExpr(Empty);
3073 break;
3074
3075 case EXPR_OBJC_IVAR_REF_EXPR:
3076 S = new (Context) ObjCIvarRefExpr(Empty);
3077 break;
3078
3079 case EXPR_OBJC_PROPERTY_REF_EXPR:
3080 S = new (Context) ObjCPropertyRefExpr(Empty);
3081 break;
3082
3083 case EXPR_OBJC_SUBSCRIPT_REF_EXPR:
3084 S = new (Context) ObjCSubscriptRefExpr(Empty);
3085 break;
3086
3087 case EXPR_OBJC_KVC_REF_EXPR:
3088 llvm_unreachable("mismatching AST file")__builtin_unreachable();
3089
3090 case EXPR_OBJC_MESSAGE_EXPR:
3091 S = ObjCMessageExpr::CreateEmpty(Context,
3092 Record[ASTStmtReader::NumExprFields],
3093 Record[ASTStmtReader::NumExprFields + 1]);
3094 break;
3095
3096 case EXPR_OBJC_ISA:
3097 S = new (Context) ObjCIsaExpr(Empty);
3098 break;
3099
3100 case EXPR_OBJC_INDIRECT_COPY_RESTORE:
3101 S = new (Context) ObjCIndirectCopyRestoreExpr(Empty);
3102 break;
3103
3104 case EXPR_OBJC_BRIDGED_CAST:
3105 S = new (Context) ObjCBridgedCastExpr(Empty);
3106 break;
3107
3108 case STMT_OBJC_FOR_COLLECTION:
3109 S = new (Context) ObjCForCollectionStmt(Empty);
3110 break;
3111
3112 case STMT_OBJC_CATCH:
3113 S = new (Context) ObjCAtCatchStmt(Empty);
3114 break;
3115
3116 case STMT_OBJC_FINALLY:
3117 S = new (Context) ObjCAtFinallyStmt(Empty);
3118 break;
3119
3120 case STMT_OBJC_AT_TRY:
3121 S = ObjCAtTryStmt::CreateEmpty(Context,
3122 Record[ASTStmtReader::NumStmtFields],
3123 Record[ASTStmtReader::NumStmtFields + 1]);
3124 break;
3125
3126 case STMT_OBJC_AT_SYNCHRONIZED:
3127 S = new (Context) ObjCAtSynchronizedStmt(Empty);
3128 break;
3129
3130 case STMT_OBJC_AT_THROW:
3131 S = new (Context) ObjCAtThrowStmt(Empty);
3132 break;
3133
3134 case STMT_OBJC_AUTORELEASE_POOL:
3135 S = new (Context) ObjCAutoreleasePoolStmt(Empty);
3136 break;
3137
3138 case EXPR_OBJC_BOOL_LITERAL:
3139 S = new (Context) ObjCBoolLiteralExpr(Empty);
3140 break;
3141
3142 case EXPR_OBJC_AVAILABILITY_CHECK:
3143 S = new (Context) ObjCAvailabilityCheckExpr(Empty);
3144 break;
3145
3146 case STMT_SEH_LEAVE:
3147 S = new (Context) SEHLeaveStmt(Empty);
3148 break;
3149
3150 case STMT_SEH_EXCEPT:
3151 S = new (Context) SEHExceptStmt(Empty);
3152 break;
3153
3154 case STMT_SEH_FINALLY:
3155 S = new (Context) SEHFinallyStmt(Empty);
3156 break;
3157
3158 case STMT_SEH_TRY:
3159 S = new (Context) SEHTryStmt(Empty);
3160 break;
3161
3162 case STMT_CXX_CATCH:
3163 S = new (Context) CXXCatchStmt(Empty);
3164 break;
3165
3166 case STMT_CXX_TRY:
3167 S = CXXTryStmt::Create(Context, Empty,
3168 /*numHandlers=*/Record[ASTStmtReader::NumStmtFields]);
3169 break;
3170
3171 case STMT_CXX_FOR_RANGE:
3172 S = new (Context) CXXForRangeStmt(Empty);
3173 break;
3174
3175 case STMT_MS_DEPENDENT_EXISTS:
3176 S = new (Context) MSDependentExistsStmt(SourceLocation(), true,
3177 NestedNameSpecifierLoc(),
3178 DeclarationNameInfo(),
3179 nullptr);
3180 break;
3181
3182 case STMT_OMP_CANONICAL_LOOP:
3183 S = OMPCanonicalLoop::createEmpty(Context);
3184 break;
3185
3186 case STMT_OMP_PARALLEL_DIRECTIVE:
3187 S =
3188 OMPParallelDirective::CreateEmpty(Context,
3189 Record[ASTStmtReader::NumStmtFields],
3190 Empty);
3191 break;
3192
3193 case STMT_OMP_SIMD_DIRECTIVE: {
3194 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3195 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3196 S = OMPSimdDirective::CreateEmpty(Context, NumClauses,
3197 CollapsedNum, Empty);
3198 break;
3199 }
3200
3201 case STMT_OMP_TILE_DIRECTIVE: {
3202 unsigned NumLoops = Record[ASTStmtReader::NumStmtFields];
3203 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3204 S = OMPTileDirective::CreateEmpty(Context, NumClauses, NumLoops);
3205 break;
3206 }
3207
3208 case STMT_OMP_UNROLL_DIRECTIVE: {
3209 assert(Record[ASTStmtReader::NumStmtFields] == 1 && "Unroll directive accepts only a single loop")((void)0);
3210 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3211 S = OMPUnrollDirective::CreateEmpty(Context, NumClauses);
3212 break;
3213 }
3214
3215 case STMT_OMP_FOR_DIRECTIVE: {
3216 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3217 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3218 S = OMPForDirective::CreateEmpty(Context, NumClauses, CollapsedNum,
3219 Empty);
3220 break;
3221 }
3222
3223 case STMT_OMP_FOR_SIMD_DIRECTIVE: {
3224 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3225 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3226 S = OMPForSimdDirective::CreateEmpty(Context, NumClauses, CollapsedNum,
3227 Empty);
3228 break;
3229 }
3230
3231 case STMT_OMP_SECTIONS_DIRECTIVE:
3232 S = OMPSectionsDirective::CreateEmpty(
3233 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3234 break;
3235
3236 case STMT_OMP_SECTION_DIRECTIVE:
3237 S = OMPSectionDirective::CreateEmpty(Context, Empty);
3238 break;
3239
3240 case STMT_OMP_SINGLE_DIRECTIVE:
3241 S = OMPSingleDirective::CreateEmpty(
3242 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3243 break;
3244
3245 case STMT_OMP_MASTER_DIRECTIVE:
3246 S = OMPMasterDirective::CreateEmpty(Context, Empty);
3247 break;
3248
3249 case STMT_OMP_CRITICAL_DIRECTIVE:
3250 S = OMPCriticalDirective::CreateEmpty(
3251 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3252 break;
3253
3254 case STMT_OMP_PARALLEL_FOR_DIRECTIVE: {
3255 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3256 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3257 S = OMPParallelForDirective::CreateEmpty(Context, NumClauses,
3258 CollapsedNum, Empty);
3259 break;
3260 }
3261
3262 case STMT_OMP_PARALLEL_FOR_SIMD_DIRECTIVE: {
3263 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3264 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3265 S = OMPParallelForSimdDirective::CreateEmpty(Context, NumClauses,
3266 CollapsedNum, Empty);
3267 break;
3268 }
3269
3270 case STMT_OMP_PARALLEL_MASTER_DIRECTIVE:
3271 S = OMPParallelMasterDirective::CreateEmpty(
3272 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3273 break;
3274
3275 case STMT_OMP_PARALLEL_SECTIONS_DIRECTIVE:
3276 S = OMPParallelSectionsDirective::CreateEmpty(
3277 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3278 break;
3279
3280 case STMT_OMP_TASK_DIRECTIVE:
3281 S = OMPTaskDirective::CreateEmpty(
3282 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3283 break;
3284
3285 case STMT_OMP_TASKYIELD_DIRECTIVE:
3286 S = OMPTaskyieldDirective::CreateEmpty(Context, Empty);
3287 break;
3288
3289 case STMT_OMP_BARRIER_DIRECTIVE:
3290 S = OMPBarrierDirective::CreateEmpty(Context, Empty);
3291 break;
3292
3293 case STMT_OMP_TASKWAIT_DIRECTIVE:
3294 S = OMPTaskwaitDirective::CreateEmpty(Context, Empty);
3295 break;
3296
3297 case STMT_OMP_TASKGROUP_DIRECTIVE:
3298 S = OMPTaskgroupDirective::CreateEmpty(
3299 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3300 break;
3301
3302 case STMT_OMP_FLUSH_DIRECTIVE:
3303 S = OMPFlushDirective::CreateEmpty(
3304 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3305 break;
3306
3307 case STMT_OMP_DEPOBJ_DIRECTIVE:
3308 S = OMPDepobjDirective::CreateEmpty(
3309 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3310 break;
3311
3312 case STMT_OMP_SCAN_DIRECTIVE:
3313 S = OMPScanDirective::CreateEmpty(
3314 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3315 break;
3316
3317 case STMT_OMP_ORDERED_DIRECTIVE: {
3318 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields];
3319 bool HasAssociatedStmt = Record[ASTStmtReader::NumStmtFields + 2];
3320 S = OMPOrderedDirective::CreateEmpty(Context, NumClauses,
3321 !HasAssociatedStmt, Empty);
3322 break;
3323 }
3324
3325 case STMT_OMP_ATOMIC_DIRECTIVE:
3326 S = OMPAtomicDirective::CreateEmpty(
3327 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3328 break;
3329
3330 case STMT_OMP_TARGET_DIRECTIVE:
3331 S = OMPTargetDirective::CreateEmpty(
3332 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3333 break;
3334
3335 case STMT_OMP_TARGET_DATA_DIRECTIVE:
3336 S = OMPTargetDataDirective::CreateEmpty(
3337 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3338 break;
3339
3340 case STMT_OMP_TARGET_ENTER_DATA_DIRECTIVE:
3341 S = OMPTargetEnterDataDirective::CreateEmpty(
3342 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3343 break;
3344
3345 case STMT_OMP_TARGET_EXIT_DATA_DIRECTIVE:
3346 S = OMPTargetExitDataDirective::CreateEmpty(
3347 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3348 break;
3349
3350 case STMT_OMP_TARGET_PARALLEL_DIRECTIVE:
3351 S = OMPTargetParallelDirective::CreateEmpty(
3352 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3353 break;
3354
3355 case STMT_OMP_TARGET_PARALLEL_FOR_DIRECTIVE: {
3356 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3357 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3358 S = OMPTargetParallelForDirective::CreateEmpty(Context, NumClauses,
3359 CollapsedNum, Empty);
3360 break;
3361 }
3362
3363 case STMT_OMP_TARGET_UPDATE_DIRECTIVE:
3364 S = OMPTargetUpdateDirective::CreateEmpty(
3365 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3366 break;
3367
3368 case STMT_OMP_TEAMS_DIRECTIVE:
3369 S = OMPTeamsDirective::CreateEmpty(
3370 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3371 break;
3372
3373 case STMT_OMP_CANCELLATION_POINT_DIRECTIVE:
3374 S = OMPCancellationPointDirective::CreateEmpty(Context, Empty);
3375 break;
3376
3377 case STMT_OMP_CANCEL_DIRECTIVE:
3378 S = OMPCancelDirective::CreateEmpty(
3379 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3380 break;
3381
3382 case STMT_OMP_TASKLOOP_DIRECTIVE: {
3383 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3384 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3385 S = OMPTaskLoopDirective::CreateEmpty(Context, NumClauses, CollapsedNum,
3386 Empty);
3387 break;
3388 }
3389
3390 case STMT_OMP_TASKLOOP_SIMD_DIRECTIVE: {
3391 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3392 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3393 S = OMPTaskLoopSimdDirective::CreateEmpty(Context, NumClauses,
3394 CollapsedNum, Empty);
3395 break;
3396 }
3397
3398 case STMT_OMP_MASTER_TASKLOOP_DIRECTIVE: {
3399 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3400 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3401 S = OMPMasterTaskLoopDirective::CreateEmpty(Context, NumClauses,
3402 CollapsedNum, Empty);
3403 break;
3404 }
3405
3406 case STMT_OMP_MASTER_TASKLOOP_SIMD_DIRECTIVE: {
3407 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3408 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3409 S = OMPMasterTaskLoopSimdDirective::CreateEmpty(Context, NumClauses,
3410 CollapsedNum, Empty);
3411 break;
3412 }
3413
3414 case STMT_OMP_PARALLEL_MASTER_TASKLOOP_DIRECTIVE: {
3415 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3416 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3417 S = OMPParallelMasterTaskLoopDirective::CreateEmpty(Context, NumClauses,
3418 CollapsedNum, Empty);
3419 break;
3420 }
3421
3422 case STMT_OMP_PARALLEL_MASTER_TASKLOOP_SIMD_DIRECTIVE: {
3423 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3424 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3425 S = OMPParallelMasterTaskLoopSimdDirective::CreateEmpty(
3426 Context, NumClauses, CollapsedNum, Empty);
3427 break;
3428 }
3429
3430 case STMT_OMP_DISTRIBUTE_DIRECTIVE: {
3431 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3432 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3433 S = OMPDistributeDirective::CreateEmpty(Context, NumClauses, CollapsedNum,
3434 Empty);
3435 break;
3436 }
3437
3438 case STMT_OMP_DISTRIBUTE_PARALLEL_FOR_DIRECTIVE: {
3439 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3440 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3441 S = OMPDistributeParallelForDirective::CreateEmpty(Context, NumClauses,
3442 CollapsedNum, Empty);
3443 break;
3444 }
3445
3446 case STMT_OMP_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE: {
3447 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3448 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3449 S = OMPDistributeParallelForSimdDirective::CreateEmpty(Context, NumClauses,
3450 CollapsedNum,
3451 Empty);
3452 break;
3453 }
3454
3455 case STMT_OMP_DISTRIBUTE_SIMD_DIRECTIVE: {
3456 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3457 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3458 S = OMPDistributeSimdDirective::CreateEmpty(Context, NumClauses,
3459 CollapsedNum, Empty);
3460 break;
3461 }
3462
3463 case STMT_OMP_TARGET_PARALLEL_FOR_SIMD_DIRECTIVE: {
3464 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3465 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3466 S = OMPTargetParallelForSimdDirective::CreateEmpty(Context, NumClauses,
3467 CollapsedNum, Empty);
3468 break;
3469 }
3470
3471 case STMT_OMP_TARGET_SIMD_DIRECTIVE: {
3472 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3473 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3474 S = OMPTargetSimdDirective::CreateEmpty(Context, NumClauses, CollapsedNum,
3475 Empty);
3476 break;
3477 }
3478
3479 case STMT_OMP_TEAMS_DISTRIBUTE_DIRECTIVE: {
3480 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3481 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3482 S = OMPTeamsDistributeDirective::CreateEmpty(Context, NumClauses,
3483 CollapsedNum, Empty);
3484 break;
3485 }
3486
3487 case STMT_OMP_TEAMS_DISTRIBUTE_SIMD_DIRECTIVE: {
3488 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3489 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3490 S = OMPTeamsDistributeSimdDirective::CreateEmpty(Context, NumClauses,
3491 CollapsedNum, Empty);
3492 break;
3493 }
3494
3495 case STMT_OMP_TEAMS_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE: {
3496 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3497 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3498 S = OMPTeamsDistributeParallelForSimdDirective::CreateEmpty(
3499 Context, NumClauses, CollapsedNum, Empty);
3500 break;
3501 }
3502
3503 case STMT_OMP_TEAMS_DISTRIBUTE_PARALLEL_FOR_DIRECTIVE: {
3504 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3505 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3506 S = OMPTeamsDistributeParallelForDirective::CreateEmpty(
3507 Context, NumClauses, CollapsedNum, Empty);
3508 break;
3509 }
3510
3511 case STMT_OMP_TARGET_TEAMS_DIRECTIVE:
3512 S = OMPTargetTeamsDirective::CreateEmpty(
3513 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3514 break;
3515
3516 case STMT_OMP_TARGET_TEAMS_DISTRIBUTE_DIRECTIVE: {
3517 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3518 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3519 S = OMPTargetTeamsDistributeDirective::CreateEmpty(Context, NumClauses,
3520 CollapsedNum, Empty);
3521 break;
3522 }
3523
3524 case STMT_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_FOR_DIRECTIVE: {
3525 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3526 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3527 S = OMPTargetTeamsDistributeParallelForDirective::CreateEmpty(
3528 Context, NumClauses, CollapsedNum, Empty);
3529 break;
3530 }
3531
3532 case STMT_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE: {
3533 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3534 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3535 S = OMPTargetTeamsDistributeParallelForSimdDirective::CreateEmpty(
3536 Context, NumClauses, CollapsedNum, Empty);
3537 break;
3538 }
3539
3540 case STMT_OMP_TARGET_TEAMS_DISTRIBUTE_SIMD_DIRECTIVE: {
3541 unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
3542 unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
3543 S = OMPTargetTeamsDistributeSimdDirective::CreateEmpty(
3544 Context, NumClauses, CollapsedNum, Empty);
3545 break;
3546 }
3547
3548 case STMT_OMP_INTEROP_DIRECTIVE:
3549 S = OMPInteropDirective::CreateEmpty(
3550 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3551 break;
3552
3553 case STMT_OMP_DISPATCH_DIRECTIVE:
3554 S = OMPDispatchDirective::CreateEmpty(
3555 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3556 break;
3557
3558 case STMT_OMP_MASKED_DIRECTIVE:
3559 S = OMPMaskedDirective::CreateEmpty(
3560 Context, Record[ASTStmtReader::NumStmtFields], Empty);
3561 break;
3562
3563 case EXPR_CXX_OPERATOR_CALL:
3564 S = CXXOperatorCallExpr::CreateEmpty(
3565 Context, /*NumArgs=*/Record[ASTStmtReader::NumExprFields],
3566 /*HasFPFeatures=*/Record[ASTStmtReader::NumExprFields + 1], Empty);
3567 break;
3568
3569 case EXPR_CXX_MEMBER_CALL:
3570 S = CXXMemberCallExpr::CreateEmpty(
3571 Context, /*NumArgs=*/Record[ASTStmtReader::NumExprFields],
3572 /*HasFPFeatures=*/Record[ASTStmtReader::NumExprFields + 1], Empty);
3573 break;
3574
3575 case EXPR_CXX_REWRITTEN_BINARY_OPERATOR:
3576 S = new (Context) CXXRewrittenBinaryOperator(Empty);
3577 break;
3578
3579 case EXPR_CXX_CONSTRUCT:
3580 S = CXXConstructExpr::CreateEmpty(
3581 Context,
3582 /* NumArgs=*/Record[ASTStmtReader::NumExprFields]);
3583 break;
3584
3585 case EXPR_CXX_INHERITED_CTOR_INIT:
3586 S = new (Context) CXXInheritedCtorInitExpr(Empty);
3587 break;
3588
3589 case EXPR_CXX_TEMPORARY_OBJECT:
3590 S = CXXTemporaryObjectExpr::CreateEmpty(
3591 Context,
3592 /* NumArgs=*/Record[ASTStmtReader::NumExprFields]);
3593 break;
3594
3595 case EXPR_CXX_STATIC_CAST:
3596 S = CXXStaticCastExpr::CreateEmpty(
3597 Context,
3598 /*PathSize*/ Record[ASTStmtReader::NumExprFields],
3599 /*HasFPFeatures*/ Record[ASTStmtReader::NumExprFields + 1]);
3600 break;
3601
3602 case EXPR_CXX_DYNAMIC_CAST:
3603 S = CXXDynamicCastExpr::CreateEmpty(Context,
3604 /*PathSize*/ Record[ASTStmtReader::NumExprFields]);
3605 break;
3606
3607 case EXPR_CXX_REINTERPRET_CAST:
3608 S = CXXReinterpretCastExpr::CreateEmpty(Context,
3609 /*PathSize*/ Record[ASTStmtReader::NumExprFields]);
3610 break;
3611
3612 case EXPR_CXX_CONST_CAST:
3613 S = CXXConstCastExpr::CreateEmpty(Context);
3614 break;
3615
3616 case EXPR_CXX_ADDRSPACE_CAST:
3617 S = CXXAddrspaceCastExpr::CreateEmpty(Context);
3618 break;
3619
3620 case EXPR_CXX_FUNCTIONAL_CAST:
3621 S = CXXFunctionalCastExpr::CreateEmpty(
3622 Context,
3623 /*PathSize*/ Record[ASTStmtReader::NumExprFields],
3624 /*HasFPFeatures*/ Record[ASTStmtReader::NumExprFields + 1]);
3625 break;
3626
3627 case EXPR_BUILTIN_BIT_CAST:
3628 assert(Record[ASTStmtReader::NumExprFields] == 0 && "Wrong PathSize!")((void)0);
3629 S = new (Context) BuiltinBitCastExpr(Empty);
3630 break;
3631
3632 case EXPR_USER_DEFINED_LITERAL:
3633 S = UserDefinedLiteral::CreateEmpty(
3634 Context, /*NumArgs=*/Record[ASTStmtReader::NumExprFields],
3635 /*HasFPFeatures=*/Record[ASTStmtReader::NumExprFields + 1], Empty);
3636 break;
3637
3638 case EXPR_CXX_STD_INITIALIZER_LIST:
3639 S = new (Context) CXXStdInitializerListExpr(Empty);
3640 break;
3641
3642 case EXPR_CXX_BOOL_LITERAL:
3643 S = new (Context) CXXBoolLiteralExpr(Empty);
3644 break;
3645
3646 case EXPR_CXX_NULL_PTR_LITERAL:
3647 S = new (Context) CXXNullPtrLiteralExpr(Empty);
3648 break;
3649
3650 case EXPR_CXX_TYPEID_EXPR:
3651 S = new (Context) CXXTypeidExpr(Empty, true);
3652 break;
3653
3654 case EXPR_CXX_TYPEID_TYPE:
3655 S = new (Context) CXXTypeidExpr(Empty, false);
3656 break;
3657
3658 case EXPR_CXX_UUIDOF_EXPR:
3659 S = new (Context) CXXUuidofExpr(Empty, true);
3660 break;
3661
3662 case EXPR_CXX_PROPERTY_REF_EXPR:
3663 S = new (Context) MSPropertyRefExpr(Empty);
3664 break;
3665
3666 case EXPR_CXX_PROPERTY_SUBSCRIPT_EXPR:
3667 S = new (Context) MSPropertySubscriptExpr(Empty);
3668 break;
3669
3670 case EXPR_CXX_UUIDOF_TYPE:
3671 S = new (Context) CXXUuidofExpr(Empty, false);
3672 break;
3673
3674 case EXPR_CXX_THIS:
3675 S = new (Context) CXXThisExpr(Empty);
3676 break;
3677
3678 case EXPR_CXX_THROW:
3679 S = new (Context) CXXThrowExpr(Empty);
3680 break;
3681
3682 case EXPR_CXX_DEFAULT_ARG:
3683 S = new (Context) CXXDefaultArgExpr(Empty);
3684 break;
3685
3686 case EXPR_CXX_DEFAULT_INIT:
3687 S = new (Context) CXXDefaultInitExpr(Empty);
3688 break;
3689
3690 case EXPR_CXX_BIND_TEMPORARY:
3691 S = new (Context) CXXBindTemporaryExpr(Empty);
3692 break;
3693
3694 case EXPR_CXX_SCALAR_VALUE_INIT:
3695 S = new (Context) CXXScalarValueInitExpr(Empty);
3696 break;
3697
3698 case EXPR_CXX_NEW:
3699 S = CXXNewExpr::CreateEmpty(
3700 Context,
3701 /*IsArray=*/Record[ASTStmtReader::NumExprFields],
3702 /*HasInit=*/Record[ASTStmtReader::NumExprFields + 1],
3703 /*NumPlacementArgs=*/Record[ASTStmtReader::NumExprFields + 2],
3704 /*IsParenTypeId=*/Record[ASTStmtReader::NumExprFields + 3]);
3705 break;
3706
3707 case EXPR_CXX_DELETE:
3708 S = new (Context) CXXDeleteExpr(Empty);
3709 break;
3710
3711 case EXPR_CXX_PSEUDO_DESTRUCTOR:
3712 S = new (Context) CXXPseudoDestructorExpr(Empty);
3713 break;
3714
3715 case EXPR_EXPR_WITH_CLEANUPS:
3716 S = ExprWithCleanups::Create(Context, Empty,
3717 Record[ASTStmtReader::NumExprFields]);
3718 break;
3719
3720 case EXPR_CXX_DEPENDENT_SCOPE_MEMBER:
3721 S = CXXDependentScopeMemberExpr::CreateEmpty(
3722 Context,
3723 /*HasTemplateKWAndArgsInfo=*/Record[ASTStmtReader::NumExprFields],
3724 /*NumTemplateArgs=*/Record[ASTStmtReader::NumExprFields + 1],
3725 /*HasFirstQualifierFoundInScope=*/
3726 Record[ASTStmtReader::NumExprFields + 2]);
3727 break;
3728
3729 case EXPR_CXX_DEPENDENT_SCOPE_DECL_REF:
3730 S = DependentScopeDeclRefExpr::CreateEmpty(Context,
3731 /*HasTemplateKWAndArgsInfo=*/Record[ASTStmtReader::NumExprFields],
3732 /*NumTemplateArgs=*/Record[ASTStmtReader::NumExprFields]
3733 ? Record[ASTStmtReader::NumExprFields + 1]
3734 : 0);
3735 break;
3736
3737 case EXPR_CXX_UNRESOLVED_CONSTRUCT:
3738 S = CXXUnresolvedConstructExpr::CreateEmpty(Context,
3739 /*NumArgs=*/Record[ASTStmtReader::NumExprFields]);
3740 break;
3741
3742 case EXPR_CXX_UNRESOLVED_MEMBER:
3743 S = UnresolvedMemberExpr::CreateEmpty(
3744 Context,
3745 /*NumResults=*/Record[ASTStmtReader::NumExprFields],
3746 /*HasTemplateKWAndArgsInfo=*/Record[ASTStmtReader::NumExprFields + 1],
3747 /*NumTemplateArgs=*/
3748 Record[ASTStmtReader::NumExprFields + 1]
3749 ? Record[ASTStmtReader::NumExprFields + 2]
3750 : 0);
3751 break;
3752
3753 case EXPR_CXX_UNRESOLVED_LOOKUP:
3754 S = UnresolvedLookupExpr::CreateEmpty(
3755 Context,
3756 /*NumResults=*/Record[ASTStmtReader::NumExprFields],
3757 /*HasTemplateKWAndArgsInfo=*/Record[ASTStmtReader::NumExprFields + 1],
3758 /*NumTemplateArgs=*/
3759 Record[ASTStmtReader::NumExprFields + 1]
3760 ? Record[ASTStmtReader::NumExprFields + 2]
3761 : 0);
3762 break;
3763
3764 case EXPR_TYPE_TRAIT:
3765 S = TypeTraitExpr::CreateDeserialized(Context,
3766 Record[ASTStmtReader::NumExprFields]);
3767 break;
3768
3769 case EXPR_ARRAY_TYPE_TRAIT:
3770 S = new (Context) ArrayTypeTraitExpr(Empty);
3771 break;
3772
3773 case EXPR_CXX_EXPRESSION_TRAIT:
3774 S = new (Context) ExpressionTraitExpr(Empty);
3775 break;
3776
3777 case EXPR_CXX_NOEXCEPT:
3778 S = new (Context) CXXNoexceptExpr(Empty);
3779 break;
3780
3781 case EXPR_PACK_EXPANSION:
3782 S = new (Context) PackExpansionExpr(Empty);
3783 break;
3784
3785 case EXPR_SIZEOF_PACK:
3786 S = SizeOfPackExpr::CreateDeserialized(
3787 Context,
3788 /*NumPartialArgs=*/Record[ASTStmtReader::NumExprFields]);
3789 break;
3790
3791 case EXPR_SUBST_NON_TYPE_TEMPLATE_PARM:
3792 S = new (Context) SubstNonTypeTemplateParmExpr(Empty);
3793 break;
3794
3795 case EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK:
3796 S = new (Context) SubstNonTypeTemplateParmPackExpr(Empty);
3797 break;
3798
3799 case EXPR_FUNCTION_PARM_PACK:
3800 S = FunctionParmPackExpr::CreateEmpty(Context,
3801 Record[ASTStmtReader::NumExprFields]);
3802 break;
3803
3804 case EXPR_MATERIALIZE_TEMPORARY:
3805 S = new (Context) MaterializeTemporaryExpr(Empty);
3806 break;
3807
3808 case EXPR_CXX_FOLD:
3809 S = new (Context) CXXFoldExpr(Empty);
3810 break;
3811
3812 case EXPR_OPAQUE_VALUE:
3813 S = new (Context) OpaqueValueExpr(Empty);
3814 break;
3815
3816 case EXPR_CUDA_KERNEL_CALL:
3817 S = CUDAKernelCallExpr::CreateEmpty(
3818 Context, /*NumArgs=*/Record[ASTStmtReader::NumExprFields],
3819 /*HasFPFeatures=*/Record[ASTStmtReader::NumExprFields + 1], Empty);
3820 break;
3821
3822 case EXPR_ASTYPE:
3823 S = new (Context) AsTypeExpr(Empty);
3824 break;
3825
3826 case EXPR_PSEUDO_OBJECT: {
3827 unsigned numSemanticExprs = Record[ASTStmtReader::NumExprFields];
3828 S = PseudoObjectExpr::Create(Context, Empty, numSemanticExprs);
3829 break;
3830 }
3831
3832 case EXPR_ATOMIC:
3833 S = new (Context) AtomicExpr(Empty);
3834 break;
3835
3836 case EXPR_LAMBDA: {
3837 unsigned NumCaptures = Record[ASTStmtReader::NumExprFields];
3838 S = LambdaExpr::CreateDeserialized(Context, NumCaptures);
3839 break;
3840 }
3841
3842 case STMT_COROUTINE_BODY: {
3843 unsigned NumParams = Record[ASTStmtReader::NumStmtFields];
3844 S = CoroutineBodyStmt::Create(Context, Empty, NumParams);
3845 break;
3846 }
3847
3848 case STMT_CORETURN:
3849 S = new (Context) CoreturnStmt(Empty);
3850 break;
3851
3852 case EXPR_COAWAIT:
3853 S = new (Context) CoawaitExpr(Empty);
3854 break;
3855
3856 case EXPR_COYIELD:
3857 S = new (Context) CoyieldExpr(Empty);
3858 break;
3859
3860 case EXPR_DEPENDENT_COAWAIT:
3861 S = new (Context) DependentCoawaitExpr(Empty);
3862 break;
3863
3864 case EXPR_CONCEPT_SPECIALIZATION: {
3865 unsigned numTemplateArgs = Record[ASTStmtReader::NumExprFields];
3866 S = ConceptSpecializationExpr::Create(Context, Empty, numTemplateArgs);
3867 break;
3868 }
3869
3870 case EXPR_REQUIRES:
3871 unsigned numLocalParameters = Record[ASTStmtReader::NumExprFields];
3872 unsigned numRequirement = Record[ASTStmtReader::NumExprFields + 1];
3873 S = RequiresExpr::Create(Context, Empty, numLocalParameters,
3874 numRequirement);
3875 break;
3876 }
3877
3878 // We hit a STMT_STOP, so we're done with this expression.
3879 if (Finished)
3880 break;
3881
3882 ++NumStatementsRead;
3883
3884 if (S && !IsStmtReference) {
3885 Reader.Visit(S);
3886 StmtEntries[Cursor.GetCurrentBitNo()] = S;
3887 }
3888
3889 assert(Record.getIdx() == Record.size() &&((void)0)
3890 "Invalid deserialization of statement")((void)0);
3891 StmtStack.push_back(S);
3892 }
3893Done:
3894 assert(StmtStack.size() > PrevNumStmts && "Read too many sub-stmts!")((void)0);
3895 assert(StmtStack.size() == PrevNumStmts + 1 && "Extra expressions on stack!")((void)0);
3896 return StmtStack.pop_back_val();
3897}

/usr/src/gnu/usr.bin/clang/libclangSerialization/../../../llvm/llvm/include/llvm/Bitstream/BitstreamReader.h

1//===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This header defines the BitstreamReader class. This class can be used to
10// read an arbitrary bitstream, regardless of its contents.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_BITSTREAM_BITSTREAMREADER_H
15#define LLVM_BITSTREAM_BITSTREAMREADER_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/Bitstream/BitCodes.h"
20#include "llvm/Support/Endian.h"
21#include "llvm/Support/Error.h"
22#include "llvm/Support/ErrorHandling.h"
23#include "llvm/Support/MathExtras.h"
24#include "llvm/Support/MemoryBuffer.h"
25#include <algorithm>
26#include <cassert>
27#include <climits>
28#include <cstddef>
29#include <cstdint>
30#include <memory>
31#include <string>
32#include <utility>
33#include <vector>
34
35namespace llvm {
36
37/// This class maintains the abbreviations read from a block info block.
38class BitstreamBlockInfo {
39public:
40 /// This contains information emitted to BLOCKINFO_BLOCK blocks. These
41 /// describe abbreviations that all blocks of the specified ID inherit.
42 struct BlockInfo {
43 unsigned BlockID = 0;
44 std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
45 std::string Name;
46 std::vector<std::pair<unsigned, std::string>> RecordNames;
47 };
48
49private:
50 std::vector<BlockInfo> BlockInfoRecords;
51
52public:
53 /// If there is block info for the specified ID, return it, otherwise return
54 /// null.
55 const BlockInfo *getBlockInfo(unsigned BlockID) const {
56 // Common case, the most recent entry matches BlockID.
57 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
58 return &BlockInfoRecords.back();
59
60 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
61 i != e; ++i)
62 if (BlockInfoRecords[i].BlockID == BlockID)
63 return &BlockInfoRecords[i];
64 return nullptr;
65 }
66
67 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
68 if (const BlockInfo *BI = getBlockInfo(BlockID))
69 return *const_cast<BlockInfo*>(BI);
70
71 // Otherwise, add a new record.
72 BlockInfoRecords.emplace_back();
73 BlockInfoRecords.back().BlockID = BlockID;
74 return BlockInfoRecords.back();
75 }
76};
77
78/// This represents a position within a bitstream. There may be multiple
79/// independent cursors reading within one bitstream, each maintaining their
80/// own local state.
81class SimpleBitstreamCursor {
82 ArrayRef<uint8_t> BitcodeBytes;
83 size_t NextChar = 0;
84
85public:
86 /// This is the current data we have pulled from the stream but have not
87 /// returned to the client. This is specifically and intentionally defined to
88 /// follow the word size of the host machine for efficiency. We use word_t in
89 /// places that are aware of this to make it perfectly explicit what is going
90 /// on.
91 using word_t = size_t;
92
93private:
94 word_t CurWord = 0;
95
96 /// This is the number of bits in CurWord that are valid. This is always from
97 /// [0...bits_of(size_t)-1] inclusive.
98 unsigned BitsInCurWord = 0;
99
100public:
101 static const constexpr size_t MaxChunkSize = sizeof(word_t) * 8;
102
103 SimpleBitstreamCursor() = default;
104 explicit SimpleBitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
105 : BitcodeBytes(BitcodeBytes) {}
106 explicit SimpleBitstreamCursor(StringRef BitcodeBytes)
107 : BitcodeBytes(arrayRefFromStringRef(BitcodeBytes)) {}
108 explicit SimpleBitstreamCursor(MemoryBufferRef BitcodeBytes)
109 : SimpleBitstreamCursor(BitcodeBytes.getBuffer()) {}
110
111 bool canSkipToPos(size_t pos) const {
112 // pos can be skipped to if it is a valid address or one byte past the end.
113 return pos <= BitcodeBytes.size();
114 }
115
116 bool AtEndOfStream() {
117 return BitsInCurWord == 0 && BitcodeBytes.size() <= NextChar;
118 }
119
120 /// Return the bit # of the bit we are reading.
121 uint64_t GetCurrentBitNo() const {
122 return NextChar*CHAR_BIT8 - BitsInCurWord;
123 }
124
125 // Return the byte # of the current bit.
126 uint64_t getCurrentByteNo() const { return GetCurrentBitNo() / 8; }
127
128 ArrayRef<uint8_t> getBitcodeBytes() const { return BitcodeBytes; }
129
130 /// Reset the stream to the specified bit number.
131 Error JumpToBit(uint64_t BitNo) {
132 size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1);
133 unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
134 assert(canSkipToPos(ByteNo) && "Invalid location")((void)0);
135
136 // Move the cursor to the right word.
137 NextChar = ByteNo;
138 BitsInCurWord = 0;
139
140 // Skip over any bits that are already consumed.
141 if (WordBitNo) {
142 if (Expected<word_t> Res = Read(WordBitNo))
143 return Error::success();
144 else
145 return Res.takeError();
146 }
147
148 return Error::success();
149 }
150
151 /// Get a pointer into the bitstream at the specified byte offset.
152 const uint8_t *getPointerToByte(uint64_t ByteNo, uint64_t NumBytes) {
153 return BitcodeBytes.data() + ByteNo;
154 }
155
156 /// Get a pointer into the bitstream at the specified bit offset.
157 ///
158 /// The bit offset must be on a byte boundary.
159 const uint8_t *getPointerToBit(uint64_t BitNo, uint64_t NumBytes) {
160 assert(!(BitNo % 8) && "Expected bit on byte boundary")((void)0);
161 return getPointerToByte(BitNo / 8, NumBytes);
162 }
163
164 Error fillCurWord() {
165 if (NextChar >= BitcodeBytes.size())
166 return createStringError(std::errc::io_error,
167 "Unexpected end of file reading %u of %u bytes",
168 NextChar, BitcodeBytes.size());
169
170 // Read the next word from the stream.
171 const uint8_t *NextCharPtr = BitcodeBytes.data() + NextChar;
172 unsigned BytesRead;
173 if (BitcodeBytes.size() >= NextChar + sizeof(word_t)) {
174 BytesRead = sizeof(word_t);
175 CurWord =
176 support::endian::read<word_t, support::little, support::unaligned>(
177 NextCharPtr);
178 } else {
179 // Short read.
180 BytesRead = BitcodeBytes.size() - NextChar;
181 CurWord = 0;
182 for (unsigned B = 0; B != BytesRead; ++B)
183 CurWord |= uint64_t(NextCharPtr[B]) << (B * 8);
184 }
185 NextChar += BytesRead;
186 BitsInCurWord = BytesRead * 8;
187 return Error::success();
188 }
189
190 Expected<word_t> Read(unsigned NumBits) {
191 static const unsigned BitsInWord = MaxChunkSize;
192
193 assert(NumBits && NumBits <= BitsInWord &&((void)0)
194 "Cannot return zero or more than BitsInWord bits!")((void)0);
195
196 static const unsigned Mask = sizeof(word_t) > 4 ? 0x3f : 0x1f;
9
'?' condition is true
197
198 // If the field is fully contained by CurWord, return it quickly.
199 if (BitsInCurWord >= NumBits) {
10
Assuming 'NumBits' is > field 'BitsInCurWord'
11
Taking false branch
200 word_t R = CurWord & (~word_t(0) >> (BitsInWord - NumBits));
201
202 // Use a mask to avoid undefined behavior.
203 CurWord >>= (NumBits & Mask);
204
205 BitsInCurWord -= NumBits;
206 return R;
207 }
208
209 word_t R = BitsInCurWord
11.1
Field 'BitsInCurWord' is not equal to 0
11.1
Field 'BitsInCurWord' is not equal to 0
11.1
Field 'BitsInCurWord' is not equal to 0
? CurWord : 0;
12
'?' condition is true
210 unsigned BitsLeft = NumBits - BitsInCurWord;
211
212 if (Error fillResult = fillCurWord())
13
Calling 'Error::operator bool'
15
Returning from 'Error::operator bool'
16
Taking false branch
213 return std::move(fillResult);
214
215 // If we run out of data, abort.
216 if (BitsLeft > BitsInCurWord)
17
Assuming 'BitsLeft' is <= field 'BitsInCurWord'
18
Taking false branch
217 return createStringError(std::errc::io_error,
218 "Unexpected end of file reading %u of %u bits",
219 BitsInCurWord, BitsLeft);
220
221 word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft));
19
The result of the right shift is undefined due to shifting by '64', which is greater or equal to the width of type 'llvm::SimpleBitstreamCursor::word_t'
222
223 // Use a mask to avoid undefined behavior.
224 CurWord >>= (BitsLeft & Mask);
225
226 BitsInCurWord -= BitsLeft;
227
228 R |= R2 << (NumBits - BitsLeft);
229
230 return R;
231 }
232
233 Expected<uint32_t> ReadVBR(unsigned NumBits) {
234 Expected<unsigned> MaybeRead = Read(NumBits);
235 if (!MaybeRead)
236 return MaybeRead;
237 uint32_t Piece = MaybeRead.get();
238
239 if ((Piece & (1U << (NumBits-1))) == 0)
240 return Piece;
241
242 uint32_t Result = 0;
243 unsigned NextBit = 0;
244 while (true) {
245 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
246
247 if ((Piece & (1U << (NumBits-1))) == 0)
248 return Result;
249
250 NextBit += NumBits-1;
251 MaybeRead = Read(NumBits);
252 if (!MaybeRead)
253 return MaybeRead;
254 Piece = MaybeRead.get();
255 }
256 }
257
258 // Read a VBR that may have a value up to 64-bits in size. The chunk size of
259 // the VBR must still be <= 32 bits though.
260 Expected<uint64_t> ReadVBR64(unsigned NumBits) {
261 Expected<uint64_t> MaybeRead = Read(NumBits);
262 if (!MaybeRead)
263 return MaybeRead;
264 uint32_t Piece = MaybeRead.get();
265
266 if ((Piece & (1U << (NumBits-1))) == 0)
267 return uint64_t(Piece);
268
269 uint64_t Result = 0;
270 unsigned NextBit = 0;
271 while (true) {
272 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
273
274 if ((Piece & (1U << (NumBits-1))) == 0)
275 return Result;
276
277 NextBit += NumBits-1;
278 MaybeRead = Read(NumBits);
279 if (!MaybeRead)
280 return MaybeRead;
281 Piece = MaybeRead.get();
282 }
283 }
284
285 void SkipToFourByteBoundary() {
286 // If word_t is 64-bits and if we've read less than 32 bits, just dump
287 // the bits we have up to the next 32-bit boundary.
288 if (sizeof(word_t) > 4 &&
289 BitsInCurWord >= 32) {
290 CurWord >>= BitsInCurWord-32;
291 BitsInCurWord = 32;
292 return;
293 }
294
295 BitsInCurWord = 0;
296 }
297
298 /// Return the size of the stream in bytes.
299 size_t SizeInBytes() const { return BitcodeBytes.size(); }
300
301 /// Skip to the end of the file.
302 void skipToEnd() { NextChar = BitcodeBytes.size(); }
303};
304
305/// When advancing through a bitstream cursor, each advance can discover a few
306/// different kinds of entries:
307struct BitstreamEntry {
308 enum {
309 Error, // Malformed bitcode was found.
310 EndBlock, // We've reached the end of the current block, (or the end of the
311 // file, which is treated like a series of EndBlock records.
312 SubBlock, // This is the start of a new subblock of a specific ID.
313 Record // This is a record with a specific AbbrevID.
314 } Kind;
315
316 unsigned ID;
317
318 static BitstreamEntry getError() {
319 BitstreamEntry E; E.Kind = Error; return E;
320 }
321
322 static BitstreamEntry getEndBlock() {
323 BitstreamEntry E; E.Kind = EndBlock; return E;
324 }
325
326 static BitstreamEntry getSubBlock(unsigned ID) {
327 BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
328 }
329
330 static BitstreamEntry getRecord(unsigned AbbrevID) {
331 BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
332 }
333};
334
335/// This represents a position within a bitcode file, implemented on top of a
336/// SimpleBitstreamCursor.
337///
338/// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
339/// be passed by value.
340class BitstreamCursor : SimpleBitstreamCursor {
341 // This is the declared size of code values used for the current block, in
342 // bits.
343 unsigned CurCodeSize = 2;
344
345 /// Abbrevs installed at in this block.
346 std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
347
348 struct Block {
349 unsigned PrevCodeSize;
350 std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
351
352 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
353 };
354
355 /// This tracks the codesize of parent blocks.
356 SmallVector<Block, 8> BlockScope;
357
358 BitstreamBlockInfo *BlockInfo = nullptr;
359
360public:
361 static const size_t MaxChunkSize = sizeof(word_t) * 8;
362
363 BitstreamCursor() = default;
364 explicit BitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
365 : SimpleBitstreamCursor(BitcodeBytes) {}
366 explicit BitstreamCursor(StringRef BitcodeBytes)
367 : SimpleBitstreamCursor(BitcodeBytes) {}
368 explicit BitstreamCursor(MemoryBufferRef BitcodeBytes)
369 : SimpleBitstreamCursor(BitcodeBytes) {}
370
371 using SimpleBitstreamCursor::AtEndOfStream;
372 using SimpleBitstreamCursor::canSkipToPos;
373 using SimpleBitstreamCursor::fillCurWord;
374 using SimpleBitstreamCursor::getBitcodeBytes;
375 using SimpleBitstreamCursor::GetCurrentBitNo;
376 using SimpleBitstreamCursor::getCurrentByteNo;
377 using SimpleBitstreamCursor::getPointerToByte;
378 using SimpleBitstreamCursor::JumpToBit;
379 using SimpleBitstreamCursor::Read;
380 using SimpleBitstreamCursor::ReadVBR;
381 using SimpleBitstreamCursor::ReadVBR64;
382 using SimpleBitstreamCursor::SizeInBytes;
383 using SimpleBitstreamCursor::skipToEnd;
384
385 /// Return the number of bits used to encode an abbrev #.
386 unsigned getAbbrevIDWidth() const { return CurCodeSize; }
387
388 /// Flags that modify the behavior of advance().
389 enum {
390 /// If this flag is used, the advance() method does not automatically pop
391 /// the block scope when the end of a block is reached.
392 AF_DontPopBlockAtEnd = 1,
393
394 /// If this flag is used, abbrev entries are returned just like normal
395 /// records.
396 AF_DontAutoprocessAbbrevs = 2
397 };
398
399 /// Advance the current bitstream, returning the next entry in the stream.
400 Expected<BitstreamEntry> advance(unsigned Flags = 0) {
401 while (true) {
5
Loop condition is true. Entering loop body
402 if (AtEndOfStream())
6
Taking false branch
403 return BitstreamEntry::getError();
404
405 Expected<unsigned> MaybeCode = ReadCode();
7
Calling 'BitstreamCursor::ReadCode'
406 if (!MaybeCode)
407 return MaybeCode.takeError();
408 unsigned Code = MaybeCode.get();
409
410 if (Code == bitc::END_BLOCK) {
411 // Pop the end of the block unless Flags tells us not to.
412 if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
413 return BitstreamEntry::getError();
414 return BitstreamEntry::getEndBlock();
415 }
416
417 if (Code == bitc::ENTER_SUBBLOCK) {
418 if (Expected<unsigned> MaybeSubBlock = ReadSubBlockID())
419 return BitstreamEntry::getSubBlock(MaybeSubBlock.get());
420 else
421 return MaybeSubBlock.takeError();
422 }
423
424 if (Code == bitc::DEFINE_ABBREV &&
425 !(Flags & AF_DontAutoprocessAbbrevs)) {
426 // We read and accumulate abbrev's, the client can't do anything with
427 // them anyway.
428 if (Error Err = ReadAbbrevRecord())
429 return std::move(Err);
430 continue;
431 }
432
433 return BitstreamEntry::getRecord(Code);
434 }
435 }
436
437 /// This is a convenience function for clients that don't expect any
438 /// subblocks. This just skips over them automatically.
439 Expected<BitstreamEntry> advanceSkippingSubblocks(unsigned Flags = 0) {
440 while (true) {
3
Loop condition is true. Entering loop body
441 // If we found a normal entry, return it.
442 Expected<BitstreamEntry> MaybeEntry = advance(Flags);
4
Calling 'BitstreamCursor::advance'
443 if (!MaybeEntry)
444 return MaybeEntry;
445 BitstreamEntry Entry = MaybeEntry.get();
446
447 if (Entry.Kind != BitstreamEntry::SubBlock)
448 return Entry;
449
450 // If we found a sub-block, just skip over it and check the next entry.
451 if (Error Err = SkipBlock())
452 return std::move(Err);
453 }
454 }
455
456 Expected<unsigned> ReadCode() { return Read(CurCodeSize); }
8
Calling 'SimpleBitstreamCursor::Read'
457
458 // Block header:
459 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
460
461 /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
462 Expected<unsigned> ReadSubBlockID() { return ReadVBR(bitc::BlockIDWidth); }
463
464 /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
465 /// of this block.
466 Error SkipBlock() {
467 // Read and ignore the codelen value.
468 if (Expected<uint32_t> Res = ReadVBR(bitc::CodeLenWidth))
469 ; // Since we are skipping this block, we don't care what code widths are
470 // used inside of it.
471 else
472 return Res.takeError();
473
474 SkipToFourByteBoundary();
475 Expected<unsigned> MaybeNum = Read(bitc::BlockSizeWidth);
476 if (!MaybeNum)
477 return MaybeNum.takeError();
478 size_t NumFourBytes = MaybeNum.get();
479
480 // Check that the block wasn't partially defined, and that the offset isn't
481 // bogus.
482 size_t SkipTo = GetCurrentBitNo() + NumFourBytes * 4 * 8;
483 if (AtEndOfStream())
484 return createStringError(std::errc::illegal_byte_sequence,
485 "can't skip block: already at end of stream");
486 if (!canSkipToPos(SkipTo / 8))
487 return createStringError(std::errc::illegal_byte_sequence,
488 "can't skip to bit %zu from %" PRIu64"llu", SkipTo,
489 GetCurrentBitNo());
490
491 if (Error Res = JumpToBit(SkipTo))
492 return Res;
493
494 return Error::success();
495 }
496
497 /// Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
498 Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
499
500 bool ReadBlockEnd() {
501 if (BlockScope.empty()) return true;
502
503 // Block tail:
504 // [END_BLOCK, <align4bytes>]
505 SkipToFourByteBoundary();
506
507 popBlockScope();
508 return false;
509 }
510
511private:
512 void popBlockScope() {
513 CurCodeSize = BlockScope.back().PrevCodeSize;
514
515 CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
516 BlockScope.pop_back();
517 }
518
519 //===--------------------------------------------------------------------===//
520 // Record Processing
521 //===--------------------------------------------------------------------===//
522
523public:
524 /// Return the abbreviation for the specified AbbrevId.
525 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
526 unsigned AbbrevNo = AbbrevID - bitc::FIRST_APPLICATION_ABBREV;
527 if (AbbrevNo >= CurAbbrevs.size())
528 report_fatal_error("Invalid abbrev number");
529 return CurAbbrevs[AbbrevNo].get();
530 }
531
532 /// Read the current record and discard it, returning the code for the record.
533 Expected<unsigned> skipRecord(unsigned AbbrevID);
534
535 Expected<unsigned> readRecord(unsigned AbbrevID,
536 SmallVectorImpl<uint64_t> &Vals,
537 StringRef *Blob = nullptr);
538
539 //===--------------------------------------------------------------------===//
540 // Abbrev Processing
541 //===--------------------------------------------------------------------===//
542 Error ReadAbbrevRecord();
543
544 /// Read and return a block info block from the bitstream. If an error was
545 /// encountered, return None.
546 ///
547 /// \param ReadBlockInfoNames Whether to read block/record name information in
548 /// the BlockInfo block. Only llvm-bcanalyzer uses this.
549 Expected<Optional<BitstreamBlockInfo>>
550 ReadBlockInfoBlock(bool ReadBlockInfoNames = false);
551
552 /// Set the block info to be used by this BitstreamCursor to interpret
553 /// abbreviated records.
554 void setBlockInfo(BitstreamBlockInfo *BI) { BlockInfo = BI; }
555};
556
557} // end llvm namespace
558
559#endif // LLVM_BITSTREAM_BITSTREAMREADER_H

/usr/src/gnu/usr.bin/clang/libclangSerialization/../../../llvm/llvm/include/llvm/Support/Error.h

1//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines an API used to report recoverable errors.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_ERROR_H
14#define LLVM_SUPPORT_ERROR_H
15
16#include "llvm-c/Error.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/Config/abi-breaking.h"
22#include "llvm/Support/AlignOf.h"
23#include "llvm/Support/Compiler.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/ErrorOr.h"
27#include "llvm/Support/Format.h"
28#include "llvm/Support/raw_ostream.h"
29#include <algorithm>
30#include <cassert>
31#include <cstdint>
32#include <cstdlib>
33#include <functional>
34#include <memory>
35#include <new>
36#include <string>
37#include <system_error>
38#include <type_traits>
39#include <utility>
40#include <vector>
41
42namespace llvm {
43
44class ErrorSuccess;
45
46/// Base class for error info classes. Do not extend this directly: Extend
47/// the ErrorInfo template subclass instead.
48class ErrorInfoBase {
49public:
50 virtual ~ErrorInfoBase() = default;
51
52 /// Print an error message to an output stream.
53 virtual void log(raw_ostream &OS) const = 0;
54
55 /// Return the error message as a string.
56 virtual std::string message() const {
57 std::string Msg;
58 raw_string_ostream OS(Msg);
59 log(OS);
60 return OS.str();
61 }
62
63 /// Convert this error to a std::error_code.
64 ///
65 /// This is a temporary crutch to enable interaction with code still
66 /// using std::error_code. It will be removed in the future.
67 virtual std::error_code convertToErrorCode() const = 0;
68
69 // Returns the class ID for this type.
70 static const void *classID() { return &ID; }
71
72 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
73 virtual const void *dynamicClassID() const = 0;
74
75 // Check whether this instance is a subclass of the class identified by
76 // ClassID.
77 virtual bool isA(const void *const ClassID) const {
78 return ClassID == classID();
79 }
80
81 // Check whether this instance is a subclass of ErrorInfoT.
82 template <typename ErrorInfoT> bool isA() const {
83 return isA(ErrorInfoT::classID());
84 }
85
86private:
87 virtual void anchor();
88
89 static char ID;
90};
91
92/// Lightweight error class with error context and mandatory checking.
93///
94/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
95/// are represented by setting the pointer to a ErrorInfoBase subclass
96/// instance containing information describing the failure. Success is
97/// represented by a null pointer value.
98///
99/// Instances of Error also contains a 'Checked' flag, which must be set
100/// before the destructor is called, otherwise the destructor will trigger a
101/// runtime error. This enforces at runtime the requirement that all Error
102/// instances be checked or returned to the caller.
103///
104/// There are two ways to set the checked flag, depending on what state the
105/// Error instance is in. For Error instances indicating success, it
106/// is sufficient to invoke the boolean conversion operator. E.g.:
107///
108/// @code{.cpp}
109/// Error foo(<...>);
110///
111/// if (auto E = foo(<...>))
112/// return E; // <- Return E if it is in the error state.
113/// // We have verified that E was in the success state. It can now be safely
114/// // destroyed.
115/// @endcode
116///
117/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
118/// without testing the return value will raise a runtime error, even if foo
119/// returns success.
120///
121/// For Error instances representing failure, you must use either the
122/// handleErrors or handleAllErrors function with a typed handler. E.g.:
123///
124/// @code{.cpp}
125/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
126/// // Custom error info.
127/// };
128///
129/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
130///
131/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
132/// auto NewE =
133/// handleErrors(E,
134/// [](const MyErrorInfo &M) {
135/// // Deal with the error.
136/// },
137/// [](std::unique_ptr<OtherError> M) -> Error {
138/// if (canHandle(*M)) {
139/// // handle error.
140/// return Error::success();
141/// }
142/// // Couldn't handle this error instance. Pass it up the stack.
143/// return Error(std::move(M));
144/// );
145/// // Note - we must check or return NewE in case any of the handlers
146/// // returned a new error.
147/// @endcode
148///
149/// The handleAllErrors function is identical to handleErrors, except
150/// that it has a void return type, and requires all errors to be handled and
151/// no new errors be returned. It prevents errors (assuming they can all be
152/// handled) from having to be bubbled all the way to the top-level.
153///
154/// *All* Error instances must be checked before destruction, even if
155/// they're moved-assigned or constructed from Success values that have already
156/// been checked. This enforces checking through all levels of the call stack.
157class LLVM_NODISCARD[[clang::warn_unused_result]] Error {
158 // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors
159 // to add to the error list. It can't rely on handleErrors for this, since
160 // handleErrors does not support ErrorList handlers.
161 friend class ErrorList;
162
163 // handleErrors needs to be able to set the Checked flag.
164 template <typename... HandlerTs>
165 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
166
167 // Expected<T> needs to be able to steal the payload when constructed from an
168 // error.
169 template <typename T> friend class Expected;
170
171 // wrap needs to be able to steal the payload.
172 friend LLVMErrorRef wrap(Error);
173
174protected:
175 /// Create a success value. Prefer using 'Error::success()' for readability
176 Error() {
177 setPtr(nullptr);
178 setChecked(false);
179 }
180
181public:
182 /// Create a success value.
183 static ErrorSuccess success();
184
185 // Errors are not copy-constructable.
186 Error(const Error &Other) = delete;
187
188 /// Move-construct an error value. The newly constructed error is considered
189 /// unchecked, even if the source error had been checked. The original error
190 /// becomes a checked Success value, regardless of its original state.
191 Error(Error &&Other) {
192 setChecked(true);
193 *this = std::move(Other);
194 }
195
196 /// Create an error value. Prefer using the 'make_error' function, but
197 /// this constructor can be useful when "re-throwing" errors from handlers.
198 Error(std::unique_ptr<ErrorInfoBase> Payload) {
199 setPtr(Payload.release());
200 setChecked(false);
201 }
202
203 // Errors are not copy-assignable.
204 Error &operator=(const Error &Other) = delete;
205
206 /// Move-assign an error value. The current error must represent success, you
207 /// you cannot overwrite an unhandled error. The current error is then
208 /// considered unchecked. The source error becomes a checked success value,
209 /// regardless of its original state.
210 Error &operator=(Error &&Other) {
211 // Don't allow overwriting of unchecked values.
212 assertIsChecked();
213 setPtr(Other.getPtr());
214
215 // This Error is unchecked, even if the source error was checked.
216 setChecked(false);
217
218 // Null out Other's payload and set its checked bit.
219 Other.setPtr(nullptr);
220 Other.setChecked(true);
221
222 return *this;
223 }
224
225 /// Destroy a Error. Fails with a call to abort() if the error is
226 /// unchecked.
227 ~Error() {
228 assertIsChecked();
229 delete getPtr();
230 }
231
232 /// Bool conversion. Returns true if this Error is in a failure state,
233 /// and false if it is in an accept state. If the error is in a Success state
234 /// it will be considered checked.
235 explicit operator bool() {
236 setChecked(getPtr() == nullptr);
237 return getPtr() != nullptr;
14
Returning zero, which participates in a condition later
238 }
239
240 /// Check whether one error is a subclass of another.
241 template <typename ErrT> bool isA() const {
242 return getPtr() && getPtr()->isA(ErrT::classID());
243 }
244
245 /// Returns the dynamic class id of this error, or null if this is a success
246 /// value.
247 const void* dynamicClassID() const {
248 if (!getPtr())
249 return nullptr;
250 return getPtr()->dynamicClassID();
251 }
252
253private:
254#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
255 // assertIsChecked() happens very frequently, but under normal circumstances
256 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
257 // of debug prints can cause the function to be too large for inlining. So
258 // it's important that we define this function out of line so that it can't be
259 // inlined.
260 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
261 void fatalUncheckedError() const;
262#endif
263
264 void assertIsChecked() {
265#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
266 if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false))
267 fatalUncheckedError();
268#endif
269 }
270
271 ErrorInfoBase *getPtr() const {
272#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
273 return reinterpret_cast<ErrorInfoBase*>(
274 reinterpret_cast<uintptr_t>(Payload) &
275 ~static_cast<uintptr_t>(0x1));
276#else
277 return Payload;
278#endif
279 }
280
281 void setPtr(ErrorInfoBase *EI) {
282#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
283 Payload = reinterpret_cast<ErrorInfoBase*>(
284 (reinterpret_cast<uintptr_t>(EI) &
285 ~static_cast<uintptr_t>(0x1)) |
286 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
287#else
288 Payload = EI;
289#endif
290 }
291
292 bool getChecked() const {
293#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
294 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
295#else
296 return true;
297#endif
298 }
299
300 void setChecked(bool V) {
301#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
302 Payload = reinterpret_cast<ErrorInfoBase*>(
303 (reinterpret_cast<uintptr_t>(Payload) &
304 ~static_cast<uintptr_t>(0x1)) |
305 (V ? 0 : 1));
306#endif
307 }
308
309 std::unique_ptr<ErrorInfoBase> takePayload() {
310 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
311 setPtr(nullptr);
312 setChecked(true);
313 return Tmp;
314 }
315
316 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
317 if (auto P = E.getPtr())
318 P->log(OS);
319 else
320 OS << "success";
321 return OS;
322 }
323
324 ErrorInfoBase *Payload = nullptr;
325};
326
327/// Subclass of Error for the sole purpose of identifying the success path in
328/// the type system. This allows to catch invalid conversion to Expected<T> at
329/// compile time.
330class ErrorSuccess final : public Error {};
331
332inline ErrorSuccess Error::success() { return ErrorSuccess(); }
333
334/// Make a Error instance representing failure using the given error info
335/// type.
336template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
337 return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
338}
339
340/// Base class for user error types. Users should declare their error types
341/// like:
342///
343/// class MyError : public ErrorInfo<MyError> {
344/// ....
345/// };
346///
347/// This class provides an implementation of the ErrorInfoBase::kind
348/// method, which is used by the Error RTTI system.
349template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
350class ErrorInfo : public ParentErrT {
351public:
352 using ParentErrT::ParentErrT; // inherit constructors
353
354 static const void *classID() { return &ThisErrT::ID; }
355
356 const void *dynamicClassID() const override { return &ThisErrT::ID; }
357
358 bool isA(const void *const ClassID) const override {
359 return ClassID == classID() || ParentErrT::isA(ClassID);
360 }
361};
362
363/// Special ErrorInfo subclass representing a list of ErrorInfos.
364/// Instances of this class are constructed by joinError.
365class ErrorList final : public ErrorInfo<ErrorList> {
366 // handleErrors needs to be able to iterate the payload list of an
367 // ErrorList.
368 template <typename... HandlerTs>
369 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
370
371 // joinErrors is implemented in terms of join.
372 friend Error joinErrors(Error, Error);
373
374public:
375 void log(raw_ostream &OS) const override {
376 OS << "Multiple errors:\n";
377 for (auto &ErrPayload : Payloads) {
378 ErrPayload->log(OS);
379 OS << "\n";
380 }
381 }
382
383 std::error_code convertToErrorCode() const override;
384
385 // Used by ErrorInfo::classID.
386 static char ID;
387
388private:
389 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
390 std::unique_ptr<ErrorInfoBase> Payload2) {
391 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((void)0)
392 "ErrorList constructor payloads should be singleton errors")((void)0);
393 Payloads.push_back(std::move(Payload1));
394 Payloads.push_back(std::move(Payload2));
395 }
396
397 static Error join(Error E1, Error E2) {
398 if (!E1)
399 return E2;
400 if (!E2)
401 return E1;
402 if (E1.isA<ErrorList>()) {
403 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
404 if (E2.isA<ErrorList>()) {
405 auto E2Payload = E2.takePayload();
406 auto &E2List = static_cast<ErrorList &>(*E2Payload);
407 for (auto &Payload : E2List.Payloads)
408 E1List.Payloads.push_back(std::move(Payload));
409 } else
410 E1List.Payloads.push_back(E2.takePayload());
411
412 return E1;
413 }
414 if (E2.isA<ErrorList>()) {
415 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
416 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
417 return E2;
418 }
419 return Error(std::unique_ptr<ErrorList>(
420 new ErrorList(E1.takePayload(), E2.takePayload())));
421 }
422
423 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
424};
425
426/// Concatenate errors. The resulting Error is unchecked, and contains the
427/// ErrorInfo(s), if any, contained in E1, followed by the
428/// ErrorInfo(s), if any, contained in E2.
429inline Error joinErrors(Error E1, Error E2) {
430 return ErrorList::join(std::move(E1), std::move(E2));
431}
432
433/// Tagged union holding either a T or a Error.
434///
435/// This class parallels ErrorOr, but replaces error_code with Error. Since
436/// Error cannot be copied, this class replaces getError() with
437/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
438/// error class type.
439///
440/// Example usage of 'Expected<T>' as a function return type:
441///
442/// @code{.cpp}
443/// Expected<int> myDivide(int A, int B) {
444/// if (B == 0) {
445/// // return an Error
446/// return createStringError(inconvertibleErrorCode(),
447/// "B must not be zero!");
448/// }
449/// // return an integer
450/// return A / B;
451/// }
452/// @endcode
453///
454/// Checking the results of to a function returning 'Expected<T>':
455/// @code{.cpp}
456/// if (auto E = Result.takeError()) {
457/// // We must consume the error. Typically one of:
458/// // - return the error to our caller
459/// // - toString(), when logging
460/// // - consumeError(), to silently swallow the error
461/// // - handleErrors(), to distinguish error types
462/// errs() << "Problem with division " << toString(std::move(E)) << "\n";
463/// return;
464/// }
465/// // use the result
466/// outs() << "The answer is " << *Result << "\n";
467/// @endcode
468///
469/// For unit-testing a function returning an 'Expceted<T>', see the
470/// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h
471
472template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected {
473 template <class T1> friend class ExpectedAsOutParameter;
474 template <class OtherT> friend class Expected;
475
476 static constexpr bool isRef = std::is_reference<T>::value;
477
478 using wrap = std::reference_wrapper<std::remove_reference_t<T>>;
479
480 using error_type = std::unique_ptr<ErrorInfoBase>;
481
482public:
483 using storage_type = std::conditional_t<isRef, wrap, T>;
484 using value_type = T;
485
486private:
487 using reference = std::remove_reference_t<T> &;
488 using const_reference = const std::remove_reference_t<T> &;
489 using pointer = std::remove_reference_t<T> *;
490 using const_pointer = const std::remove_reference_t<T> *;
491
492public:
493 /// Create an Expected<T> error value from the given Error.
494 Expected(Error Err)
495 : HasError(true)
496#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
497 // Expected is unchecked upon construction in Debug builds.
498 , Unchecked(true)
499#endif
500 {
501 assert(Err && "Cannot create Expected<T> from Error success value.")((void)0);
502 new (getErrorStorage()) error_type(Err.takePayload());
503 }
504
505 /// Forbid to convert from Error::success() implicitly, this avoids having
506 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
507 /// but triggers the assertion above.
508 Expected(ErrorSuccess) = delete;
509
510 /// Create an Expected<T> success value from the given OtherT value, which
511 /// must be convertible to T.
512 template <typename OtherT>
513 Expected(OtherT &&Val,
514 std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr)
515 : HasError(false)
516#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
517 // Expected is unchecked upon construction in Debug builds.
518 ,
519 Unchecked(true)
520#endif
521 {
522 new (getStorage()) storage_type(std::forward<OtherT>(Val));
523 }
524
525 /// Move construct an Expected<T> value.
526 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
527
528 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
529 /// must be convertible to T.
530 template <class OtherT>
531 Expected(
532 Expected<OtherT> &&Other,
533 std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) {
534 moveConstruct(std::move(Other));
535 }
536
537 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
538 /// isn't convertible to T.
539 template <class OtherT>
540 explicit Expected(
541 Expected<OtherT> &&Other,
542 std::enable_if_t<!std::is_convertible<OtherT, T>::value> * = nullptr) {
543 moveConstruct(std::move(Other));
544 }
545
546 /// Move-assign from another Expected<T>.
547 Expected &operator=(Expected &&Other) {
548 moveAssign(std::move(Other));
549 return *this;
550 }
551
552 /// Destroy an Expected<T>.
553 ~Expected() {
554 assertIsChecked();
555 if (!HasError)
556 getStorage()->~storage_type();
557 else
558 getErrorStorage()->~error_type();
559 }
560
561 /// Return false if there is an error.
562 explicit operator bool() {
563#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
564 Unchecked = HasError;
565#endif
566 return !HasError;
567 }
568
569 /// Returns a reference to the stored T value.
570 reference get() {
571 assertIsChecked();
572 return *getStorage();
573 }
574
575 /// Returns a const reference to the stored T value.
576 const_reference get() const {
577 assertIsChecked();
578 return const_cast<Expected<T> *>(this)->get();
579 }
580
581 /// Check that this Expected<T> is an error of type ErrT.
582 template <typename ErrT> bool errorIsA() const {
583 return HasError && (*getErrorStorage())->template isA<ErrT>();
584 }
585
586 /// Take ownership of the stored error.
587 /// After calling this the Expected<T> is in an indeterminate state that can
588 /// only be safely destructed. No further calls (beside the destructor) should
589 /// be made on the Expected<T> value.
590 Error takeError() {
591#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
592 Unchecked = false;
593#endif
594 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
595 }
596
597 /// Returns a pointer to the stored T value.
598 pointer operator->() {
599 assertIsChecked();
600 return toPointer(getStorage());
601 }
602
603 /// Returns a const pointer to the stored T value.
604 const_pointer operator->() const {
605 assertIsChecked();
606 return toPointer(getStorage());
607 }
608
609 /// Returns a reference to the stored T value.
610 reference operator*() {
611 assertIsChecked();
612 return *getStorage();
613 }
614
615 /// Returns a const reference to the stored T value.
616 const_reference operator*() const {
617 assertIsChecked();
618 return *getStorage();
619 }
620
621private:
622 template <class T1>
623 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
624 return &a == &b;
625 }
626
627 template <class T1, class T2>
628 static bool compareThisIfSameType(const T1 &, const T2 &) {
629 return false;
630 }
631
632 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
633 HasError = Other.HasError;
634#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
635 Unchecked = true;
636 Other.Unchecked = false;
637#endif
638
639 if (!HasError)
640 new (getStorage()) storage_type(std::move(*Other.getStorage()));
641 else
642 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
643 }
644
645 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
646 assertIsChecked();
647
648 if (compareThisIfSameType(*this, Other))
649 return;
650
651 this->~Expected();
652 new (this) Expected(std::move(Other));
653 }
654
655 pointer toPointer(pointer Val) { return Val; }
656
657 const_pointer toPointer(const_pointer Val) const { return Val; }
658
659 pointer toPointer(wrap *Val) { return &Val->get(); }
660
661 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
662
663 storage_type *getStorage() {
664 assert(!HasError && "Cannot get value when an error exists!")((void)0);
665 return reinterpret_cast<storage_type *>(&TStorage);
666 }
667
668 const storage_type *getStorage() const {
669 assert(!HasError && "Cannot get value when an error exists!")((void)0);
670 return reinterpret_cast<const storage_type *>(&TStorage);
671 }
672
673 error_type *getErrorStorage() {
674 assert(HasError && "Cannot get error when a value exists!")((void)0);
675 return reinterpret_cast<error_type *>(&ErrorStorage);
676 }
677
678 const error_type *getErrorStorage() const {
679 assert(HasError && "Cannot get error when a value exists!")((void)0);
680 return reinterpret_cast<const error_type *>(&ErrorStorage);
681 }
682
683 // Used by ExpectedAsOutParameter to reset the checked flag.
684 void setUnchecked() {
685#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
686 Unchecked = true;
687#endif
688 }
689
690#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
691 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
692 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline))
693 void fatalUncheckedExpected() const {
694 dbgs() << "Expected<T> must be checked before access or destruction.\n";
695 if (HasError) {
696 dbgs() << "Unchecked Expected<T> contained error:\n";
697 (*getErrorStorage())->log(dbgs());
698 } else
699 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
700 "values in success mode must still be checked prior to being "
701 "destroyed).\n";
702 abort();
703 }
704#endif
705
706 void assertIsChecked() const {
707#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
708 if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false))
709 fatalUncheckedExpected();
710#endif
711 }
712
713 union {
714 AlignedCharArrayUnion<storage_type> TStorage;
715 AlignedCharArrayUnion<error_type> ErrorStorage;
716 };
717 bool HasError : 1;
718#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
719 bool Unchecked : 1;
720#endif
721};
722
723/// Report a serious error, calling any installed error handler. See
724/// ErrorHandling.h.
725LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err,
726 bool gen_crash_diag = true);
727
728/// Report a fatal error if Err is a failure value.
729///
730/// This function can be used to wrap calls to fallible functions ONLY when it
731/// is known that the Error will always be a success value. E.g.
732///
733/// @code{.cpp}
734/// // foo only attempts the fallible operation if DoFallibleOperation is
735/// // true. If DoFallibleOperation is false then foo always returns
736/// // Error::success().
737/// Error foo(bool DoFallibleOperation);
738///
739/// cantFail(foo(false));
740/// @endcode
741inline void cantFail(Error Err, const char *Msg = nullptr) {
742 if (Err) {
743 if (!Msg)
744 Msg = "Failure value returned from cantFail wrapped call";
745#ifndef NDEBUG1
746 std::string Str;
747 raw_string_ostream OS(Str);
748 OS << Msg << "\n" << Err;
749 Msg = OS.str().c_str();
750#endif
751 llvm_unreachable(Msg)__builtin_unreachable();
752 }
753}
754
755/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
756/// returns the contained value.
757///
758/// This function can be used to wrap calls to fallible functions ONLY when it
759/// is known that the Error will always be a success value. E.g.
760///
761/// @code{.cpp}
762/// // foo only attempts the fallible operation if DoFallibleOperation is
763/// // true. If DoFallibleOperation is false then foo always returns an int.
764/// Expected<int> foo(bool DoFallibleOperation);
765///
766/// int X = cantFail(foo(false));
767/// @endcode
768template <typename T>
769T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
770 if (ValOrErr)
771 return std::move(*ValOrErr);
772 else {
773 if (!Msg)
774 Msg = "Failure value returned from cantFail wrapped call";
775#ifndef NDEBUG1
776 std::string Str;
777 raw_string_ostream OS(Str);
778 auto E = ValOrErr.takeError();
779 OS << Msg << "\n" << E;
780 Msg = OS.str().c_str();
781#endif
782 llvm_unreachable(Msg)__builtin_unreachable();
783 }
784}
785
786/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
787/// returns the contained reference.
788///
789/// This function can be used to wrap calls to fallible functions ONLY when it
790/// is known that the Error will always be a success value. E.g.
791///
792/// @code{.cpp}
793/// // foo only attempts the fallible operation if DoFallibleOperation is
794/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
795/// Expected<Bar&> foo(bool DoFallibleOperation);
796///
797/// Bar &X = cantFail(foo(false));
798/// @endcode
799template <typename T>
800T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
801 if (ValOrErr)
802 return *ValOrErr;
803 else {
804 if (!Msg)
805 Msg = "Failure value returned from cantFail wrapped call";
806#ifndef NDEBUG1
807 std::string Str;
808 raw_string_ostream OS(Str);
809 auto E = ValOrErr.takeError();
810 OS << Msg << "\n" << E;
811 Msg = OS.str().c_str();
812#endif
813 llvm_unreachable(Msg)__builtin_unreachable();
814 }
815}
816
817/// Helper for testing applicability of, and applying, handlers for
818/// ErrorInfo types.
819template <typename HandlerT>
820class ErrorHandlerTraits
821 : public ErrorHandlerTraits<decltype(
822 &std::remove_reference<HandlerT>::type::operator())> {};
823
824// Specialization functions of the form 'Error (const ErrT&)'.
825template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
826public:
827 static bool appliesTo(const ErrorInfoBase &E) {
828 return E.template isA<ErrT>();
829 }
830
831 template <typename HandlerT>
832 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
833 assert(appliesTo(*E) && "Applying incorrect handler")((void)0);
834 return H(static_cast<ErrT &>(*E));
835 }
836};
837
838// Specialization functions of the form 'void (const ErrT&)'.
839template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
840public:
841 static bool appliesTo(const ErrorInfoBase &E) {
842 return E.template isA<ErrT>();
843 }
844
845 template <typename HandlerT>
846 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
847 assert(appliesTo(*E) && "Applying incorrect handler")((void)0);
848 H(static_cast<ErrT &>(*E));
849 return Error::success();
850 }
851};
852
853/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
854template <typename ErrT>
855class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
856public:
857 static bool appliesTo(const ErrorInfoBase &E) {
858 return E.template isA<ErrT>();
859 }
860
861 template <typename HandlerT>
862 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
863 assert(appliesTo(*E) && "Applying incorrect handler")((void)0);
864 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
865 return H(std::move(SubE));
866 }
867};
868
869/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
870template <typename ErrT>
871class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
872public:
873 static bool appliesTo(const ErrorInfoBase &E) {
874 return E.template isA<ErrT>();
875 }
876
877 template <typename HandlerT>
878 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
879 assert(appliesTo(*E) && "Applying incorrect handler")((void)0);
880 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
881 H(std::move(SubE));
882 return Error::success();
883 }
884};
885
886// Specialization for member functions of the form 'RetT (const ErrT&)'.
887template <typename C, typename RetT, typename ErrT>
888class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
889 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
890
891// Specialization for member functions of the form 'RetT (const ErrT&) const'.
892template <typename C, typename RetT, typename ErrT>
893class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
894 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
895
896// Specialization for member functions of the form 'RetT (const ErrT&)'.
897template <typename C, typename RetT, typename ErrT>
898class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
899 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
900
901// Specialization for member functions of the form 'RetT (const ErrT&) const'.
902template <typename C, typename RetT, typename ErrT>
903class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
904 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
905
906/// Specialization for member functions of the form
907/// 'RetT (std::unique_ptr<ErrT>)'.
908template <typename C, typename RetT, typename ErrT>
909class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
910 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
911
912/// Specialization for member functions of the form
913/// 'RetT (std::unique_ptr<ErrT>) const'.
914template <typename C, typename RetT, typename ErrT>
915class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
916 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
917
918inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
919 return Error(std::move(Payload));
920}
921
922template <typename HandlerT, typename... HandlerTs>
923Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
924 HandlerT &&Handler, HandlerTs &&... Handlers) {
925 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
926 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
927 std::move(Payload));
928 return handleErrorImpl(std::move(Payload),
929 std::forward<HandlerTs>(Handlers)...);
930}
931
932/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
933/// unhandled errors (or Errors returned by handlers) are re-concatenated and
934/// returned.
935/// Because this function returns an error, its result must also be checked
936/// or returned. If you intend to handle all errors use handleAllErrors
937/// (which returns void, and will abort() on unhandled errors) instead.
938template <typename... HandlerTs>
939Error handleErrors(Error E, HandlerTs &&... Hs) {
940 if (!E)
941 return Error::success();
942
943 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
944
945 if (Payload->isA<ErrorList>()) {
946 ErrorList &List = static_cast<ErrorList &>(*Payload);
947 Error R;
948 for (auto &P : List.Payloads)
949 R = ErrorList::join(
950 std::move(R),
951 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
952 return R;
953 }
954
955 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
956}
957
958/// Behaves the same as handleErrors, except that by contract all errors
959/// *must* be handled by the given handlers (i.e. there must be no remaining
960/// errors after running the handlers, or llvm_unreachable is called).
961template <typename... HandlerTs>
962void handleAllErrors(Error E, HandlerTs &&... Handlers) {
963 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
964}
965
966/// Check that E is a non-error, then drop it.
967/// If E is an error, llvm_unreachable will be called.
968inline void handleAllErrors(Error E) {
969 cantFail(std::move(E));
970}
971
972/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
973///
974/// If the incoming value is a success value it is returned unmodified. If it
975/// is a failure value then it the contained error is passed to handleErrors.
976/// If handleErrors is able to handle the error then the RecoveryPath functor
977/// is called to supply the final result. If handleErrors is not able to
978/// handle all errors then the unhandled errors are returned.
979///
980/// This utility enables the follow pattern:
981///
982/// @code{.cpp}
983/// enum FooStrategy { Aggressive, Conservative };
984/// Expected<Foo> foo(FooStrategy S);
985///
986/// auto ResultOrErr =
987/// handleExpected(
988/// foo(Aggressive),
989/// []() { return foo(Conservative); },
990/// [](AggressiveStrategyError&) {
991/// // Implicitly conusme this - we'll recover by using a conservative
992/// // strategy.
993/// });
994///
995/// @endcode
996template <typename T, typename RecoveryFtor, typename... HandlerTs>
997Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
998 HandlerTs &&... Handlers) {
999 if (ValOrErr)
1000 return ValOrErr;
1001
1002 if (auto Err = handleErrors(ValOrErr.takeError(),
1003 std::forward<HandlerTs>(Handlers)...))
1004 return std::move(Err);
1005
1006 return RecoveryPath();
1007}
1008
1009/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
1010/// will be printed before the first one is logged. A newline will be printed
1011/// after each error.
1012///
1013/// This function is compatible with the helpers from Support/WithColor.h. You
1014/// can pass any of them as the OS. Please consider using them instead of
1015/// including 'error: ' in the ErrorBanner.
1016///
1017/// This is useful in the base level of your program to allow clean termination
1018/// (allowing clean deallocation of resources, etc.), while reporting error
1019/// information to the user.
1020void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {});
1021
1022/// Write all error messages (if any) in E to a string. The newline character
1023/// is used to separate error messages.
1024inline std::string toString(Error E) {
1025 SmallVector<std::string, 2> Errors;
1026 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
1027 Errors.push_back(EI.message());
1028 });
1029 return join(Errors.begin(), Errors.end(), "\n");
1030}
1031
1032/// Consume a Error without doing anything. This method should be used
1033/// only where an error can be considered a reasonable and expected return
1034/// value.
1035///
1036/// Uses of this method are potentially indicative of design problems: If it's
1037/// legitimate to do nothing while processing an "error", the error-producer
1038/// might be more clearly refactored to return an Optional<T>.
1039inline void consumeError(Error Err) {
1040 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
1041}
1042
1043/// Convert an Expected to an Optional without doing anything. This method
1044/// should be used only where an error can be considered a reasonable and
1045/// expected return value.
1046///
1047/// Uses of this method are potentially indicative of problems: perhaps the
1048/// error should be propagated further, or the error-producer should just
1049/// return an Optional in the first place.
1050template <typename T> Optional<T> expectedToOptional(Expected<T> &&E) {
1051 if (E)
1052 return std::move(*E);
1053 consumeError(E.takeError());
1054 return None;
1055}
1056
1057/// Helper for converting an Error to a bool.
1058///
1059/// This method returns true if Err is in an error state, or false if it is
1060/// in a success state. Puts Err in a checked state in both cases (unlike
1061/// Error::operator bool(), which only does this for success states).
1062inline bool errorToBool(Error Err) {
1063 bool IsError = static_cast<bool>(Err);
1064 if (IsError)
1065 consumeError(std::move(Err));
1066 return IsError;
1067}
1068
1069/// Helper for Errors used as out-parameters.
1070///
1071/// This helper is for use with the Error-as-out-parameter idiom, where an error
1072/// is passed to a function or method by reference, rather than being returned.
1073/// In such cases it is helpful to set the checked bit on entry to the function
1074/// so that the error can be written to (unchecked Errors abort on assignment)
1075/// and clear the checked bit on exit so that clients cannot accidentally forget
1076/// to check the result. This helper performs these actions automatically using
1077/// RAII:
1078///
1079/// @code{.cpp}
1080/// Result foo(Error &Err) {
1081/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1082/// // <body of foo>
1083/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1084/// }
1085/// @endcode
1086///
1087/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1088/// used with optional Errors (Error pointers that are allowed to be null). If
1089/// ErrorAsOutParameter took an Error reference, an instance would have to be
1090/// created inside every condition that verified that Error was non-null. By
1091/// taking an Error pointer we can just create one instance at the top of the
1092/// function.
1093class ErrorAsOutParameter {
1094public:
1095 ErrorAsOutParameter(Error *Err) : Err(Err) {
1096 // Raise the checked bit if Err is success.
1097 if (Err)
1098 (void)!!*Err;
1099 }
1100
1101 ~ErrorAsOutParameter() {
1102 // Clear the checked bit.
1103 if (Err && !*Err)
1104 *Err = Error::success();
1105 }
1106
1107private:
1108 Error *Err;
1109};
1110
1111/// Helper for Expected<T>s used as out-parameters.
1112///
1113/// See ErrorAsOutParameter.
1114template <typename T>
1115class ExpectedAsOutParameter {
1116public:
1117 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1118 : ValOrErr(ValOrErr) {
1119 if (ValOrErr)
1120 (void)!!*ValOrErr;
1121 }
1122
1123 ~ExpectedAsOutParameter() {
1124 if (ValOrErr)
1125 ValOrErr->setUnchecked();
1126 }
1127
1128private:
1129 Expected<T> *ValOrErr;
1130};
1131
1132/// This class wraps a std::error_code in a Error.
1133///
1134/// This is useful if you're writing an interface that returns a Error
1135/// (or Expected) and you want to call code that still returns
1136/// std::error_codes.
1137class ECError : public ErrorInfo<ECError> {
1138 friend Error errorCodeToError(std::error_code);
1139
1140 virtual void anchor() override;
1141
1142public:
1143 void setErrorCode(std::error_code EC) { this->EC = EC; }
1144 std::error_code convertToErrorCode() const override { return EC; }
1145 void log(raw_ostream &OS) const override { OS << EC.message(); }
1146
1147 // Used by ErrorInfo::classID.
1148 static char ID;
1149
1150protected:
1151 ECError() = default;
1152 ECError(std::error_code EC) : EC(EC) {}
1153
1154 std::error_code EC;
1155};
1156
1157/// The value returned by this function can be returned from convertToErrorCode
1158/// for Error values where no sensible translation to std::error_code exists.
1159/// It should only be used in this situation, and should never be used where a
1160/// sensible conversion to std::error_code is available, as attempts to convert
1161/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1162///error to try to convert such a value).
1163std::error_code inconvertibleErrorCode();
1164
1165/// Helper for converting an std::error_code to a Error.
1166Error errorCodeToError(std::error_code EC);
1167
1168/// Helper for converting an ECError to a std::error_code.
1169///
1170/// This method requires that Err be Error() or an ECError, otherwise it
1171/// will trigger a call to abort().
1172std::error_code errorToErrorCode(Error Err);
1173
1174/// Convert an ErrorOr<T> to an Expected<T>.
1175template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1176 if (auto EC = EO.getError())
1177 return errorCodeToError(EC);
1178 return std::move(*EO);
1179}
1180
1181/// Convert an Expected<T> to an ErrorOr<T>.
1182template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1183 if (auto Err = E.takeError())
1184 return errorToErrorCode(std::move(Err));
1185 return std::move(*E);
1186}
1187
1188/// This class wraps a string in an Error.
1189///
1190/// StringError is useful in cases where the client is not expected to be able
1191/// to consume the specific error message programmatically (for example, if the
1192/// error message is to be presented to the user).
1193///
1194/// StringError can also be used when additional information is to be printed
1195/// along with a error_code message. Depending on the constructor called, this
1196/// class can either display:
1197/// 1. the error_code message (ECError behavior)
1198/// 2. a string
1199/// 3. the error_code message and a string
1200///
1201/// These behaviors are useful when subtyping is required; for example, when a
1202/// specific library needs an explicit error type. In the example below,
1203/// PDBError is derived from StringError:
1204///
1205/// @code{.cpp}
1206/// Expected<int> foo() {
1207/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1208/// "Additional information");
1209/// }
1210/// @endcode
1211///
1212class StringError : public ErrorInfo<StringError> {
1213public:
1214 static char ID;
1215
1216 // Prints EC + S and converts to EC
1217 StringError(std::error_code EC, const Twine &S = Twine());
1218
1219 // Prints S and converts to EC
1220 StringError(const Twine &S, std::error_code EC);
1221
1222 void log(raw_ostream &OS) const override;
1223 std::error_code convertToErrorCode() const override;
1224
1225 const std::string &getMessage() const { return Msg; }
1226
1227private:
1228 std::string Msg;
1229 std::error_code EC;
1230 const bool PrintMsgOnly = false;
1231};
1232
1233/// Create formatted StringError object.
1234template <typename... Ts>
1235inline Error createStringError(std::error_code EC, char const *Fmt,
1236 const Ts &... Vals) {
1237 std::string Buffer;
1238 raw_string_ostream Stream(Buffer);
1239 Stream << format(Fmt, Vals...);
1240 return make_error<StringError>(Stream.str(), EC);
1241}
1242
1243Error createStringError(std::error_code EC, char const *Msg);
1244
1245inline Error createStringError(std::error_code EC, const Twine &S) {
1246 return createStringError(EC, S.str().c_str());
1247}
1248
1249template <typename... Ts>
1250inline Error createStringError(std::errc EC, char const *Fmt,
1251 const Ts &... Vals) {
1252 return createStringError(std::make_error_code(EC), Fmt, Vals...);
1253}
1254
1255/// This class wraps a filename and another Error.
1256///
1257/// In some cases, an error needs to live along a 'source' name, in order to
1258/// show more detailed information to the user.
1259class FileError final : public ErrorInfo<FileError> {
1260
1261 friend Error createFileError(const Twine &, Error);
1262 friend Error createFileError(const Twine &, size_t, Error);
1263
1264public:
1265 void log(raw_ostream &OS) const override {
1266 assert(Err && !FileName.empty() && "Trying to log after takeError().")((void)0);
1267 OS << "'" << FileName << "': ";
1268 if (Line.hasValue())
1269 OS << "line " << Line.getValue() << ": ";
1270 Err->log(OS);
1271 }
1272
1273 StringRef getFileName() { return FileName; }
1274
1275 Error takeError() { return Error(std::move(Err)); }
1276
1277 std::error_code convertToErrorCode() const override;
1278
1279 // Used by ErrorInfo::classID.
1280 static char ID;
1281
1282private:
1283 FileError(const Twine &F, Optional<size_t> LineNum,
1284 std::unique_ptr<ErrorInfoBase> E) {
1285 assert(E && "Cannot create FileError from Error success value.")((void)0);
1286 assert(!F.isTriviallyEmpty() &&((void)0)
1287 "The file name provided to FileError must not be empty.")((void)0);
1288 FileName = F.str();
1289 Err = std::move(E);
1290 Line = std::move(LineNum);
1291 }
1292
1293 static Error build(const Twine &F, Optional<size_t> Line, Error E) {
1294 std::unique_ptr<ErrorInfoBase> Payload;
1295 handleAllErrors(std::move(E),
1296 [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error {
1297 Payload = std::move(EIB);
1298 return Error::success();
1299 });
1300 return Error(
1301 std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload))));
1302 }
1303
1304 std::string FileName;
1305 Optional<size_t> Line;
1306 std::unique_ptr<ErrorInfoBase> Err;
1307};
1308
1309/// Concatenate a source file path and/or name with an Error. The resulting
1310/// Error is unchecked.
1311inline Error createFileError(const Twine &F, Error E) {
1312 return FileError::build(F, Optional<size_t>(), std::move(E));
1313}
1314
1315/// Concatenate a source file path and/or name with line number and an Error.
1316/// The resulting Error is unchecked.
1317inline Error createFileError(const Twine &F, size_t Line, Error E) {
1318 return FileError::build(F, Optional<size_t>(Line), std::move(E));
1319}
1320
1321/// Concatenate a source file path and/or name with a std::error_code
1322/// to form an Error object.
1323inline Error createFileError(const Twine &F, std::error_code EC) {
1324 return createFileError(F, errorCodeToError(EC));
1325}
1326
1327/// Concatenate a source file path and/or name with line number and
1328/// std::error_code to form an Error object.
1329inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
1330 return createFileError(F, Line, errorCodeToError(EC));
1331}
1332
1333Error createFileError(const Twine &F, ErrorSuccess) = delete;
1334
1335/// Helper for check-and-exit error handling.
1336///
1337/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1338///
1339class ExitOnError {
1340public:
1341 /// Create an error on exit helper.
1342 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1343 : Banner(std::move(Banner)),
1344 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1345
1346 /// Set the banner string for any errors caught by operator().
1347 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1348
1349 /// Set the exit-code mapper function.
1350 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1351 this->GetExitCode = std::move(GetExitCode);
1352 }
1353
1354 /// Check Err. If it's in a failure state log the error(s) and exit.
1355 void operator()(Error Err) const { checkError(std::move(Err)); }
1356
1357 /// Check E. If it's in a success state then return the contained value. If
1358 /// it's in a failure state log the error(s) and exit.
1359 template <typename T> T operator()(Expected<T> &&E) const {
1360 checkError(E.takeError());
1361 return std::move(*E);
1362 }
1363
1364 /// Check E. If it's in a success state then return the contained reference. If
1365 /// it's in a failure state log the error(s) and exit.
1366 template <typename T> T& operator()(Expected<T&> &&E) const {
1367 checkError(E.takeError());
1368 return *E;
1369 }
1370
1371private:
1372 void checkError(Error Err) const {
1373 if (Err) {
1374 int ExitCode = GetExitCode(Err);
1375 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1376 exit(ExitCode);
1377 }
1378 }
1379
1380 std::string Banner;
1381 std::function<int(const Error &)> GetExitCode;
1382};
1383
1384/// Conversion from Error to LLVMErrorRef for C error bindings.
1385inline LLVMErrorRef wrap(Error Err) {
1386 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1387}
1388
1389/// Conversion from LLVMErrorRef to Error for C error bindings.
1390inline Error unwrap(LLVMErrorRef ErrRef) {
1391 return Error(std::unique_ptr<ErrorInfoBase>(
1392 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1393}
1394
1395} // end namespace llvm
1396
1397#endif // LLVM_SUPPORT_ERROR_H