Bug Summary

File:tools/clang/lib/Analysis/BodyFarm.cpp
Warning:line 141, column 19
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name BodyFarm.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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn358860/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/tools/clang/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn358860=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-04-22-050718-5320-1 -x c++ /build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Analysis/BodyFarm.cpp -faddrsig

/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Analysis/BodyFarm.cpp

1//== BodyFarm.cpp - Factory for conjuring up fake bodies ----------*- 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// BodyFarm is a factory for creating faux implementations for functions/methods
10// for analysis purposes.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Analysis/BodyFarm.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/Analysis/CodeInjector.h"
23#include "clang/Basic/OperatorKinds.h"
24#include "llvm/ADT/StringSwitch.h"
25#include "llvm/Support/Debug.h"
26
27#define DEBUG_TYPE"body-farm" "body-farm"
28
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Helper creation functions for constructing faux ASTs.
33//===----------------------------------------------------------------------===//
34
35static bool isDispatchBlock(QualType Ty) {
36 // Is it a block pointer?
37 const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
38 if (!BPT)
39 return false;
40
41 // Check if the block pointer type takes no arguments and
42 // returns void.
43 const FunctionProtoType *FT =
44 BPT->getPointeeType()->getAs<FunctionProtoType>();
45 return FT && FT->getReturnType()->isVoidType() && FT->getNumParams() == 0;
46}
47
48namespace {
49class ASTMaker {
50public:
51 ASTMaker(ASTContext &C) : C(C) {}
52
53 /// Create a new BinaryOperator representing a simple assignment.
54 BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
55
56 /// Create a new BinaryOperator representing a comparison.
57 BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
58 BinaryOperator::Opcode Op);
59
60 /// Create a new compound stmt using the provided statements.
61 CompoundStmt *makeCompound(ArrayRef<Stmt*>);
62
63 /// Create a new DeclRefExpr for the referenced variable.
64 DeclRefExpr *makeDeclRefExpr(const VarDecl *D,
65 bool RefersToEnclosingVariableOrCapture = false);
66
67 /// Create a new UnaryOperator representing a dereference.
68 UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
69
70 /// Create an implicit cast for an integer conversion.
71 Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
72
73 /// Create an implicit cast to a builtin boolean type.
74 ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
75
76 /// Create an implicit cast for lvalue-to-rvaluate conversions.
77 ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
78
79 /// Make RValue out of variable declaration, creating a temporary
80 /// DeclRefExpr in the process.
81 ImplicitCastExpr *
82 makeLvalueToRvalue(const VarDecl *Decl,
83 bool RefersToEnclosingVariableOrCapture = false);
84
85 /// Create an implicit cast of the given type.
86 ImplicitCastExpr *makeImplicitCast(const Expr *Arg, QualType Ty,
87 CastKind CK = CK_LValueToRValue);
88
89 /// Create an Objective-C bool literal.
90 ObjCBoolLiteralExpr *makeObjCBool(bool Val);
91
92 /// Create an Objective-C ivar reference.
93 ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
94
95 /// Create a Return statement.
96 ReturnStmt *makeReturn(const Expr *RetVal);
97
98 /// Create an integer literal expression of the given type.
99 IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty);
100
101 /// Create a member expression.
102 MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
103 bool IsArrow = false,
104 ExprValueKind ValueKind = VK_LValue);
105
106 /// Returns a *first* member field of a record declaration with a given name.
107 /// \return an nullptr if no member with such a name exists.
108 ValueDecl *findMemberField(const RecordDecl *RD, StringRef Name);
109
110private:
111 ASTContext &C;
112};
113}
114
115BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
116 QualType Ty) {
117 return new (C) BinaryOperator(const_cast<Expr*>(LHS), const_cast<Expr*>(RHS),
118 BO_Assign, Ty, VK_RValue,
119 OK_Ordinary, SourceLocation(), FPOptions());
120}
121
122BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
123 BinaryOperator::Opcode Op) {
124 assert(BinaryOperator::isLogicalOp(Op) ||((BinaryOperator::isLogicalOp(Op) || BinaryOperator::isComparisonOp
(Op)) ? static_cast<void> (0) : __assert_fail ("BinaryOperator::isLogicalOp(Op) || BinaryOperator::isComparisonOp(Op)"
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Analysis/BodyFarm.cpp"
, 125, __PRETTY_FUNCTION__))
125 BinaryOperator::isComparisonOp(Op))((BinaryOperator::isLogicalOp(Op) || BinaryOperator::isComparisonOp
(Op)) ? static_cast<void> (0) : __assert_fail ("BinaryOperator::isLogicalOp(Op) || BinaryOperator::isComparisonOp(Op)"
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Analysis/BodyFarm.cpp"
, 125, __PRETTY_FUNCTION__))
;
126 return new (C) BinaryOperator(const_cast<Expr*>(LHS),
127 const_cast<Expr*>(RHS),
128 Op,
129 C.getLogicalOperationType(),
130 VK_RValue,
131 OK_Ordinary, SourceLocation(), FPOptions());
132}
133
134CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
135 return CompoundStmt::Create(C, Stmts, SourceLocation(), SourceLocation());
136}
137
138DeclRefExpr *ASTMaker::makeDeclRefExpr(
139 const VarDecl *D,
140 bool RefersToEnclosingVariableOrCapture) {
141 QualType Type = D->getType().getNonReferenceType();
43
Called C++ object pointer is null
142
143 DeclRefExpr *DR = DeclRefExpr::Create(
144 C, NestedNameSpecifierLoc(), SourceLocation(), const_cast<VarDecl *>(D),
145 RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
146 return DR;
147}
148
149UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
150 return new (C) UnaryOperator(const_cast<Expr*>(Arg), UO_Deref, Ty,
151 VK_LValue, OK_Ordinary, SourceLocation(),
152 /*CanOverflow*/ false);
153}
154
155ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
156 return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
157}
158
159ImplicitCastExpr *
160ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
161 bool RefersToEnclosingVariableOrCapture) {
162 QualType Type = Arg->getType().getNonReferenceType();
163 return makeLvalueToRvalue(makeDeclRefExpr(Arg,
164 RefersToEnclosingVariableOrCapture),
165 Type);
166}
167
168ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
169 CastKind CK) {
170 return ImplicitCastExpr::Create(C, Ty,
171 /* CastKind=*/ CK,
172 /* Expr=*/ const_cast<Expr *>(Arg),
173 /* CXXCastPath=*/ nullptr,
174 /* ExprValueKind=*/ VK_RValue);
175}
176
177Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
178 if (Arg->getType() == Ty)
179 return const_cast<Expr*>(Arg);
180
181 return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
182 const_cast<Expr*>(Arg), nullptr, VK_RValue);
183}
184
185ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
186 return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
187 const_cast<Expr*>(Arg), nullptr, VK_RValue);
188}
189
190ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
191 QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
192 return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
193}
194
195ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
196 const ObjCIvarDecl *IVar) {
197 return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
198 IVar->getType(), SourceLocation(),
199 SourceLocation(), const_cast<Expr*>(Base),
200 /*arrow=*/true, /*free=*/false);
201}
202
203ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
204 return ReturnStmt::Create(C, SourceLocation(), const_cast<Expr *>(RetVal),
205 /* NRVOCandidate=*/nullptr);
206}
207
208IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
209 llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
210 return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
211}
212
213MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
214 bool IsArrow,
215 ExprValueKind ValueKind) {
216
217 DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
218 return MemberExpr::Create(
219 C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
220 SourceLocation(), MemberDecl, FoundDecl,
221 DeclarationNameInfo(MemberDecl->getDeclName(), SourceLocation()),
222 /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
223 OK_Ordinary);
224}
225
226ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
227
228 CXXBasePaths Paths(
229 /* FindAmbiguities=*/false,
230 /* RecordPaths=*/false,
231 /* DetectVirtual=*/ false);
232 const IdentifierInfo &II = C.Idents.get(Name);
233 DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
234
235 DeclContextLookupResult Decls = RD->lookup(DeclName);
236 for (NamedDecl *FoundDecl : Decls)
237 if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
238 return cast<ValueDecl>(FoundDecl);
239
240 return nullptr;
241}
242
243//===----------------------------------------------------------------------===//
244// Creation functions for faux ASTs.
245//===----------------------------------------------------------------------===//
246
247typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
248
249static CallExpr *create_call_once_funcptr_call(ASTContext &C, ASTMaker M,
250 const ParmVarDecl *Callback,
251 ArrayRef<Expr *> CallArgs) {
252
253 QualType Ty = Callback->getType();
254 DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
255 Expr *SubExpr;
256 if (Ty->isRValueReferenceType()) {
257 SubExpr = M.makeImplicitCast(
258 Call, Ty.getNonReferenceType(), CK_LValueToRValue);
259 } else if (Ty->isLValueReferenceType() &&
260 Call->getType()->isFunctionType()) {
261 Ty = C.getPointerType(Ty.getNonReferenceType());
262 SubExpr = M.makeImplicitCast(Call, Ty, CK_FunctionToPointerDecay);
263 } else if (Ty->isLValueReferenceType()
264 && Call->getType()->isPointerType()
265 && Call->getType()->getPointeeType()->isFunctionType()){
266 SubExpr = Call;
267 } else {
268 llvm_unreachable("Unexpected state")::llvm::llvm_unreachable_internal("Unexpected state", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Analysis/BodyFarm.cpp"
, 268)
;
269 }
270
271 return CallExpr::Create(C, SubExpr, CallArgs, C.VoidTy, VK_RValue,
272 SourceLocation());
273}
274
275static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
276 const ParmVarDecl *Callback,
277 CXXRecordDecl *CallbackDecl,
278 ArrayRef<Expr *> CallArgs) {
279 assert(CallbackDecl != nullptr)((CallbackDecl != nullptr) ? static_cast<void> (0) : __assert_fail
("CallbackDecl != nullptr", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Analysis/BodyFarm.cpp"
, 279, __PRETTY_FUNCTION__))
;
280 assert(CallbackDecl->isLambda())((CallbackDecl->isLambda()) ? static_cast<void> (0) :
__assert_fail ("CallbackDecl->isLambda()", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Analysis/BodyFarm.cpp"
, 280, __PRETTY_FUNCTION__))
;
281 FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
282 assert(callOperatorDecl != nullptr)((callOperatorDecl != nullptr) ? static_cast<void> (0) :
__assert_fail ("callOperatorDecl != nullptr", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Analysis/BodyFarm.cpp"
, 282, __PRETTY_FUNCTION__))
;
283
284 DeclRefExpr *callOperatorDeclRef =
285 DeclRefExpr::Create(/* Ctx =*/ C,
286 /* QualifierLoc =*/ NestedNameSpecifierLoc(),
287 /* TemplateKWLoc =*/ SourceLocation(),
288 const_cast<FunctionDecl *>(callOperatorDecl),
289 /* RefersToEnclosingVariableOrCapture=*/ false,
290 /* NameLoc =*/ SourceLocation(),
291 /* T =*/ callOperatorDecl->getType(),
292 /* VK =*/ VK_LValue);
293
294 return CXXOperatorCallExpr::Create(
295 /*AstContext=*/C, OO_Call, callOperatorDeclRef,
296 /*args=*/CallArgs,
297 /*QualType=*/C.VoidTy,
298 /*ExprValueType=*/VK_RValue,
299 /*SourceLocation=*/SourceLocation(), FPOptions());
300}
301
302/// Create a fake body for std::call_once.
303/// Emulates the following function body:
304///
305/// \code
306/// typedef struct once_flag_s {
307/// unsigned long __state = 0;
308/// } once_flag;
309/// template<class Callable>
310/// void call_once(once_flag& o, Callable func) {
311/// if (!o.__state) {
312/// func();
313/// }
314/// o.__state = 1;
315/// }
316/// \endcode
317static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) {
318 LLVM_DEBUG(llvm::dbgs() << "Generating body for call_once\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Generating body for call_once\n"
; } } while (false)
;
15
Assuming 'DebugFlag' is 0
16
Loop condition is false. Exiting loop
319
320 // We need at least two parameters.
321 if (D->param_size() < 2)
17
Assuming the condition is false
18
Taking false branch
322 return nullptr;
323
324 ASTMaker M(C);
325
326 const ParmVarDecl *Flag = D->getParamDecl(0);
327 const ParmVarDecl *Callback = D->getParamDecl(1);
328
329 if (!Callback->getType()->isReferenceType()) {
19
Taking false branch
330 llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
331 return nullptr;
332 }
333 if (!Flag->getType()->isReferenceType()) {
20
Taking false branch
334 llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
335 return nullptr;
336 }
337
338 QualType CallbackType = Callback->getType().getNonReferenceType();
339
340 // Nullable pointer, non-null iff function is a CXXRecordDecl.
341 CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
342 QualType FlagType = Flag->getType().getNonReferenceType();
343 auto *FlagRecordDecl = FlagType->getAsRecordDecl();
344
345 if (!FlagRecordDecl) {
21
Assuming 'FlagRecordDecl' is non-null
22
Taking false branch
346 LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Flag field is not a record: "
<< "unknown std::call_once implementation, " << "ignoring the call.\n"
; } } while (false)
347 << "unknown std::call_once implementation, "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Flag field is not a record: "
<< "unknown std::call_once implementation, " << "ignoring the call.\n"
; } } while (false)
348 << "ignoring the call.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Flag field is not a record: "
<< "unknown std::call_once implementation, " << "ignoring the call.\n"
; } } while (false)
;
349 return nullptr;
350 }
351
352 // We initially assume libc++ implementation of call_once,
353 // where the once_flag struct has a field `__state_`.
354 ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
355
356 // Otherwise, try libstdc++ implementation, with a field
357 // `_M_once`
358 if (!FlagFieldDecl) {
23
Taking true branch
359 FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
360 }
361
362 if (!FlagFieldDecl) {
24
Taking false branch
363 LLVM_DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "No field _M_once or __state_ found on "
<< "std::once_flag struct: unknown std::call_once " <<
"implementation, ignoring the call."; } } while (false)
364 << "std::once_flag struct: unknown std::call_once "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "No field _M_once or __state_ found on "
<< "std::once_flag struct: unknown std::call_once " <<
"implementation, ignoring the call."; } } while (false)
365 << "implementation, ignoring the call.")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "No field _M_once or __state_ found on "
<< "std::once_flag struct: unknown std::call_once " <<
"implementation, ignoring the call."; } } while (false)
;
366 return nullptr;
367 }
368
369 bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
25
Assuming 'CallbackRecordDecl' is null
370 if (CallbackRecordDecl && !isLambdaCall) {
371 LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Not supported: synthesizing body for functors when "
<< "body farming std::call_once, ignoring the call."; }
} while (false)
372 << "Not supported: synthesizing body for functors when "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Not supported: synthesizing body for functors when "
<< "body farming std::call_once, ignoring the call."; }
} while (false)
373 << "body farming std::call_once, ignoring the call.")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Not supported: synthesizing body for functors when "
<< "body farming std::call_once, ignoring the call."; }
} while (false)
;
374 return nullptr;
375 }
376
377 SmallVector<Expr *, 5> CallArgs;
378 const FunctionProtoType *CallbackFunctionType;
379 if (isLambdaCall) {
26
Taking false branch
380
381 // Lambda requires callback itself inserted as a first parameter.
382 CallArgs.push_back(
383 M.makeDeclRefExpr(Callback,
384 /* RefersToEnclosingVariableOrCapture=*/ true));
385 CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
386 ->getType()
387 ->getAs<FunctionProtoType>();
388 } else if (!CallbackType->getPointeeType().isNull()) {
27
Taking true branch
389 CallbackFunctionType =
390 CallbackType->getPointeeType()->getAs<FunctionProtoType>();
391 } else {
392 CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
393 }
394
395 if (!CallbackFunctionType)
28
Taking false branch
396 return nullptr;
397
398 // First two arguments are used for the flag and for the callback.
399 if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
29
Assuming the condition is false
30
Taking false branch
400 LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
401 << "params passed to std::call_once, "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
402 << "ignoring the call\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
;
403 return nullptr;
404 }
405
406 // All arguments past first two ones are passed to the callback,
407 // and we turn lvalues into rvalues if the argument is not passed by
408 // reference.
409 for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
31
Assuming the condition is true
32
Loop condition is true. Entering loop body
410 const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
33
Calling 'FunctionDecl::getParamDecl'
37
Returning from 'FunctionDecl::getParamDecl'
38
'PDecl' initialized here
411 if (PDecl &&
39
Assuming 'PDecl' is null
40
Taking false branch
412 CallbackFunctionType->getParamType(ParamIdx - 2)
413 .getNonReferenceType()
414 .getCanonicalType() !=
415 PDecl->getType().getNonReferenceType().getCanonicalType()) {
416 LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
417 << "params passed to std::call_once, "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
418 << "ignoring the call\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
;
419 return nullptr;
420 }
421 Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
41
Passing null pointer value via 1st parameter 'D'
42
Calling 'ASTMaker::makeDeclRefExpr'
422 if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
423 QualType PTy = PDecl->getType().getNonReferenceType();
424 ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
425 }
426 CallArgs.push_back(ParamExpr);
427 }
428
429 CallExpr *CallbackCall;
430 if (isLambdaCall) {
431
432 CallbackCall = create_call_once_lambda_call(C, M, Callback,
433 CallbackRecordDecl, CallArgs);
434 } else {
435
436 // Function pointer case.
437 CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
438 }
439
440 DeclRefExpr *FlagDecl =
441 M.makeDeclRefExpr(Flag,
442 /* RefersToEnclosingVariableOrCapture=*/true);
443
444
445 MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
446 assert(Deref->isLValue())((Deref->isLValue()) ? static_cast<void> (0) : __assert_fail
("Deref->isLValue()", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Analysis/BodyFarm.cpp"
, 446, __PRETTY_FUNCTION__))
;
447 QualType DerefType = Deref->getType();
448
449 // Negation predicate.
450 UnaryOperator *FlagCheck = new (C) UnaryOperator(
451 /* input=*/
452 M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
453 CK_IntegralToBoolean),
454 /* opc=*/ UO_LNot,
455 /* QualType=*/ C.IntTy,
456 /* ExprValueKind=*/ VK_RValue,
457 /* ExprObjectKind=*/ OK_Ordinary, SourceLocation(),
458 /* CanOverflow*/ false);
459
460 // Create assignment.
461 BinaryOperator *FlagAssignment = M.makeAssignment(
462 Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
463 DerefType);
464
465 auto *Out =
466 IfStmt::Create(C, SourceLocation(),
467 /* IsConstexpr=*/false,
468 /* init=*/nullptr,
469 /* var=*/nullptr,
470 /* cond=*/FlagCheck,
471 /* then=*/M.makeCompound({CallbackCall, FlagAssignment}));
472
473 return Out;
474}
475
476/// Create a fake body for dispatch_once.
477static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
478 // Check if we have at least two parameters.
479 if (D->param_size() != 2)
480 return nullptr;
481
482 // Check if the first parameter is a pointer to integer type.
483 const ParmVarDecl *Predicate = D->getParamDecl(0);
484 QualType PredicateQPtrTy = Predicate->getType();
485 const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
486 if (!PredicatePtrTy)
487 return nullptr;
488 QualType PredicateTy = PredicatePtrTy->getPointeeType();
489 if (!PredicateTy->isIntegerType())
490 return nullptr;
491
492 // Check if the second parameter is the proper block type.
493 const ParmVarDecl *Block = D->getParamDecl(1);
494 QualType Ty = Block->getType();
495 if (!isDispatchBlock(Ty))
496 return nullptr;
497
498 // Everything checks out. Create a fakse body that checks the predicate,
499 // sets it, and calls the block. Basically, an AST dump of:
500 //
501 // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
502 // if (*predicate != ~0l) {
503 // *predicate = ~0l;
504 // block();
505 // }
506 // }
507
508 ASTMaker M(C);
509
510 // (1) Create the call.
511 CallExpr *CE = CallExpr::Create(
512 /*ASTContext=*/C,
513 /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
514 /*args=*/None,
515 /*QualType=*/C.VoidTy,
516 /*ExprValueType=*/VK_RValue,
517 /*SourceLocation=*/SourceLocation());
518
519 // (2) Create the assignment to the predicate.
520 Expr *DoneValue =
521 new (C) UnaryOperator(M.makeIntegerLiteral(0, C.LongTy), UO_Not, C.LongTy,
522 VK_RValue, OK_Ordinary, SourceLocation(),
523 /*CanOverflow*/false);
524
525 BinaryOperator *B =
526 M.makeAssignment(
527 M.makeDereference(
528 M.makeLvalueToRvalue(
529 M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
530 PredicateTy),
531 M.makeIntegralCast(DoneValue, PredicateTy),
532 PredicateTy);
533
534 // (3) Create the compound statement.
535 Stmt *Stmts[] = { B, CE };
536 CompoundStmt *CS = M.makeCompound(Stmts);
537
538 // (4) Create the 'if' condition.
539 ImplicitCastExpr *LValToRval =
540 M.makeLvalueToRvalue(
541 M.makeDereference(
542 M.makeLvalueToRvalue(
543 M.makeDeclRefExpr(Predicate),
544 PredicateQPtrTy),
545 PredicateTy),
546 PredicateTy);
547
548 Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
549 // (5) Create the 'if' statement.
550 auto *If = IfStmt::Create(C, SourceLocation(),
551 /* IsConstexpr=*/false,
552 /* init=*/nullptr,
553 /* var=*/nullptr,
554 /* cond=*/GuardCondition,
555 /* then=*/CS);
556 return If;
557}
558
559/// Create a fake body for dispatch_sync.
560static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
561 // Check if we have at least two parameters.
562 if (D->param_size() != 2)
563 return nullptr;
564
565 // Check if the second parameter is a block.
566 const ParmVarDecl *PV = D->getParamDecl(1);
567 QualType Ty = PV->getType();
568 if (!isDispatchBlock(Ty))
569 return nullptr;
570
571 // Everything checks out. Create a fake body that just calls the block.
572 // This is basically just an AST dump of:
573 //
574 // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
575 // block();
576 // }
577 //
578 ASTMaker M(C);
579 DeclRefExpr *DR = M.makeDeclRefExpr(PV);
580 ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
581 CallExpr *CE =
582 CallExpr::Create(C, ICE, None, C.VoidTy, VK_RValue, SourceLocation());
583 return CE;
584}
585
586static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
587{
588 // There are exactly 3 arguments.
589 if (D->param_size() != 3)
590 return nullptr;
591
592 // Signature:
593 // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
594 // void *__newValue,
595 // void * volatile *__theValue)
596 // Generate body:
597 // if (oldValue == *theValue) {
598 // *theValue = newValue;
599 // return YES;
600 // }
601 // else return NO;
602
603 QualType ResultTy = D->getReturnType();
604 bool isBoolean = ResultTy->isBooleanType();
605 if (!isBoolean && !ResultTy->isIntegralType(C))
606 return nullptr;
607
608 const ParmVarDecl *OldValue = D->getParamDecl(0);
609 QualType OldValueTy = OldValue->getType();
610
611 const ParmVarDecl *NewValue = D->getParamDecl(1);
612 QualType NewValueTy = NewValue->getType();
613
614 assert(OldValueTy == NewValueTy)((OldValueTy == NewValueTy) ? static_cast<void> (0) : __assert_fail
("OldValueTy == NewValueTy", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Analysis/BodyFarm.cpp"
, 614, __PRETTY_FUNCTION__))
;
615
616 const ParmVarDecl *TheValue = D->getParamDecl(2);
617 QualType TheValueTy = TheValue->getType();
618 const PointerType *PT = TheValueTy->getAs<PointerType>();
619 if (!PT)
620 return nullptr;
621 QualType PointeeTy = PT->getPointeeType();
622
623 ASTMaker M(C);
624 // Construct the comparison.
625 Expr *Comparison =
626 M.makeComparison(
627 M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
628 M.makeLvalueToRvalue(
629 M.makeDereference(
630 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
631 PointeeTy),
632 PointeeTy),
633 BO_EQ);
634
635 // Construct the body of the IfStmt.
636 Stmt *Stmts[2];
637 Stmts[0] =
638 M.makeAssignment(
639 M.makeDereference(
640 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
641 PointeeTy),
642 M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
643 NewValueTy);
644
645 Expr *BoolVal = M.makeObjCBool(true);
646 Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
647 : M.makeIntegralCast(BoolVal, ResultTy);
648 Stmts[1] = M.makeReturn(RetVal);
649 CompoundStmt *Body = M.makeCompound(Stmts);
650
651 // Construct the else clause.
652 BoolVal = M.makeObjCBool(false);
653 RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
654 : M.makeIntegralCast(BoolVal, ResultTy);
655 Stmt *Else = M.makeReturn(RetVal);
656
657 /// Construct the If.
658 auto *If = IfStmt::Create(C, SourceLocation(),
659 /* IsConstexpr=*/false,
660 /* init=*/nullptr,
661 /* var=*/nullptr, Comparison, Body,
662 SourceLocation(), Else);
663
664 return If;
665}
666
667Stmt *BodyFarm::getBody(const FunctionDecl *D) {
668 D = D->getCanonicalDecl();
669
670 Optional<Stmt *> &Val = Bodies[D];
671 if (Val.hasValue())
1
Assuming the condition is false
2
Taking false branch
672 return Val.getValue();
673
674 Val = nullptr;
675
676 if (D->getIdentifier() == nullptr)
3
Assuming the condition is false
4
Taking false branch
677 return nullptr;
678
679 StringRef Name = D->getName();
680 if (Name.empty())
5
Assuming the condition is false
6
Taking false branch
681 return nullptr;
682
683 FunctionFarmer FF;
684
685 if (Name.startswith("OSAtomicCompareAndSwap") ||
7
Assuming the condition is false
8
Assuming the condition is false
9
Taking false branch
686 Name.startswith("objc_atomicCompareAndSwap")) {
687 FF = create_OSAtomicCompareAndSwap;
688 } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
10
Assuming the condition is true
11
Assuming the condition is true
12
Taking true branch
689 FF = create_call_once;
690 } else {
691 FF = llvm::StringSwitch<FunctionFarmer>(Name)
692 .Case("dispatch_sync", create_dispatch_sync)
693 .Case("dispatch_once", create_dispatch_once)
694 .Default(nullptr);
695 }
696
697 if (FF) { Val = FF(C, D); }
13
Taking true branch
14
Calling 'create_call_once'
698 else if (Injector) { Val = Injector->getBody(D); }
699 return Val.getValue();
700}
701
702static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
703 const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
704
705 if (IVar)
706 return IVar;
707
708 // When a readonly property is shadowed in a class extensions with a
709 // a readwrite property, the instance variable belongs to the shadowing
710 // property rather than the shadowed property. If there is no instance
711 // variable on a readonly property, check to see whether the property is
712 // shadowed and if so try to get the instance variable from shadowing
713 // property.
714 if (!Prop->isReadOnly())
715 return nullptr;
716
717 auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
718 const ObjCInterfaceDecl *PrimaryInterface = nullptr;
719 if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
720 PrimaryInterface = InterfaceDecl;
721 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
722 PrimaryInterface = CategoryDecl->getClassInterface();
723 } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
724 PrimaryInterface = ImplDecl->getClassInterface();
725 } else {
726 return nullptr;
727 }
728
729 // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
730 // is guaranteed to find the shadowing property, if it exists, rather than
731 // the shadowed property.
732 auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
733 Prop->getIdentifier(), Prop->getQueryKind());
734 if (ShadowingProp && ShadowingProp != Prop) {
735 IVar = ShadowingProp->getPropertyIvarDecl();
736 }
737
738 return IVar;
739}
740
741static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
742 const ObjCPropertyDecl *Prop) {
743 // First, find the backing ivar.
744 const ObjCIvarDecl *IVar = findBackingIvar(Prop);
745 if (!IVar)
746 return nullptr;
747
748 // Ignore weak variables, which have special behavior.
749 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
750 return nullptr;
751
752 // Look to see if Sema has synthesized a body for us. This happens in
753 // Objective-C++ because the return value may be a C++ class type with a
754 // non-trivial copy constructor. We can only do this if we can find the
755 // @synthesize for this property, though (or if we know it's been auto-
756 // synthesized).
757 const ObjCImplementationDecl *ImplDecl =
758 IVar->getContainingInterface()->getImplementation();
759 if (ImplDecl) {
760 for (const auto *I : ImplDecl->property_impls()) {
761 if (I->getPropertyDecl() != Prop)
762 continue;
763
764 if (I->getGetterCXXConstructor()) {
765 ASTMaker M(Ctx);
766 return M.makeReturn(I->getGetterCXXConstructor());
767 }
768 }
769 }
770
771 // Sanity check that the property is the same type as the ivar, or a
772 // reference to it, and that it is either an object pointer or trivially
773 // copyable.
774 if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
775 Prop->getType().getNonReferenceType()))
776 return nullptr;
777 if (!IVar->getType()->isObjCLifetimeType() &&
778 !IVar->getType().isTriviallyCopyableType(Ctx))
779 return nullptr;
780
781 // Generate our body:
782 // return self->_ivar;
783 ASTMaker M(Ctx);
784
785 const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
786 if (!selfVar)
787 return nullptr;
788
789 Expr *loadedIVar =
790 M.makeObjCIvarRef(
791 M.makeLvalueToRvalue(
792 M.makeDeclRefExpr(selfVar),
793 selfVar->getType()),
794 IVar);
795
796 if (!Prop->getType()->isReferenceType())
797 loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
798
799 return M.makeReturn(loadedIVar);
800}
801
802Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
803 // We currently only know how to synthesize property accessors.
804 if (!D->isPropertyAccessor())
805 return nullptr;
806
807 D = D->getCanonicalDecl();
808
809 // We should not try to synthesize explicitly redefined accessors.
810 // We do not know for sure how they behave.
811 if (!D->isImplicit())
812 return nullptr;
813
814 Optional<Stmt *> &Val = Bodies[D];
815 if (Val.hasValue())
816 return Val.getValue();
817 Val = nullptr;
818
819 const ObjCPropertyDecl *Prop = D->findPropertyDecl();
820 if (!Prop)
821 return nullptr;
822
823 // For now, we only synthesize getters.
824 // Synthesizing setters would cause false negatives in the
825 // RetainCountChecker because the method body would bind the parameter
826 // to an instance variable, causing it to escape. This would prevent
827 // warning in the following common scenario:
828 //
829 // id foo = [[NSObject alloc] init];
830 // self.foo = foo; // We should warn that foo leaks here.
831 //
832 if (D->param_size() != 0)
833 return nullptr;
834
835 Val = createObjCPropertyGetter(C, Prop);
836
837 return Val.getValue();
838}

/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- 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 the Decl subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECL_H
14#define LLVM_CLANG_AST_DECL_H
15
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTContextAllocate.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/AddressSpaces.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/IdentifierTable.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/PragmaKinds.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/Specifiers.h"
34#include "clang/Basic/Visibility.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/iterator_range.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/TrailingObjects.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <string>
49#include <utility>
50
51namespace clang {
52
53class ASTContext;
54struct ASTTemplateArgumentListInfo;
55class Attr;
56class CompoundStmt;
57class DependentFunctionTemplateSpecializationInfo;
58class EnumDecl;
59class Expr;
60class FunctionTemplateDecl;
61class FunctionTemplateSpecializationInfo;
62class LabelStmt;
63class MemberSpecializationInfo;
64class Module;
65class NamespaceDecl;
66class ParmVarDecl;
67class RecordDecl;
68class Stmt;
69class StringLiteral;
70class TagDecl;
71class TemplateArgumentList;
72class TemplateArgumentListInfo;
73class TemplateParameterList;
74class TypeAliasTemplateDecl;
75class TypeLoc;
76class UnresolvedSetImpl;
77class VarTemplateDecl;
78
79/// A container of type source information.
80///
81/// A client can read the relevant info using TypeLoc wrappers, e.g:
82/// @code
83/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
84/// TL.getBeginLoc().print(OS, SrcMgr);
85/// @endcode
86class alignas(8) TypeSourceInfo {
87 // Contains a memory block after the class, used for type source information,
88 // allocated by ASTContext.
89 friend class ASTContext;
90
91 QualType Ty;
92
93 TypeSourceInfo(QualType ty) : Ty(ty) {}
94
95public:
96 /// Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// The top declaration context.
107class TranslationUnitDecl : public Decl, public DeclContext {
108 ASTContext &Ctx;
109
110 /// The (most recently entered) anonymous namespace for this
111 /// translation unit, if one has been created.
112 NamespaceDecl *AnonymousNamespace = nullptr;
113
114 explicit TranslationUnitDecl(ASTContext &ctx);
115
116 virtual void anchor();
117
118public:
119 ASTContext &getASTContext() const { return Ctx; }
120
121 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
122 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
123
124 static TranslationUnitDecl *Create(ASTContext &C);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == TranslationUnit; }
129 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
130 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
131 }
132 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
133 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
134 }
135};
136
137/// Represents a `#pragma comment` line. Always a child of
138/// TranslationUnitDecl.
139class PragmaCommentDecl final
140 : public Decl,
141 private llvm::TrailingObjects<PragmaCommentDecl, char> {
142 friend class ASTDeclReader;
143 friend class ASTDeclWriter;
144 friend TrailingObjects;
145
146 PragmaMSCommentKind CommentKind;
147
148 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
149 PragmaMSCommentKind CommentKind)
150 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
151
152 virtual void anchor();
153
154public:
155 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
156 SourceLocation CommentLoc,
157 PragmaMSCommentKind CommentKind,
158 StringRef Arg);
159 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
160 unsigned ArgSize);
161
162 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
163
164 StringRef getArg() const { return getTrailingObjects<char>(); }
165
166 // Implement isa/cast/dyncast/etc.
167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
168 static bool classofKind(Kind K) { return K == PragmaComment; }
169};
170
171/// Represents a `#pragma detect_mismatch` line. Always a child of
172/// TranslationUnitDecl.
173class PragmaDetectMismatchDecl final
174 : public Decl,
175 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
176 friend class ASTDeclReader;
177 friend class ASTDeclWriter;
178 friend TrailingObjects;
179
180 size_t ValueStart;
181
182 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
183 size_t ValueStart)
184 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
185
186 virtual void anchor();
187
188public:
189 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
190 TranslationUnitDecl *DC,
191 SourceLocation Loc, StringRef Name,
192 StringRef Value);
193 static PragmaDetectMismatchDecl *
194 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
195
196 StringRef getName() const { return getTrailingObjects<char>(); }
197 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
198
199 // Implement isa/cast/dyncast/etc.
200 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
201 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
202};
203
204/// Declaration context for names declared as extern "C" in C++. This
205/// is neither the semantic nor lexical context for such declarations, but is
206/// used to check for conflicts with other extern "C" declarations. Example:
207///
208/// \code
209/// namespace N { extern "C" void f(); } // #1
210/// void N::f() {} // #2
211/// namespace M { extern "C" void f(); } // #3
212/// \endcode
213///
214/// The semantic context of #1 is namespace N and its lexical context is the
215/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
216/// context is the TU. However, both declarations are also visible in the
217/// extern "C" context.
218///
219/// The declaration at #3 finds it is a redeclaration of \c N::f through
220/// lookup in the extern "C" context.
221class ExternCContextDecl : public Decl, public DeclContext {
222 explicit ExternCContextDecl(TranslationUnitDecl *TU)
223 : Decl(ExternCContext, TU, SourceLocation()),
224 DeclContext(ExternCContext) {}
225
226 virtual void anchor();
227
228public:
229 static ExternCContextDecl *Create(const ASTContext &C,
230 TranslationUnitDecl *TU);
231
232 // Implement isa/cast/dyncast/etc.
233 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
234 static bool classofKind(Kind K) { return K == ExternCContext; }
235 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
236 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
237 }
238 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
239 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
240 }
241};
242
243/// This represents a decl that may have a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245///
246/// Note that not every NamedDecl is actually named (e.g., a struct might
247/// be anonymous), and not every name is an identifier.
248class NamedDecl : public Decl {
249 /// The name of this declaration, which is typically a normal
250 /// identifier but may also be a special kind of name (C++
251 /// constructor, Objective-C selector, etc.)
252 DeclarationName Name;
253
254 virtual void anchor();
255
256private:
257 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
258
259protected:
260 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
261 : Decl(DK, DC, L), Name(N) {}
262
263public:
264 /// Get the identifier that names this declaration, if there is one.
265 ///
266 /// This will return NULL if this declaration has no name (e.g., for
267 /// an unnamed class) or if the name is a special name (C++ constructor,
268 /// Objective-C selector, etc.).
269 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
270
271 /// Get the name of identifier for this declaration as a StringRef.
272 ///
273 /// This requires that the declaration have a name and that it be a simple
274 /// identifier.
275 StringRef getName() const {
276 assert(Name.isIdentifier() && "Name is not a simple identifier")((Name.isIdentifier() && "Name is not a simple identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 276, __PRETTY_FUNCTION__))
;
277 return getIdentifier() ? getIdentifier()->getName() : "";
278 }
279
280 /// Get a human-readable name for the declaration, even if it is one of the
281 /// special kinds of names (C++ constructor, Objective-C selector, etc).
282 ///
283 /// Creating this name requires expensive string manipulation, so it should
284 /// be called only when performance doesn't matter. For simple declarations,
285 /// getNameAsCString() should suffice.
286 //
287 // FIXME: This function should be renamed to indicate that it is not just an
288 // alternate form of getName(), and clients should move as appropriate.
289 //
290 // FIXME: Deprecated, move clients to getName().
291 std::string getNameAsString() const { return Name.getAsString(); }
292
293 virtual void printName(raw_ostream &os) const;
294
295 /// Get the actual, stored name of the declaration, which may be a special
296 /// name.
297 DeclarationName getDeclName() const { return Name; }
298
299 /// Set the name of this declaration.
300 void setDeclName(DeclarationName N) { Name = N; }
301
302 /// Returns a human-readable qualified name for this declaration, like
303 /// A::B::i, for i being member of namespace A::B.
304 ///
305 /// If the declaration is not a member of context which can be named (record,
306 /// namespace), it will return the same result as printName().
307 ///
308 /// Creating this name is expensive, so it should be called only when
309 /// performance doesn't matter.
310 void printQualifiedName(raw_ostream &OS) const;
311 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
312
313 // FIXME: Remove string version.
314 std::string getQualifiedNameAsString() const;
315
316 /// Appends a human-readable name for this declaration into the given stream.
317 ///
318 /// This is the method invoked by Sema when displaying a NamedDecl
319 /// in a diagnostic. It does not necessarily produce the same
320 /// result as printName(); for example, class template
321 /// specializations are printed with their template arguments.
322 virtual void getNameForDiagnostic(raw_ostream &OS,
323 const PrintingPolicy &Policy,
324 bool Qualified) const;
325
326 /// Determine whether this declaration, if known to be well-formed within
327 /// its context, will replace the declaration OldD if introduced into scope.
328 ///
329 /// A declaration will replace another declaration if, for example, it is
330 /// a redeclaration of the same variable or function, but not if it is a
331 /// declaration of a different kind (function vs. class) or an overloaded
332 /// function.
333 ///
334 /// \param IsKnownNewer \c true if this declaration is known to be newer
335 /// than \p OldD (for instance, if this declaration is newly-created).
336 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
337
338 /// Determine whether this declaration has linkage.
339 bool hasLinkage() const;
340
341 using Decl::isModulePrivate;
342 using Decl::setModulePrivate;
343
344 /// Determine whether this declaration is a C++ class member.
345 bool isCXXClassMember() const {
346 const DeclContext *DC = getDeclContext();
347
348 // C++0x [class.mem]p1:
349 // The enumerators of an unscoped enumeration defined in
350 // the class are members of the class.
351 if (isa<EnumDecl>(DC))
352 DC = DC->getRedeclContext();
353
354 return DC->isRecord();
355 }
356
357 /// Determine whether the given declaration is an instance member of
358 /// a C++ class.
359 bool isCXXInstanceMember() const;
360
361 /// Determine what kind of linkage this entity has.
362 ///
363 /// This is not the linkage as defined by the standard or the codegen notion
364 /// of linkage. It is just an implementation detail that is used to compute
365 /// those.
366 Linkage getLinkageInternal() const;
367
368 /// Get the linkage from a semantic point of view. Entities in
369 /// anonymous namespaces are external (in c++98).
370 Linkage getFormalLinkage() const {
371 return clang::getFormalLinkage(getLinkageInternal());
372 }
373
374 /// True if this decl has external linkage.
375 bool hasExternalFormalLinkage() const {
376 return isExternalFormalLinkage(getLinkageInternal());
377 }
378
379 bool isExternallyVisible() const {
380 return clang::isExternallyVisible(getLinkageInternal());
381 }
382
383 /// Determine whether this declaration can be redeclared in a
384 /// different translation unit.
385 bool isExternallyDeclarable() const {
386 return isExternallyVisible() && !getOwningModuleForLinkage();
387 }
388
389 /// Determines the visibility of this entity.
390 Visibility getVisibility() const {
391 return getLinkageAndVisibility().getVisibility();
392 }
393
394 /// Determines the linkage and visibility of this entity.
395 LinkageInfo getLinkageAndVisibility() const;
396
397 /// Kinds of explicit visibility.
398 enum ExplicitVisibilityKind {
399 /// Do an LV computation for, ultimately, a type.
400 /// Visibility may be restricted by type visibility settings and
401 /// the visibility of template arguments.
402 VisibilityForType,
403
404 /// Do an LV computation for, ultimately, a non-type declaration.
405 /// Visibility may be restricted by value visibility settings and
406 /// the visibility of template arguments.
407 VisibilityForValue
408 };
409
410 /// If visibility was explicitly specified for this
411 /// declaration, return that visibility.
412 Optional<Visibility>
413 getExplicitVisibility(ExplicitVisibilityKind kind) const;
414
415 /// True if the computed linkage is valid. Used for consistency
416 /// checking. Should always return true.
417 bool isLinkageValid() const;
418
419 /// True if something has required us to compute the linkage
420 /// of this declaration.
421 ///
422 /// Language features which can retroactively change linkage (like a
423 /// typedef name for linkage purposes) may need to consider this,
424 /// but hopefully only in transitory ways during parsing.
425 bool hasLinkageBeenComputed() const {
426 return hasCachedLinkage();
427 }
428
429 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
430 /// the underlying named decl.
431 NamedDecl *getUnderlyingDecl() {
432 // Fast-path the common case.
433 if (this->getKind() != UsingShadow &&
434 this->getKind() != ConstructorUsingShadow &&
435 this->getKind() != ObjCCompatibleAlias &&
436 this->getKind() != NamespaceAlias)
437 return this;
438
439 return getUnderlyingDeclImpl();
440 }
441 const NamedDecl *getUnderlyingDecl() const {
442 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
443 }
444
445 NamedDecl *getMostRecentDecl() {
446 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
447 }
448 const NamedDecl *getMostRecentDecl() const {
449 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
450 }
451
452 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
453
454 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
455 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
456};
457
458inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
459 ND.printName(OS);
460 return OS;
461}
462
463/// Represents the declaration of a label. Labels also have a
464/// corresponding LabelStmt, which indicates the position that the label was
465/// defined at. For normal labels, the location of the decl is the same as the
466/// location of the statement. For GNU local labels (__label__), the decl
467/// location is where the __label__ is.
468class LabelDecl : public NamedDecl {
469 LabelStmt *TheStmt;
470 StringRef MSAsmName;
471 bool MSAsmNameResolved = false;
472
473 /// For normal labels, this is the same as the main declaration
474 /// label, i.e., the location of the identifier; for GNU local labels,
475 /// this is the location of the __label__ keyword.
476 SourceLocation LocStart;
477
478 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
479 LabelStmt *S, SourceLocation StartL)
480 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
481
482 void anchor() override;
483
484public:
485 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
486 SourceLocation IdentL, IdentifierInfo *II);
487 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
488 SourceLocation IdentL, IdentifierInfo *II,
489 SourceLocation GnuLabelL);
490 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
491
492 LabelStmt *getStmt() const { return TheStmt; }
493 void setStmt(LabelStmt *T) { TheStmt = T; }
494
495 bool isGnuLocal() const { return LocStart != getLocation(); }
496 void setLocStart(SourceLocation L) { LocStart = L; }
497
498 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
499 return SourceRange(LocStart, getLocation());
500 }
501
502 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
503 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
504 void setMSAsmLabel(StringRef Name);
505 StringRef getMSAsmLabel() const { return MSAsmName; }
506 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
507
508 // Implement isa/cast/dyncast/etc.
509 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
510 static bool classofKind(Kind K) { return K == Label; }
511};
512
513/// Represent a C++ namespace.
514class NamespaceDecl : public NamedDecl, public DeclContext,
515 public Redeclarable<NamespaceDecl>
516{
517 /// The starting location of the source range, pointing
518 /// to either the namespace or the inline keyword.
519 SourceLocation LocStart;
520
521 /// The ending location of the source range.
522 SourceLocation RBraceLoc;
523
524 /// A pointer to either the anonymous namespace that lives just inside
525 /// this namespace or to the first namespace in the chain (the latter case
526 /// only when this is not the first in the chain), along with a
527 /// boolean value indicating whether this is an inline namespace.
528 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
529
530 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
531 SourceLocation StartLoc, SourceLocation IdLoc,
532 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
533
534 using redeclarable_base = Redeclarable<NamespaceDecl>;
535
536 NamespaceDecl *getNextRedeclarationImpl() override;
537 NamespaceDecl *getPreviousDeclImpl() override;
538 NamespaceDecl *getMostRecentDeclImpl() override;
539
540public:
541 friend class ASTDeclReader;
542 friend class ASTDeclWriter;
543
544 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
545 bool Inline, SourceLocation StartLoc,
546 SourceLocation IdLoc, IdentifierInfo *Id,
547 NamespaceDecl *PrevDecl);
548
549 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
550
551 using redecl_range = redeclarable_base::redecl_range;
552 using redecl_iterator = redeclarable_base::redecl_iterator;
553
554 using redeclarable_base::redecls_begin;
555 using redeclarable_base::redecls_end;
556 using redeclarable_base::redecls;
557 using redeclarable_base::getPreviousDecl;
558 using redeclarable_base::getMostRecentDecl;
559 using redeclarable_base::isFirstDecl;
560
561 /// Returns true if this is an anonymous namespace declaration.
562 ///
563 /// For example:
564 /// \code
565 /// namespace {
566 /// ...
567 /// };
568 /// \endcode
569 /// q.v. C++ [namespace.unnamed]
570 bool isAnonymousNamespace() const {
571 return !getIdentifier();
572 }
573
574 /// Returns true if this is an inline namespace declaration.
575 bool isInline() const {
576 return AnonOrFirstNamespaceAndInline.getInt();
577 }
578
579 /// Set whether this is an inline namespace declaration.
580 void setInline(bool Inline) {
581 AnonOrFirstNamespaceAndInline.setInt(Inline);
582 }
583
584 /// Get the original (first) namespace declaration.
585 NamespaceDecl *getOriginalNamespace();
586
587 /// Get the original (first) namespace declaration.
588 const NamespaceDecl *getOriginalNamespace() const;
589
590 /// Return true if this declaration is an original (first) declaration
591 /// of the namespace. This is false for non-original (subsequent) namespace
592 /// declarations and anonymous namespaces.
593 bool isOriginalNamespace() const;
594
595 /// Retrieve the anonymous namespace nested inside this namespace,
596 /// if any.
597 NamespaceDecl *getAnonymousNamespace() const {
598 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
599 }
600
601 void setAnonymousNamespace(NamespaceDecl *D) {
602 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
603 }
604
605 /// Retrieves the canonical declaration of this namespace.
606 NamespaceDecl *getCanonicalDecl() override {
607 return getOriginalNamespace();
608 }
609 const NamespaceDecl *getCanonicalDecl() const {
610 return getOriginalNamespace();
611 }
612
613 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
614 return SourceRange(LocStart, RBraceLoc);
615 }
616
617 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
618 SourceLocation getRBraceLoc() const { return RBraceLoc; }
619 void setLocStart(SourceLocation L) { LocStart = L; }
620 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
621
622 // Implement isa/cast/dyncast/etc.
623 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
624 static bool classofKind(Kind K) { return K == Namespace; }
625 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
626 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
627 }
628 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
629 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
630 }
631};
632
633/// Represent the declaration of a variable (in which case it is
634/// an lvalue) a function (in which case it is a function designator) or
635/// an enum constant.
636class ValueDecl : public NamedDecl {
637 QualType DeclType;
638
639 void anchor() override;
640
641protected:
642 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
643 DeclarationName N, QualType T)
644 : NamedDecl(DK, DC, L, N), DeclType(T) {}
645
646public:
647 QualType getType() const { return DeclType; }
648 void setType(QualType newType) { DeclType = newType; }
649
650 /// Determine whether this symbol is weakly-imported,
651 /// or declared with the weak or weak-ref attr.
652 bool isWeak() const;
653
654 // Implement isa/cast/dyncast/etc.
655 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
656 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
657};
658
659/// A struct with extended info about a syntactic
660/// name qualifier, to be used for the case of out-of-line declarations.
661struct QualifierInfo {
662 NestedNameSpecifierLoc QualifierLoc;
663
664 /// The number of "outer" template parameter lists.
665 /// The count includes all of the template parameter lists that were matched
666 /// against the template-ids occurring into the NNS and possibly (in the
667 /// case of an explicit specialization) a final "template <>".
668 unsigned NumTemplParamLists = 0;
669
670 /// A new-allocated array of size NumTemplParamLists,
671 /// containing pointers to the "outer" template parameter lists.
672 /// It includes all of the template parameter lists that were matched
673 /// against the template-ids occurring into the NNS and possibly (in the
674 /// case of an explicit specialization) a final "template <>".
675 TemplateParameterList** TemplParamLists = nullptr;
676
677 QualifierInfo() = default;
678 QualifierInfo(const QualifierInfo &) = delete;
679 QualifierInfo& operator=(const QualifierInfo &) = delete;
680
681 /// Sets info about "outer" template parameter lists.
682 void setTemplateParameterListsInfo(ASTContext &Context,
683 ArrayRef<TemplateParameterList *> TPLists);
684};
685
686/// Represents a ValueDecl that came out of a declarator.
687/// Contains type source information through TypeSourceInfo.
688class DeclaratorDecl : public ValueDecl {
689 // A struct representing both a TInfo and a syntactic qualifier,
690 // to be used for the (uncommon) case of out-of-line declarations.
691 struct ExtInfo : public QualifierInfo {
692 TypeSourceInfo *TInfo;
693 };
694
695 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
696
697 /// The start of the source range for this declaration,
698 /// ignoring outer template declarations.
699 SourceLocation InnerLocStart;
700
701 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
702 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
703 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
704
705protected:
706 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
707 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
708 SourceLocation StartL)
709 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
710
711public:
712 friend class ASTDeclReader;
713 friend class ASTDeclWriter;
714
715 TypeSourceInfo *getTypeSourceInfo() const {
716 return hasExtInfo()
717 ? getExtInfo()->TInfo
718 : DeclInfo.get<TypeSourceInfo*>();
719 }
720
721 void setTypeSourceInfo(TypeSourceInfo *TI) {
722 if (hasExtInfo())
723 getExtInfo()->TInfo = TI;
724 else
725 DeclInfo = TI;
726 }
727
728 /// Return start of source range ignoring outer template declarations.
729 SourceLocation getInnerLocStart() const { return InnerLocStart; }
730 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
731
732 /// Return start of source range taking into account any outer template
733 /// declarations.
734 SourceLocation getOuterLocStart() const;
735
736 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
737
738 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
739 return getOuterLocStart();
740 }
741
742 /// Retrieve the nested-name-specifier that qualifies the name of this
743 /// declaration, if it was present in the source.
744 NestedNameSpecifier *getQualifier() const {
745 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
746 : nullptr;
747 }
748
749 /// Retrieve the nested-name-specifier (with source-location
750 /// information) that qualifies the name of this declaration, if it was
751 /// present in the source.
752 NestedNameSpecifierLoc getQualifierLoc() const {
753 return hasExtInfo() ? getExtInfo()->QualifierLoc
754 : NestedNameSpecifierLoc();
755 }
756
757 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
758
759 unsigned getNumTemplateParameterLists() const {
760 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
761 }
762
763 TemplateParameterList *getTemplateParameterList(unsigned index) const {
764 assert(index < getNumTemplateParameterLists())((index < getNumTemplateParameterLists()) ? static_cast<
void> (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 764, __PRETTY_FUNCTION__))
;
765 return getExtInfo()->TemplParamLists[index];
766 }
767
768 void setTemplateParameterListsInfo(ASTContext &Context,
769 ArrayRef<TemplateParameterList *> TPLists);
770
771 SourceLocation getTypeSpecStartLoc() const;
772
773 // Implement isa/cast/dyncast/etc.
774 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
775 static bool classofKind(Kind K) {
776 return K >= firstDeclarator && K <= lastDeclarator;
777 }
778};
779
780/// Structure used to store a statement, the constant value to
781/// which it was evaluated (if any), and whether or not the statement
782/// is an integral constant expression (if known).
783struct EvaluatedStmt {
784 /// Whether this statement was already evaluated.
785 bool WasEvaluated : 1;
786
787 /// Whether this statement is being evaluated.
788 bool IsEvaluating : 1;
789
790 /// Whether we already checked whether this statement was an
791 /// integral constant expression.
792 bool CheckedICE : 1;
793
794 /// Whether we are checking whether this statement is an
795 /// integral constant expression.
796 bool CheckingICE : 1;
797
798 /// Whether this statement is an integral constant expression,
799 /// or in C++11, whether the statement is a constant expression. Only
800 /// valid if CheckedICE is true.
801 bool IsICE : 1;
802
803 Stmt *Value;
804 APValue Evaluated;
805
806 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
807 CheckingICE(false), IsICE(false) {}
808
809};
810
811/// Represents a variable declaration or definition.
812class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
813public:
814 /// Initialization styles.
815 enum InitializationStyle {
816 /// C-style initialization with assignment
817 CInit,
818
819 /// Call-style initialization (C++98)
820 CallInit,
821
822 /// Direct list-initialization (C++11)
823 ListInit
824 };
825
826 /// Kinds of thread-local storage.
827 enum TLSKind {
828 /// Not a TLS variable.
829 TLS_None,
830
831 /// TLS with a known-constant initializer.
832 TLS_Static,
833
834 /// TLS with a dynamic initializer.
835 TLS_Dynamic
836 };
837
838 /// Return the string used to specify the storage class \p SC.
839 ///
840 /// It is illegal to call this function with SC == None.
841 static const char *getStorageClassSpecifierString(StorageClass SC);
842
843protected:
844 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
845 // have allocated the auxiliary struct of information there.
846 //
847 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
848 // this as *many* VarDecls are ParmVarDecls that don't have default
849 // arguments. We could save some space by moving this pointer union to be
850 // allocated in trailing space when necessary.
851 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
852
853 /// The initializer for this variable or, for a ParmVarDecl, the
854 /// C++ default argument.
855 mutable InitType Init;
856
857private:
858 friend class ASTDeclReader;
859 friend class ASTNodeImporter;
860 friend class StmtIteratorBase;
861
862 class VarDeclBitfields {
863 friend class ASTDeclReader;
864 friend class VarDecl;
865
866 unsigned SClass : 3;
867 unsigned TSCSpec : 2;
868 unsigned InitStyle : 2;
869
870 /// Whether this variable is an ARC pseudo-__strong variable; see
871 /// isARCPseudoStrong() for details.
872 unsigned ARCPseudoStrong : 1;
873 };
874 enum { NumVarDeclBits = 8 };
875
876protected:
877 enum { NumParameterIndexBits = 8 };
878
879 enum DefaultArgKind {
880 DAK_None,
881 DAK_Unparsed,
882 DAK_Uninstantiated,
883 DAK_Normal
884 };
885
886 class ParmVarDeclBitfields {
887 friend class ASTDeclReader;
888 friend class ParmVarDecl;
889
890 unsigned : NumVarDeclBits;
891
892 /// Whether this parameter inherits a default argument from a
893 /// prior declaration.
894 unsigned HasInheritedDefaultArg : 1;
895
896 /// Describes the kind of default argument for this parameter. By default
897 /// this is none. If this is normal, then the default argument is stored in
898 /// the \c VarDecl initializer expression unless we were unable to parse
899 /// (even an invalid) expression for the default argument.
900 unsigned DefaultArgKind : 2;
901
902 /// Whether this parameter undergoes K&R argument promotion.
903 unsigned IsKNRPromoted : 1;
904
905 /// Whether this parameter is an ObjC method parameter or not.
906 unsigned IsObjCMethodParam : 1;
907
908 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
909 /// Otherwise, the number of function parameter scopes enclosing
910 /// the function parameter scope in which this parameter was
911 /// declared.
912 unsigned ScopeDepthOrObjCQuals : 7;
913
914 /// The number of parameters preceding this parameter in the
915 /// function parameter scope in which it was declared.
916 unsigned ParameterIndex : NumParameterIndexBits;
917 };
918
919 class NonParmVarDeclBitfields {
920 friend class ASTDeclReader;
921 friend class ImplicitParamDecl;
922 friend class VarDecl;
923
924 unsigned : NumVarDeclBits;
925
926 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
927 /// Whether this variable is a definition which was demoted due to
928 /// module merge.
929 unsigned IsThisDeclarationADemotedDefinition : 1;
930
931 /// Whether this variable is the exception variable in a C++ catch
932 /// or an Objective-C @catch statement.
933 unsigned ExceptionVar : 1;
934
935 /// Whether this local variable could be allocated in the return
936 /// slot of its function, enabling the named return value optimization
937 /// (NRVO).
938 unsigned NRVOVariable : 1;
939
940 /// Whether this variable is the for-range-declaration in a C++0x
941 /// for-range statement.
942 unsigned CXXForRangeDecl : 1;
943
944 /// Whether this variable is the for-in loop declaration in Objective-C.
945 unsigned ObjCForDecl : 1;
946
947 /// Whether this variable is (C++1z) inline.
948 unsigned IsInline : 1;
949
950 /// Whether this variable has (C++1z) inline explicitly specified.
951 unsigned IsInlineSpecified : 1;
952
953 /// Whether this variable is (C++0x) constexpr.
954 unsigned IsConstexpr : 1;
955
956 /// Whether this variable is the implicit variable for a lambda
957 /// init-capture.
958 unsigned IsInitCapture : 1;
959
960 /// Whether this local extern variable's previous declaration was
961 /// declared in the same block scope. This controls whether we should merge
962 /// the type of this declaration with its previous declaration.
963 unsigned PreviousDeclInSameBlockScope : 1;
964
965 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
966 /// something else.
967 unsigned ImplicitParamKind : 3;
968
969 unsigned EscapingByref : 1;
970 };
971
972 union {
973 unsigned AllBits;
974 VarDeclBitfields VarDeclBits;
975 ParmVarDeclBitfields ParmVarDeclBits;
976 NonParmVarDeclBitfields NonParmVarDeclBits;
977 };
978
979 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
980 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
981 TypeSourceInfo *TInfo, StorageClass SC);
982
983 using redeclarable_base = Redeclarable<VarDecl>;
984
985 VarDecl *getNextRedeclarationImpl() override {
986 return getNextRedeclaration();
987 }
988
989 VarDecl *getPreviousDeclImpl() override {
990 return getPreviousDecl();
991 }
992
993 VarDecl *getMostRecentDeclImpl() override {
994 return getMostRecentDecl();
995 }
996
997public:
998 using redecl_range = redeclarable_base::redecl_range;
999 using redecl_iterator = redeclarable_base::redecl_iterator;
1000
1001 using redeclarable_base::redecls_begin;
1002 using redeclarable_base::redecls_end;
1003 using redeclarable_base::redecls;
1004 using redeclarable_base::getPreviousDecl;
1005 using redeclarable_base::getMostRecentDecl;
1006 using redeclarable_base::isFirstDecl;
1007
1008 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1009 SourceLocation StartLoc, SourceLocation IdLoc,
1010 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1011 StorageClass S);
1012
1013 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1014
1015 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1016
1017 /// Returns the storage class as written in the source. For the
1018 /// computed linkage of symbol, see getLinkage.
1019 StorageClass getStorageClass() const {
1020 return (StorageClass) VarDeclBits.SClass;
1021 }
1022 void setStorageClass(StorageClass SC);
1023
1024 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1025 VarDeclBits.TSCSpec = TSC;
1026 assert(VarDeclBits.TSCSpec == TSC && "truncation")((VarDeclBits.TSCSpec == TSC && "truncation") ? static_cast
<void> (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1026, __PRETTY_FUNCTION__))
;
1027 }
1028 ThreadStorageClassSpecifier getTSCSpec() const {
1029 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1030 }
1031 TLSKind getTLSKind() const;
1032
1033 /// Returns true if a variable with function scope is a non-static local
1034 /// variable.
1035 bool hasLocalStorage() const {
1036 if (getStorageClass() == SC_None) {
1037 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1038 // used to describe variables allocated in global memory and which are
1039 // accessed inside a kernel(s) as read-only variables. As such, variables
1040 // in constant address space cannot have local storage.
1041 if (getType().getAddressSpace() == LangAS::opencl_constant)
1042 return false;
1043 // Second check is for C++11 [dcl.stc]p4.
1044 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1045 }
1046
1047 // Global Named Register (GNU extension)
1048 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1049 return false;
1050
1051 // Return true for: Auto, Register.
1052 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1053
1054 return getStorageClass() >= SC_Auto;
1055 }
1056
1057 /// Returns true if a variable with function scope is a static local
1058 /// variable.
1059 bool isStaticLocal() const {
1060 return (getStorageClass() == SC_Static ||
1061 // C++11 [dcl.stc]p4
1062 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1063 && !isFileVarDecl();
1064 }
1065
1066 /// Returns true if a variable has extern or __private_extern__
1067 /// storage.
1068 bool hasExternalStorage() const {
1069 return getStorageClass() == SC_Extern ||
1070 getStorageClass() == SC_PrivateExtern;
1071 }
1072
1073 /// Returns true for all variables that do not have local storage.
1074 ///
1075 /// This includes all global variables as well as static variables declared
1076 /// within a function.
1077 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1078
1079 /// Get the storage duration of this variable, per C++ [basic.stc].
1080 StorageDuration getStorageDuration() const {
1081 return hasLocalStorage() ? SD_Automatic :
1082 getTSCSpec() ? SD_Thread : SD_Static;
1083 }
1084
1085 /// Compute the language linkage.
1086 LanguageLinkage getLanguageLinkage() const;
1087
1088 /// Determines whether this variable is a variable with external, C linkage.
1089 bool isExternC() const;
1090
1091 /// Determines whether this variable's context is, or is nested within,
1092 /// a C++ extern "C" linkage spec.
1093 bool isInExternCContext() const;
1094
1095 /// Determines whether this variable's context is, or is nested within,
1096 /// a C++ extern "C++" linkage spec.
1097 bool isInExternCXXContext() const;
1098
1099 /// Returns true for local variable declarations other than parameters.
1100 /// Note that this includes static variables inside of functions. It also
1101 /// includes variables inside blocks.
1102 ///
1103 /// void foo() { int x; static int y; extern int z; }
1104 bool isLocalVarDecl() const {
1105 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1106 return false;
1107 if (const DeclContext *DC = getLexicalDeclContext())
1108 return DC->getRedeclContext()->isFunctionOrMethod();
1109 return false;
1110 }
1111
1112 /// Similar to isLocalVarDecl but also includes parameters.
1113 bool isLocalVarDeclOrParm() const {
1114 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1115 }
1116
1117 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1118 bool isFunctionOrMethodVarDecl() const {
1119 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1120 return false;
1121 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1122 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1123 }
1124
1125 /// Determines whether this is a static data member.
1126 ///
1127 /// This will only be true in C++, and applies to, e.g., the
1128 /// variable 'x' in:
1129 /// \code
1130 /// struct S {
1131 /// static int x;
1132 /// };
1133 /// \endcode
1134 bool isStaticDataMember() const {
1135 // If it wasn't static, it would be a FieldDecl.
1136 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1137 }
1138
1139 VarDecl *getCanonicalDecl() override;
1140 const VarDecl *getCanonicalDecl() const {
1141 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1142 }
1143
1144 enum DefinitionKind {
1145 /// This declaration is only a declaration.
1146 DeclarationOnly,
1147
1148 /// This declaration is a tentative definition.
1149 TentativeDefinition,
1150
1151 /// This declaration is definitely a definition.
1152 Definition
1153 };
1154
1155 /// Check whether this declaration is a definition. If this could be
1156 /// a tentative definition (in C), don't check whether there's an overriding
1157 /// definition.
1158 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1159 DefinitionKind isThisDeclarationADefinition() const {
1160 return isThisDeclarationADefinition(getASTContext());
1161 }
1162
1163 /// Check whether this variable is defined in this translation unit.
1164 DefinitionKind hasDefinition(ASTContext &) const;
1165 DefinitionKind hasDefinition() const {
1166 return hasDefinition(getASTContext());
1167 }
1168
1169 /// Get the tentative definition that acts as the real definition in a TU.
1170 /// Returns null if there is a proper definition available.
1171 VarDecl *getActingDefinition();
1172 const VarDecl *getActingDefinition() const {
1173 return const_cast<VarDecl*>(this)->getActingDefinition();
1174 }
1175
1176 /// Get the real (not just tentative) definition for this declaration.
1177 VarDecl *getDefinition(ASTContext &);
1178 const VarDecl *getDefinition(ASTContext &C) const {
1179 return const_cast<VarDecl*>(this)->getDefinition(C);
1180 }
1181 VarDecl *getDefinition() {
1182 return getDefinition(getASTContext());
1183 }
1184 const VarDecl *getDefinition() const {
1185 return const_cast<VarDecl*>(this)->getDefinition();
1186 }
1187
1188 /// Determine whether this is or was instantiated from an out-of-line
1189 /// definition of a static data member.
1190 bool isOutOfLine() const override;
1191
1192 /// Returns true for file scoped variable declaration.
1193 bool isFileVarDecl() const {
1194 Kind K = getKind();
1195 if (K == ParmVar || K == ImplicitParam)
1196 return false;
1197
1198 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1199 return true;
1200
1201 if (isStaticDataMember())
1202 return true;
1203
1204 return false;
1205 }
1206
1207 /// Get the initializer for this variable, no matter which
1208 /// declaration it is attached to.
1209 const Expr *getAnyInitializer() const {
1210 const VarDecl *D;
1211 return getAnyInitializer(D);
1212 }
1213
1214 /// Get the initializer for this variable, no matter which
1215 /// declaration it is attached to. Also get that declaration.
1216 const Expr *getAnyInitializer(const VarDecl *&D) const;
1217
1218 bool hasInit() const;
1219 const Expr *getInit() const {
1220 return const_cast<VarDecl *>(this)->getInit();
1221 }
1222 Expr *getInit();
1223
1224 /// Retrieve the address of the initializer expression.
1225 Stmt **getInitAddress();
1226
1227 void setInit(Expr *I);
1228
1229 /// Determine whether this variable's value can be used in a
1230 /// constant expression, according to the relevant language standard.
1231 /// This only checks properties of the declaration, and does not check
1232 /// whether the initializer is in fact a constant expression.
1233 bool isUsableInConstantExpressions(ASTContext &C) const;
1234
1235 EvaluatedStmt *ensureEvaluatedStmt() const;
1236
1237 /// Attempt to evaluate the value of the initializer attached to this
1238 /// declaration, and produce notes explaining why it cannot be evaluated or is
1239 /// not a constant expression. Returns a pointer to the value if evaluation
1240 /// succeeded, 0 otherwise.
1241 APValue *evaluateValue() const;
1242 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1243
1244 /// Return the already-evaluated value of this variable's
1245 /// initializer, or NULL if the value is not yet known. Returns pointer
1246 /// to untyped APValue if the value could not be evaluated.
1247 APValue *getEvaluatedValue() const;
1248
1249 /// Determines whether it is already known whether the
1250 /// initializer is an integral constant expression or not.
1251 bool isInitKnownICE() const;
1252
1253 /// Determines whether the initializer is an integral constant
1254 /// expression, or in C++11, whether the initializer is a constant
1255 /// expression.
1256 ///
1257 /// \pre isInitKnownICE()
1258 bool isInitICE() const;
1259
1260 /// Determine whether the value of the initializer attached to this
1261 /// declaration is an integral constant expression.
1262 bool checkInitIsICE() const;
1263
1264 void setInitStyle(InitializationStyle Style) {
1265 VarDeclBits.InitStyle = Style;
1266 }
1267
1268 /// The style of initialization for this declaration.
1269 ///
1270 /// C-style initialization is "int x = 1;". Call-style initialization is
1271 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1272 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1273 /// expression for class types. List-style initialization is C++11 syntax,
1274 /// e.g. "int x{1};". Clients can distinguish between different forms of
1275 /// initialization by checking this value. In particular, "int x = {1};" is
1276 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1277 /// Init expression in all three cases is an InitListExpr.
1278 InitializationStyle getInitStyle() const {
1279 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1280 }
1281
1282 /// Whether the initializer is a direct-initializer (list or call).
1283 bool isDirectInit() const {
1284 return getInitStyle() != CInit;
1285 }
1286
1287 /// If this definition should pretend to be a declaration.
1288 bool isThisDeclarationADemotedDefinition() const {
1289 return isa<ParmVarDecl>(this) ? false :
1290 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1291 }
1292
1293 /// This is a definition which should be demoted to a declaration.
1294 ///
1295 /// In some cases (mostly module merging) we can end up with two visible
1296 /// definitions one of which needs to be demoted to a declaration to keep
1297 /// the AST invariants.
1298 void demoteThisDefinitionToDeclaration() {
1299 assert(isThisDeclarationADefinition() && "Not a definition!")((isThisDeclarationADefinition() && "Not a definition!"
) ? static_cast<void> (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1299, __PRETTY_FUNCTION__))
;
1300 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")((!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1300, __PRETTY_FUNCTION__))
;
1301 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1302 }
1303
1304 /// Determine whether this variable is the exception variable in a
1305 /// C++ catch statememt or an Objective-C \@catch statement.
1306 bool isExceptionVariable() const {
1307 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1308 }
1309 void setExceptionVariable(bool EV) {
1310 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1310, __PRETTY_FUNCTION__))
;
1311 NonParmVarDeclBits.ExceptionVar = EV;
1312 }
1313
1314 /// Determine whether this local variable can be used with the named
1315 /// return value optimization (NRVO).
1316 ///
1317 /// The named return value optimization (NRVO) works by marking certain
1318 /// non-volatile local variables of class type as NRVO objects. These
1319 /// locals can be allocated within the return slot of their containing
1320 /// function, in which case there is no need to copy the object to the
1321 /// return slot when returning from the function. Within the function body,
1322 /// each return that returns the NRVO object will have this variable as its
1323 /// NRVO candidate.
1324 bool isNRVOVariable() const {
1325 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1326 }
1327 void setNRVOVariable(bool NRVO) {
1328 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1328, __PRETTY_FUNCTION__))
;
1329 NonParmVarDeclBits.NRVOVariable = NRVO;
1330 }
1331
1332 /// Determine whether this variable is the for-range-declaration in
1333 /// a C++0x for-range statement.
1334 bool isCXXForRangeDecl() const {
1335 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1336 }
1337 void setCXXForRangeDecl(bool FRD) {
1338 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1338, __PRETTY_FUNCTION__))
;
1339 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1340 }
1341
1342 /// Determine whether this variable is a for-loop declaration for a
1343 /// for-in statement in Objective-C.
1344 bool isObjCForDecl() const {
1345 return NonParmVarDeclBits.ObjCForDecl;
1346 }
1347
1348 void setObjCForDecl(bool FRD) {
1349 NonParmVarDeclBits.ObjCForDecl = FRD;
1350 }
1351
1352 /// Determine whether this variable is an ARC pseudo-__strong variable. A
1353 /// pseudo-__strong variable has a __strong-qualified type but does not
1354 /// actually retain the object written into it. Generally such variables are
1355 /// also 'const' for safety. There are 3 cases where this will be set, 1) if
1356 /// the variable is annotated with the objc_externally_retained attribute, 2)
1357 /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
1358 /// loop.
1359 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1360 void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
1361
1362 /// Whether this variable is (C++1z) inline.
1363 bool isInline() const {
1364 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1365 }
1366 bool isInlineSpecified() const {
1367 return isa<ParmVarDecl>(this) ? false
1368 : NonParmVarDeclBits.IsInlineSpecified;
1369 }
1370 void setInlineSpecified() {
1371 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1371, __PRETTY_FUNCTION__))
;
1372 NonParmVarDeclBits.IsInline = true;
1373 NonParmVarDeclBits.IsInlineSpecified = true;
1374 }
1375 void setImplicitlyInline() {
1376 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1376, __PRETTY_FUNCTION__))
;
1377 NonParmVarDeclBits.IsInline = true;
1378 }
1379
1380 /// Whether this variable is (C++11) constexpr.
1381 bool isConstexpr() const {
1382 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1383 }
1384 void setConstexpr(bool IC) {
1385 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1385, __PRETTY_FUNCTION__))
;
1386 NonParmVarDeclBits.IsConstexpr = IC;
1387 }
1388
1389 /// Whether this variable is the implicit variable for a lambda init-capture.
1390 bool isInitCapture() const {
1391 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1392 }
1393 void setInitCapture(bool IC) {
1394 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1394, __PRETTY_FUNCTION__))
;
1395 NonParmVarDeclBits.IsInitCapture = IC;
1396 }
1397
1398 /// Whether this local extern variable declaration's previous declaration
1399 /// was declared in the same block scope. Only correct in C++.
1400 bool isPreviousDeclInSameBlockScope() const {
1401 return isa<ParmVarDecl>(this)
1402 ? false
1403 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1404 }
1405 void setPreviousDeclInSameBlockScope(bool Same) {
1406 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1406, __PRETTY_FUNCTION__))
;
1407 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1408 }
1409
1410 /// Indicates the capture is a __block variable that is captured by a block
1411 /// that can potentially escape (a block for which BlockDecl::doesNotEscape
1412 /// returns false).
1413 bool isEscapingByref() const;
1414
1415 /// Indicates the capture is a __block variable that is never captured by an
1416 /// escaping block.
1417 bool isNonEscapingByref() const;
1418
1419 void setEscapingByref() {
1420 NonParmVarDeclBits.EscapingByref = true;
1421 }
1422
1423 /// Retrieve the variable declaration from which this variable could
1424 /// be instantiated, if it is an instantiation (rather than a non-template).
1425 VarDecl *getTemplateInstantiationPattern() const;
1426
1427 /// If this variable is an instantiated static data member of a
1428 /// class template specialization, returns the templated static data member
1429 /// from which it was instantiated.
1430 VarDecl *getInstantiatedFromStaticDataMember() const;
1431
1432 /// If this variable is an instantiation of a variable template or a
1433 /// static data member of a class template, determine what kind of
1434 /// template specialization or instantiation this is.
1435 TemplateSpecializationKind getTemplateSpecializationKind() const;
1436
1437 /// If this variable is an instantiation of a variable template or a
1438 /// static data member of a class template, determine its point of
1439 /// instantiation.
1440 SourceLocation getPointOfInstantiation() const;
1441
1442 /// If this variable is an instantiation of a static data member of a
1443 /// class template specialization, retrieves the member specialization
1444 /// information.
1445 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1446
1447 /// For a static data member that was instantiated from a static
1448 /// data member of a class template, set the template specialiation kind.
1449 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1450 SourceLocation PointOfInstantiation = SourceLocation());
1451
1452 /// Specify that this variable is an instantiation of the
1453 /// static data member VD.
1454 void setInstantiationOfStaticDataMember(VarDecl *VD,
1455 TemplateSpecializationKind TSK);
1456
1457 /// Retrieves the variable template that is described by this
1458 /// variable declaration.
1459 ///
1460 /// Every variable template is represented as a VarTemplateDecl and a
1461 /// VarDecl. The former contains template properties (such as
1462 /// the template parameter lists) while the latter contains the
1463 /// actual description of the template's
1464 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1465 /// VarDecl that from a VarTemplateDecl, while
1466 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1467 /// a VarDecl.
1468 VarTemplateDecl *getDescribedVarTemplate() const;
1469
1470 void setDescribedVarTemplate(VarTemplateDecl *Template);
1471
1472 // Is this variable known to have a definition somewhere in the complete
1473 // program? This may be true even if the declaration has internal linkage and
1474 // has no definition within this source file.
1475 bool isKnownToBeDefined() const;
1476
1477 /// Do we need to emit an exit-time destructor for this variable?
1478 bool isNoDestroy(const ASTContext &) const;
1479
1480 // Implement isa/cast/dyncast/etc.
1481 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1482 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1483};
1484
1485class ImplicitParamDecl : public VarDecl {
1486 void anchor() override;
1487
1488public:
1489 /// Defines the kind of the implicit parameter: is this an implicit parameter
1490 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1491 /// context or something else.
1492 enum ImplicitParamKind : unsigned {
1493 /// Parameter for Objective-C 'self' argument
1494 ObjCSelf,
1495
1496 /// Parameter for Objective-C '_cmd' argument
1497 ObjCCmd,
1498
1499 /// Parameter for C++ 'this' argument
1500 CXXThis,
1501
1502 /// Parameter for C++ virtual table pointers
1503 CXXVTT,
1504
1505 /// Parameter for captured context
1506 CapturedContext,
1507
1508 /// Other implicit parameter
1509 Other,
1510 };
1511
1512 /// Create implicit parameter.
1513 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1514 SourceLocation IdLoc, IdentifierInfo *Id,
1515 QualType T, ImplicitParamKind ParamKind);
1516 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1517 ImplicitParamKind ParamKind);
1518
1519 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1520
1521 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1522 IdentifierInfo *Id, QualType Type,
1523 ImplicitParamKind ParamKind)
1524 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1525 /*TInfo=*/nullptr, SC_None) {
1526 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1527 setImplicit();
1528 }
1529
1530 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1531 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1532 SourceLocation(), /*Id=*/nullptr, Type,
1533 /*TInfo=*/nullptr, SC_None) {
1534 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1535 setImplicit();
1536 }
1537
1538 /// Returns the implicit parameter kind.
1539 ImplicitParamKind getParameterKind() const {
1540 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1541 }
1542
1543 // Implement isa/cast/dyncast/etc.
1544 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1545 static bool classofKind(Kind K) { return K == ImplicitParam; }
1546};
1547
1548/// Represents a parameter to a function.
1549class ParmVarDecl : public VarDecl {
1550public:
1551 enum { MaxFunctionScopeDepth = 255 };
1552 enum { MaxFunctionScopeIndex = 255 };
1553
1554protected:
1555 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1556 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1557 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1558 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1559 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)((ParmVarDeclBits.HasInheritedDefaultArg == false) ? static_cast
<void> (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1559, __PRETTY_FUNCTION__))
;
1560 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)((ParmVarDeclBits.DefaultArgKind == DAK_None) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1560, __PRETTY_FUNCTION__))
;
1561 assert(ParmVarDeclBits.IsKNRPromoted == false)((ParmVarDeclBits.IsKNRPromoted == false) ? static_cast<void
> (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1561, __PRETTY_FUNCTION__))
;
1562 assert(ParmVarDeclBits.IsObjCMethodParam == false)((ParmVarDeclBits.IsObjCMethodParam == false) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1562, __PRETTY_FUNCTION__))
;
1563 setDefaultArg(DefArg);
1564 }
1565
1566public:
1567 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1568 SourceLocation StartLoc,
1569 SourceLocation IdLoc, IdentifierInfo *Id,
1570 QualType T, TypeSourceInfo *TInfo,
1571 StorageClass S, Expr *DefArg);
1572
1573 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1574
1575 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1576
1577 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1578 ParmVarDeclBits.IsObjCMethodParam = true;
1579 setParameterIndex(parameterIndex);
1580 }
1581
1582 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1583 assert(!ParmVarDeclBits.IsObjCMethodParam)((!ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1583, __PRETTY_FUNCTION__))
;
1584
1585 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1586 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1587, __PRETTY_FUNCTION__))
1587 && "truncation!")((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1587, __PRETTY_FUNCTION__))
;
1588
1589 setParameterIndex(parameterIndex);
1590 }
1591
1592 bool isObjCMethodParameter() const {
1593 return ParmVarDeclBits.IsObjCMethodParam;
1594 }
1595
1596 unsigned getFunctionScopeDepth() const {
1597 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1598 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1599 }
1600
1601 /// Returns the index of this parameter in its prototype or method scope.
1602 unsigned getFunctionScopeIndex() const {
1603 return getParameterIndex();
1604 }
1605
1606 ObjCDeclQualifier getObjCDeclQualifier() const {
1607 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1608 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1609 }
1610 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1611 assert(ParmVarDeclBits.IsObjCMethodParam)((ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1611, __PRETTY_FUNCTION__))
;
1612 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1613 }
1614
1615 /// True if the value passed to this parameter must undergo
1616 /// K&R-style default argument promotion:
1617 ///
1618 /// C99 6.5.2.2.
1619 /// If the expression that denotes the called function has a type
1620 /// that does not include a prototype, the integer promotions are
1621 /// performed on each argument, and arguments that have type float
1622 /// are promoted to double.
1623 bool isKNRPromoted() const {
1624 return ParmVarDeclBits.IsKNRPromoted;
1625 }
1626 void setKNRPromoted(bool promoted) {
1627 ParmVarDeclBits.IsKNRPromoted = promoted;
1628 }
1629
1630 Expr *getDefaultArg();
1631 const Expr *getDefaultArg() const {
1632 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1633 }
1634
1635 void setDefaultArg(Expr *defarg);
1636
1637 /// Retrieve the source range that covers the entire default
1638 /// argument.
1639 SourceRange getDefaultArgRange() const;
1640 void setUninstantiatedDefaultArg(Expr *arg);
1641 Expr *getUninstantiatedDefaultArg();
1642 const Expr *getUninstantiatedDefaultArg() const {
1643 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1644 }
1645
1646 /// Determines whether this parameter has a default argument,
1647 /// either parsed or not.
1648 bool hasDefaultArg() const;
1649
1650 /// Determines whether this parameter has a default argument that has not
1651 /// yet been parsed. This will occur during the processing of a C++ class
1652 /// whose member functions have default arguments, e.g.,
1653 /// @code
1654 /// class X {
1655 /// public:
1656 /// void f(int x = 17); // x has an unparsed default argument now
1657 /// }; // x has a regular default argument now
1658 /// @endcode
1659 bool hasUnparsedDefaultArg() const {
1660 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1661 }
1662
1663 bool hasUninstantiatedDefaultArg() const {
1664 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1665 }
1666
1667 /// Specify that this parameter has an unparsed default argument.
1668 /// The argument will be replaced with a real default argument via
1669 /// setDefaultArg when the class definition enclosing the function
1670 /// declaration that owns this default argument is completed.
1671 void setUnparsedDefaultArg() {
1672 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1673 }
1674
1675 bool hasInheritedDefaultArg() const {
1676 return ParmVarDeclBits.HasInheritedDefaultArg;
1677 }
1678
1679 void setHasInheritedDefaultArg(bool I = true) {
1680 ParmVarDeclBits.HasInheritedDefaultArg = I;
1681 }
1682
1683 QualType getOriginalType() const;
1684
1685 /// Determine whether this parameter is actually a function
1686 /// parameter pack.
1687 bool isParameterPack() const;
1688
1689 /// Sets the function declaration that owns this
1690 /// ParmVarDecl. Since ParmVarDecls are often created before the
1691 /// FunctionDecls that own them, this routine is required to update
1692 /// the DeclContext appropriately.
1693 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1694
1695 // Implement isa/cast/dyncast/etc.
1696 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1697 static bool classofKind(Kind K) { return K == ParmVar; }
1698
1699private:
1700 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1701
1702 void setParameterIndex(unsigned parameterIndex) {
1703 if (parameterIndex >= ParameterIndexSentinel) {
1704 setParameterIndexLarge(parameterIndex);
1705 return;
1706 }
1707
1708 ParmVarDeclBits.ParameterIndex = parameterIndex;
1709 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")((ParmVarDeclBits.ParameterIndex == parameterIndex &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 1709, __PRETTY_FUNCTION__))
;
1710 }
1711 unsigned getParameterIndex() const {
1712 unsigned d = ParmVarDeclBits.ParameterIndex;
1713 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1714 }
1715
1716 void setParameterIndexLarge(unsigned parameterIndex);
1717 unsigned getParameterIndexLarge() const;
1718};
1719
1720enum class MultiVersionKind {
1721 None,
1722 Target,
1723 CPUSpecific,
1724 CPUDispatch
1725};
1726
1727/// Represents a function declaration or definition.
1728///
1729/// Since a given function can be declared several times in a program,
1730/// there may be several FunctionDecls that correspond to that
1731/// function. Only one of those FunctionDecls will be found when
1732/// traversing the list of declarations in the context of the
1733/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1734/// contains all of the information known about the function. Other,
1735/// previous declarations of the function are available via the
1736/// getPreviousDecl() chain.
1737class FunctionDecl : public DeclaratorDecl,
1738 public DeclContext,
1739 public Redeclarable<FunctionDecl> {
1740 // This class stores some data in DeclContext::FunctionDeclBits
1741 // to save some space. Use the provided accessors to access it.
1742public:
1743 /// The kind of templated function a FunctionDecl can be.
1744 enum TemplatedKind {
1745 TK_NonTemplate,
1746 TK_FunctionTemplate,
1747 TK_MemberSpecialization,
1748 TK_FunctionTemplateSpecialization,
1749 TK_DependentFunctionTemplateSpecialization
1750 };
1751
1752private:
1753 /// A new[]'d array of pointers to VarDecls for the formal
1754 /// parameters of this function. This is null if a prototype or if there are
1755 /// no formals.
1756 ParmVarDecl **ParamInfo = nullptr;
1757
1758 LazyDeclStmtPtr Body;
1759
1760 unsigned ODRHash;
1761
1762 /// End part of this FunctionDecl's source range.
1763 ///
1764 /// We could compute the full range in getSourceRange(). However, when we're
1765 /// dealing with a function definition deserialized from a PCH/AST file,
1766 /// we can only compute the full range once the function body has been
1767 /// de-serialized, so it's far better to have the (sometimes-redundant)
1768 /// EndRangeLoc.
1769 SourceLocation EndRangeLoc;
1770
1771 /// The template or declaration that this declaration
1772 /// describes or was instantiated from, respectively.
1773 ///
1774 /// For non-templates, this value will be NULL. For function
1775 /// declarations that describe a function template, this will be a
1776 /// pointer to a FunctionTemplateDecl. For member functions
1777 /// of class template specializations, this will be a MemberSpecializationInfo
1778 /// pointer containing information about the specialization.
1779 /// For function template specializations, this will be a
1780 /// FunctionTemplateSpecializationInfo, which contains information about
1781 /// the template being specialized and the template arguments involved in
1782 /// that specialization.
1783 llvm::PointerUnion4<FunctionTemplateDecl *,
1784 MemberSpecializationInfo *,
1785 FunctionTemplateSpecializationInfo *,
1786 DependentFunctionTemplateSpecializationInfo *>
1787 TemplateOrSpecialization;
1788
1789 /// Provides source/type location info for the declaration name embedded in
1790 /// the DeclaratorDecl base class.
1791 DeclarationNameLoc DNLoc;
1792
1793 /// Specify that this function declaration is actually a function
1794 /// template specialization.
1795 ///
1796 /// \param C the ASTContext.
1797 ///
1798 /// \param Template the function template that this function template
1799 /// specialization specializes.
1800 ///
1801 /// \param TemplateArgs the template arguments that produced this
1802 /// function template specialization from the template.
1803 ///
1804 /// \param InsertPos If non-NULL, the position in the function template
1805 /// specialization set where the function template specialization data will
1806 /// be inserted.
1807 ///
1808 /// \param TSK the kind of template specialization this is.
1809 ///
1810 /// \param TemplateArgsAsWritten location info of template arguments.
1811 ///
1812 /// \param PointOfInstantiation point at which the function template
1813 /// specialization was first instantiated.
1814 void setFunctionTemplateSpecialization(ASTContext &C,
1815 FunctionTemplateDecl *Template,
1816 const TemplateArgumentList *TemplateArgs,
1817 void *InsertPos,
1818 TemplateSpecializationKind TSK,
1819 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1820 SourceLocation PointOfInstantiation);
1821
1822 /// Specify that this record is an instantiation of the
1823 /// member function FD.
1824 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1825 TemplateSpecializationKind TSK);
1826
1827 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1828
1829 // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
1830 // need to access this bit but we want to avoid making ASTDeclWriter
1831 // a friend of FunctionDeclBitfields just for this.
1832 bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
1833
1834 /// Whether an ODRHash has been stored.
1835 bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
1836
1837 /// State that an ODRHash has been stored.
1838 void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
1839
1840protected:
1841 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1842 const DeclarationNameInfo &NameInfo, QualType T,
1843 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1844 bool isConstexprSpecified);
1845
1846 using redeclarable_base = Redeclarable<FunctionDecl>;
1847
1848 FunctionDecl *getNextRedeclarationImpl() override {
1849 return getNextRedeclaration();
1850 }
1851
1852 FunctionDecl *getPreviousDeclImpl() override {
1853 return getPreviousDecl();
1854 }
1855
1856 FunctionDecl *getMostRecentDeclImpl() override {
1857 return getMostRecentDecl();
1858 }
1859
1860public:
1861 friend class ASTDeclReader;
1862 friend class ASTDeclWriter;
1863
1864 using redecl_range = redeclarable_base::redecl_range;
1865 using redecl_iterator = redeclarable_base::redecl_iterator;
1866
1867 using redeclarable_base::redecls_begin;
1868 using redeclarable_base::redecls_end;
1869 using redeclarable_base::redecls;
1870 using redeclarable_base::getPreviousDecl;
1871 using redeclarable_base::getMostRecentDecl;
1872 using redeclarable_base::isFirstDecl;
1873
1874 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1875 SourceLocation StartLoc, SourceLocation NLoc,
1876 DeclarationName N, QualType T,
1877 TypeSourceInfo *TInfo,
1878 StorageClass SC,
1879 bool isInlineSpecified = false,
1880 bool hasWrittenPrototype = true,
1881 bool isConstexprSpecified = false) {
1882 DeclarationNameInfo NameInfo(N, NLoc);
1883 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1884 SC,
1885 isInlineSpecified, hasWrittenPrototype,
1886 isConstexprSpecified);
1887 }
1888
1889 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1890 SourceLocation StartLoc,
1891 const DeclarationNameInfo &NameInfo,
1892 QualType T, TypeSourceInfo *TInfo,
1893 StorageClass SC,
1894 bool isInlineSpecified,
1895 bool hasWrittenPrototype,
1896 bool isConstexprSpecified = false);
1897
1898 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1899
1900 DeclarationNameInfo getNameInfo() const {
1901 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1902 }
1903
1904 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1905 bool Qualified) const override;
1906
1907 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1908
1909 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1910
1911 // Function definitions.
1912 //
1913 // A function declaration may be:
1914 // - a non defining declaration,
1915 // - a definition. A function may be defined because:
1916 // - it has a body, or will have it in the case of late parsing.
1917 // - it has an uninstantiated body. The body does not exist because the
1918 // function is not used yet, but the declaration is considered a
1919 // definition and does not allow other definition of this function.
1920 // - it does not have a user specified body, but it does not allow
1921 // redefinition, because it is deleted/defaulted or is defined through
1922 // some other mechanism (alias, ifunc).
1923
1924 /// Returns true if the function has a body.
1925 ///
1926 /// The function body might be in any of the (re-)declarations of this
1927 /// function. The variant that accepts a FunctionDecl pointer will set that
1928 /// function declaration to the actual declaration containing the body (if
1929 /// there is one).
1930 bool hasBody(const FunctionDecl *&Definition) const;
1931
1932 bool hasBody() const override {
1933 const FunctionDecl* Definition;
1934 return hasBody(Definition);
1935 }
1936
1937 /// Returns whether the function has a trivial body that does not require any
1938 /// specific codegen.
1939 bool hasTrivialBody() const;
1940
1941 /// Returns true if the function has a definition that does not need to be
1942 /// instantiated.
1943 ///
1944 /// The variant that accepts a FunctionDecl pointer will set that function
1945 /// declaration to the declaration that is a definition (if there is one).
1946 bool isDefined(const FunctionDecl *&Definition) const;
1947
1948 virtual bool isDefined() const {
1949 const FunctionDecl* Definition;
1950 return isDefined(Definition);
1951 }
1952
1953 /// Get the definition for this declaration.
1954 FunctionDecl *getDefinition() {
1955 const FunctionDecl *Definition;
1956 if (isDefined(Definition))
1957 return const_cast<FunctionDecl *>(Definition);
1958 return nullptr;
1959 }
1960 const FunctionDecl *getDefinition() const {
1961 return const_cast<FunctionDecl *>(this)->getDefinition();
1962 }
1963
1964 /// Retrieve the body (definition) of the function. The function body might be
1965 /// in any of the (re-)declarations of this function. The variant that accepts
1966 /// a FunctionDecl pointer will set that function declaration to the actual
1967 /// declaration containing the body (if there is one).
1968 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1969 /// unnecessary AST de-serialization of the body.
1970 Stmt *getBody(const FunctionDecl *&Definition) const;
1971
1972 Stmt *getBody() const override {
1973 const FunctionDecl* Definition;
1974 return getBody(Definition);
1975 }
1976
1977 /// Returns whether this specific declaration of the function is also a
1978 /// definition that does not contain uninstantiated body.
1979 ///
1980 /// This does not determine whether the function has been defined (e.g., in a
1981 /// previous definition); for that information, use isDefined.
1982 bool isThisDeclarationADefinition() const {
1983 return isDeletedAsWritten() || isDefaulted() || Body || hasSkippedBody() ||
1984 isLateTemplateParsed() || willHaveBody() || hasDefiningAttr();
1985 }
1986
1987 /// Returns whether this specific declaration of the function has a body.
1988 bool doesThisDeclarationHaveABody() const {
1989 return Body || isLateTemplateParsed();
1990 }
1991
1992 void setBody(Stmt *B);
1993 void setLazyBody(uint64_t Offset) { Body = Offset; }
1994
1995 /// Whether this function is variadic.
1996 bool isVariadic() const;
1997
1998 /// Whether this function is marked as virtual explicitly.
1999 bool isVirtualAsWritten() const {
2000 return FunctionDeclBits.IsVirtualAsWritten;
2001 }
2002
2003 /// State that this function is marked as virtual explicitly.
2004 void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
2005
2006 /// Whether this virtual function is pure, i.e. makes the containing class
2007 /// abstract.
2008 bool isPure() const { return FunctionDeclBits.IsPure; }
2009 void setPure(bool P = true);
2010
2011 /// Whether this templated function will be late parsed.
2012 bool isLateTemplateParsed() const {
2013 return FunctionDeclBits.IsLateTemplateParsed;
2014 }
2015
2016 /// State that this templated function will be late parsed.
2017 void setLateTemplateParsed(bool ILT = true) {
2018 FunctionDeclBits.IsLateTemplateParsed = ILT;
2019 }
2020
2021 /// Whether this function is "trivial" in some specialized C++ senses.
2022 /// Can only be true for default constructors, copy constructors,
2023 /// copy assignment operators, and destructors. Not meaningful until
2024 /// the class has been fully built by Sema.
2025 bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
2026 void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
2027
2028 bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
2029 void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
2030
2031 /// Whether this function is defaulted per C++0x. Only valid for
2032 /// special member functions.
2033 bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
2034 void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
2035
2036 /// Whether this function is explicitly defaulted per C++0x. Only valid
2037 /// for special member functions.
2038 bool isExplicitlyDefaulted() const {
2039 return FunctionDeclBits.IsExplicitlyDefaulted;
2040 }
2041
2042 /// State that this function is explicitly defaulted per C++0x. Only valid
2043 /// for special member functions.
2044 void setExplicitlyDefaulted(bool ED = true) {
2045 FunctionDeclBits.IsExplicitlyDefaulted = ED;
2046 }
2047
2048 /// Whether falling off this function implicitly returns null/zero.
2049 /// If a more specific implicit return value is required, front-ends
2050 /// should synthesize the appropriate return statements.
2051 bool hasImplicitReturnZero() const {
2052 return FunctionDeclBits.HasImplicitReturnZero;
2053 }
2054
2055 /// State that falling off this function implicitly returns null/zero.
2056 /// If a more specific implicit return value is required, front-ends
2057 /// should synthesize the appropriate return statements.
2058 void setHasImplicitReturnZero(bool IRZ) {
2059 FunctionDeclBits.HasImplicitReturnZero = IRZ;
2060 }
2061
2062 /// Whether this function has a prototype, either because one
2063 /// was explicitly written or because it was "inherited" by merging
2064 /// a declaration without a prototype with a declaration that has a
2065 /// prototype.
2066 bool hasPrototype() const {
2067 return hasWrittenPrototype() || hasInheritedPrototype();
2068 }
2069
2070 /// Whether this function has a written prototype.
2071 bool hasWrittenPrototype() const {
2072 return FunctionDeclBits.HasWrittenPrototype;
2073 }
2074
2075 /// State that this function has a written prototype.
2076 void setHasWrittenPrototype(bool P = true) {
2077 FunctionDeclBits.HasWrittenPrototype = P;
2078 }
2079
2080 /// Whether this function inherited its prototype from a
2081 /// previous declaration.
2082 bool hasInheritedPrototype() const {
2083 return FunctionDeclBits.HasInheritedPrototype;
2084 }
2085
2086 /// State that this function inherited its prototype from a
2087 /// previous declaration.
2088 void setHasInheritedPrototype(bool P = true) {
2089 FunctionDeclBits.HasInheritedPrototype = P;
2090 }
2091
2092 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2093 bool isConstexpr() const { return FunctionDeclBits.IsConstexpr; }
2094 void setConstexpr(bool IC) { FunctionDeclBits.IsConstexpr = IC; }
2095
2096 /// Whether the instantiation of this function is pending.
2097 /// This bit is set when the decision to instantiate this function is made
2098 /// and unset if and when the function body is created. That leaves out
2099 /// cases where instantiation did not happen because the template definition
2100 /// was not seen in this TU. This bit remains set in those cases, under the
2101 /// assumption that the instantiation will happen in some other TU.
2102 bool instantiationIsPending() const {
2103 return FunctionDeclBits.InstantiationIsPending;
2104 }
2105
2106 /// State that the instantiation of this function is pending.
2107 /// (see instantiationIsPending)
2108 void setInstantiationIsPending(bool IC) {
2109 FunctionDeclBits.InstantiationIsPending = IC;
2110 }
2111
2112 /// Indicates the function uses __try.
2113 bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
2114 void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
2115
2116 /// Whether this function has been deleted.
2117 ///
2118 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2119 /// acts like a normal function, except that it cannot actually be
2120 /// called or have its address taken. Deleted functions are
2121 /// typically used in C++ overload resolution to attract arguments
2122 /// whose type or lvalue/rvalue-ness would permit the use of a
2123 /// different overload that would behave incorrectly. For example,
2124 /// one might use deleted functions to ban implicit conversion from
2125 /// a floating-point number to an Integer type:
2126 ///
2127 /// @code
2128 /// struct Integer {
2129 /// Integer(long); // construct from a long
2130 /// Integer(double) = delete; // no construction from float or double
2131 /// Integer(long double) = delete; // no construction from long double
2132 /// };
2133 /// @endcode
2134 // If a function is deleted, its first declaration must be.
2135 bool isDeleted() const {
2136 return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
2137 }
2138
2139 bool isDeletedAsWritten() const {
2140 return FunctionDeclBits.IsDeleted && !isDefaulted();
2141 }
2142
2143 void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
2144
2145 /// Determines whether this function is "main", which is the
2146 /// entry point into an executable program.
2147 bool isMain() const;
2148
2149 /// Determines whether this function is a MSVCRT user defined entry
2150 /// point.
2151 bool isMSVCRTEntryPoint() const;
2152
2153 /// Determines whether this operator new or delete is one
2154 /// of the reserved global placement operators:
2155 /// void *operator new(size_t, void *);
2156 /// void *operator new[](size_t, void *);
2157 /// void operator delete(void *, void *);
2158 /// void operator delete[](void *, void *);
2159 /// These functions have special behavior under [new.delete.placement]:
2160 /// These functions are reserved, a C++ program may not define
2161 /// functions that displace the versions in the Standard C++ library.
2162 /// The provisions of [basic.stc.dynamic] do not apply to these
2163 /// reserved placement forms of operator new and operator delete.
2164 ///
2165 /// This function must be an allocation or deallocation function.
2166 bool isReservedGlobalPlacementOperator() const;
2167
2168 /// Determines whether this function is one of the replaceable
2169 /// global allocation functions:
2170 /// void *operator new(size_t);
2171 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2172 /// void *operator new[](size_t);
2173 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2174 /// void operator delete(void *) noexcept;
2175 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2176 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2177 /// void operator delete[](void *) noexcept;
2178 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2179 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2180 /// These functions have special behavior under C++1y [expr.new]:
2181 /// An implementation is allowed to omit a call to a replaceable global
2182 /// allocation function. [...]
2183 ///
2184 /// If this function is an aligned allocation/deallocation function, return
2185 /// true through IsAligned.
2186 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2187
2188 /// Determine whether this is a destroying operator delete.
2189 bool isDestroyingOperatorDelete() const;
2190
2191 /// Compute the language linkage.
2192 LanguageLinkage getLanguageLinkage() const;
2193
2194 /// Determines whether this function is a function with
2195 /// external, C linkage.
2196 bool isExternC() const;
2197
2198 /// Determines whether this function's context is, or is nested within,
2199 /// a C++ extern "C" linkage spec.
2200 bool isInExternCContext() const;
2201
2202 /// Determines whether this function's context is, or is nested within,
2203 /// a C++ extern "C++" linkage spec.
2204 bool isInExternCXXContext() const;
2205
2206 /// Determines whether this is a global function.
2207 bool isGlobal() const;
2208
2209 /// Determines whether this function is known to be 'noreturn', through
2210 /// an attribute on its declaration or its type.
2211 bool isNoReturn() const;
2212
2213 /// True if the function was a definition but its body was skipped.
2214 bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
2215 void setHasSkippedBody(bool Skipped = true) {
2216 FunctionDeclBits.HasSkippedBody = Skipped;
2217 }
2218
2219 /// True if this function will eventually have a body, once it's fully parsed.
2220 bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
2221 void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
2222
2223 /// True if this function is considered a multiversioned function.
2224 bool isMultiVersion() const {
2225 return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
2226 }
2227
2228 /// Sets the multiversion state for this declaration and all of its
2229 /// redeclarations.
2230 void setIsMultiVersion(bool V = true) {
2231 getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
2232 }
2233
2234 /// Gets the kind of multiversioning attribute this declaration has. Note that
2235 /// this can return a value even if the function is not multiversion, such as
2236 /// the case of 'target'.
2237 MultiVersionKind getMultiVersionKind() const;
2238
2239
2240 /// True if this function is a multiversioned dispatch function as a part of
2241 /// the cpu_specific/cpu_dispatch functionality.
2242 bool isCPUDispatchMultiVersion() const;
2243 /// True if this function is a multiversioned processor specific function as a
2244 /// part of the cpu_specific/cpu_dispatch functionality.
2245 bool isCPUSpecificMultiVersion() const;
2246
2247 /// True if this function is a multiversioned dispatch function as a part of
2248 /// the target functionality.
2249 bool isTargetMultiVersion() const;
2250
2251 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2252
2253 FunctionDecl *getCanonicalDecl() override;
2254 const FunctionDecl *getCanonicalDecl() const {
2255 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2256 }
2257
2258 unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
2259
2260 // ArrayRef interface to parameters.
2261 ArrayRef<ParmVarDecl *> parameters() const {
2262 return {ParamInfo, getNumParams()};
2263 }
2264 MutableArrayRef<ParmVarDecl *> parameters() {
2265 return {ParamInfo, getNumParams()};
2266 }
2267
2268 // Iterator access to formal parameters.
2269 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2270 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2271
2272 bool param_empty() const { return parameters().empty(); }
2273 param_iterator param_begin() { return parameters().begin(); }
2274 param_iterator param_end() { return parameters().end(); }
2275 param_const_iterator param_begin() const { return parameters().begin(); }
2276 param_const_iterator param_end() const { return parameters().end(); }
2277 size_t param_size() const { return parameters().size(); }
2278
2279 /// Return the number of parameters this function must have based on its
2280 /// FunctionType. This is the length of the ParamInfo array after it has been
2281 /// created.
2282 unsigned getNumParams() const;
2283
2284 const ParmVarDecl *getParamDecl(unsigned i) const {
2285 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 2285, __PRETTY_FUNCTION__))
;
34
Assuming the condition is true
35
'?' condition is true
2286 return ParamInfo[i];
36
Returning pointer
2287 }
2288 ParmVarDecl *getParamDecl(unsigned i) {
2289 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 2289, __PRETTY_FUNCTION__))
;
2290 return ParamInfo[i];
2291 }
2292 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2293 setParams(getASTContext(), NewParamInfo);
2294 }
2295
2296 /// Returns the minimum number of arguments needed to call this function. This
2297 /// may be fewer than the number of function parameters, if some of the
2298 /// parameters have default arguments (in C++).
2299 unsigned getMinRequiredArguments() const;
2300
2301 QualType getReturnType() const {
2302 return getType()->castAs<FunctionType>()->getReturnType();
2303 }
2304
2305 /// Attempt to compute an informative source range covering the
2306 /// function return type. This may omit qualifiers and other information with
2307 /// limited representation in the AST.
2308 SourceRange getReturnTypeSourceRange() const;
2309
2310 /// Get the declared return type, which may differ from the actual return
2311 /// type if the return type is deduced.
2312 QualType getDeclaredReturnType() const {
2313 auto *TSI = getTypeSourceInfo();
2314 QualType T = TSI ? TSI->getType() : getType();
2315 return T->castAs<FunctionType>()->getReturnType();
2316 }
2317
2318 /// Attempt to compute an informative source range covering the
2319 /// function exception specification, if any.
2320 SourceRange getExceptionSpecSourceRange() const;
2321
2322 /// Determine the type of an expression that calls this function.
2323 QualType getCallResultType() const {
2324 return getType()->castAs<FunctionType>()->getCallResultType(
2325 getASTContext());
2326 }
2327
2328 /// Returns the storage class as written in the source. For the
2329 /// computed linkage of symbol, see getLinkage.
2330 StorageClass getStorageClass() const {
2331 return static_cast<StorageClass>(FunctionDeclBits.SClass);
2332 }
2333
2334 /// Sets the storage class as written in the source.
2335 void setStorageClass(StorageClass SClass) {
2336 FunctionDeclBits.SClass = SClass;
2337 }
2338
2339 /// Determine whether the "inline" keyword was specified for this
2340 /// function.
2341 bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
2342
2343 /// Set whether the "inline" keyword was specified for this function.
2344 void setInlineSpecified(bool I) {
2345 FunctionDeclBits.IsInlineSpecified = I;
2346 FunctionDeclBits.IsInline = I;
2347 }
2348
2349 /// Flag that this function is implicitly inline.
2350 void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
2351
2352 /// Determine whether this function should be inlined, because it is
2353 /// either marked "inline" or "constexpr" or is a member function of a class
2354 /// that was defined in the class body.
2355 bool isInlined() const { return FunctionDeclBits.IsInline; }
2356
2357 /// Whether this function is marked as explicit explicitly.
2358 bool isExplicitSpecified() const {
2359 return FunctionDeclBits.IsExplicitSpecified;
2360 }
2361
2362 /// State that this function is marked as explicit explicitly.
2363 void setExplicitSpecified(bool ExpSpec = true) {
2364 FunctionDeclBits.IsExplicitSpecified = ExpSpec;
2365 }
2366
2367 bool isInlineDefinitionExternallyVisible() const;
2368
2369 bool isMSExternInline() const;
2370
2371 bool doesDeclarationForceExternallyVisibleDefinition() const;
2372
2373 /// Whether this function declaration represents an C++ overloaded
2374 /// operator, e.g., "operator+".
2375 bool isOverloadedOperator() const {
2376 return getOverloadedOperator() != OO_None;
2377 }
2378
2379 OverloadedOperatorKind getOverloadedOperator() const;
2380
2381 const IdentifierInfo *getLiteralIdentifier() const;
2382
2383 /// If this function is an instantiation of a member function
2384 /// of a class template specialization, retrieves the function from
2385 /// which it was instantiated.
2386 ///
2387 /// This routine will return non-NULL for (non-templated) member
2388 /// functions of class templates and for instantiations of function
2389 /// templates. For example, given:
2390 ///
2391 /// \code
2392 /// template<typename T>
2393 /// struct X {
2394 /// void f(T);
2395 /// };
2396 /// \endcode
2397 ///
2398 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2399 /// whose parent is the class template specialization X<int>. For
2400 /// this declaration, getInstantiatedFromFunction() will return
2401 /// the FunctionDecl X<T>::A. When a complete definition of
2402 /// X<int>::A is required, it will be instantiated from the
2403 /// declaration returned by getInstantiatedFromMemberFunction().
2404 FunctionDecl *getInstantiatedFromMemberFunction() const;
2405
2406 /// What kind of templated function this is.
2407 TemplatedKind getTemplatedKind() const;
2408
2409 /// If this function is an instantiation of a member function of a
2410 /// class template specialization, retrieves the member specialization
2411 /// information.
2412 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2413
2414 /// Specify that this record is an instantiation of the
2415 /// member function FD.
2416 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2417 TemplateSpecializationKind TSK) {
2418 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2419 }
2420
2421 /// Retrieves the function template that is described by this
2422 /// function declaration.
2423 ///
2424 /// Every function template is represented as a FunctionTemplateDecl
2425 /// and a FunctionDecl (or something derived from FunctionDecl). The
2426 /// former contains template properties (such as the template
2427 /// parameter lists) while the latter contains the actual
2428 /// description of the template's
2429 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2430 /// FunctionDecl that describes the function template,
2431 /// getDescribedFunctionTemplate() retrieves the
2432 /// FunctionTemplateDecl from a FunctionDecl.
2433 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2434
2435 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2436
2437 /// Determine whether this function is a function template
2438 /// specialization.
2439 bool isFunctionTemplateSpecialization() const {
2440 return getPrimaryTemplate() != nullptr;
2441 }
2442
2443 /// Retrieve the class scope template pattern that this function
2444 /// template specialization is instantiated from.
2445 FunctionDecl *getClassScopeSpecializationPattern() const;
2446
2447 /// If this function is actually a function template specialization,
2448 /// retrieve information about this function template specialization.
2449 /// Otherwise, returns NULL.
2450 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2451
2452 /// Determines whether this function is a function template
2453 /// specialization or a member of a class template specialization that can
2454 /// be implicitly instantiated.
2455 bool isImplicitlyInstantiable() const;
2456
2457 /// Determines if the given function was instantiated from a
2458 /// function template.
2459 bool isTemplateInstantiation() const;
2460
2461 /// Retrieve the function declaration from which this function could
2462 /// be instantiated, if it is an instantiation (rather than a non-template
2463 /// or a specialization, for example).
2464 FunctionDecl *getTemplateInstantiationPattern() const;
2465
2466 /// Retrieve the primary template that this function template
2467 /// specialization either specializes or was instantiated from.
2468 ///
2469 /// If this function declaration is not a function template specialization,
2470 /// returns NULL.
2471 FunctionTemplateDecl *getPrimaryTemplate() const;
2472
2473 /// Retrieve the template arguments used to produce this function
2474 /// template specialization from the primary template.
2475 ///
2476 /// If this function declaration is not a function template specialization,
2477 /// returns NULL.
2478 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2479
2480 /// Retrieve the template argument list as written in the sources,
2481 /// if any.
2482 ///
2483 /// If this function declaration is not a function template specialization
2484 /// or if it had no explicit template argument list, returns NULL.
2485 /// Note that it an explicit template argument list may be written empty,
2486 /// e.g., template<> void foo<>(char* s);
2487 const ASTTemplateArgumentListInfo*
2488 getTemplateSpecializationArgsAsWritten() const;
2489
2490 /// Specify that this function declaration is actually a function
2491 /// template specialization.
2492 ///
2493 /// \param Template the function template that this function template
2494 /// specialization specializes.
2495 ///
2496 /// \param TemplateArgs the template arguments that produced this
2497 /// function template specialization from the template.
2498 ///
2499 /// \param InsertPos If non-NULL, the position in the function template
2500 /// specialization set where the function template specialization data will
2501 /// be inserted.
2502 ///
2503 /// \param TSK the kind of template specialization this is.
2504 ///
2505 /// \param TemplateArgsAsWritten location info of template arguments.
2506 ///
2507 /// \param PointOfInstantiation point at which the function template
2508 /// specialization was first instantiated.
2509 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2510 const TemplateArgumentList *TemplateArgs,
2511 void *InsertPos,
2512 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2513 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2514 SourceLocation PointOfInstantiation = SourceLocation()) {
2515 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2516 InsertPos, TSK, TemplateArgsAsWritten,
2517 PointOfInstantiation);
2518 }
2519
2520 /// Specifies that this function declaration is actually a
2521 /// dependent function template specialization.
2522 void setDependentTemplateSpecialization(ASTContext &Context,
2523 const UnresolvedSetImpl &Templates,
2524 const TemplateArgumentListInfo &TemplateArgs);
2525
2526 DependentFunctionTemplateSpecializationInfo *
2527 getDependentSpecializationInfo() const;
2528
2529 /// Determine what kind of template instantiation this function
2530 /// represents.
2531 TemplateSpecializationKind getTemplateSpecializationKind() const;
2532
2533 /// Determine what kind of template instantiation this function
2534 /// represents.
2535 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2536 SourceLocation PointOfInstantiation = SourceLocation());
2537
2538 /// Retrieve the (first) point of instantiation of a function template
2539 /// specialization or a member of a class template specialization.
2540 ///
2541 /// \returns the first point of instantiation, if this function was
2542 /// instantiated from a template; otherwise, returns an invalid source
2543 /// location.
2544 SourceLocation getPointOfInstantiation() const;
2545
2546 /// Determine whether this is or was instantiated from an out-of-line
2547 /// definition of a member function.
2548 bool isOutOfLine() const override;
2549
2550 /// Identify a memory copying or setting function.
2551 /// If the given function is a memory copy or setting function, returns
2552 /// the corresponding Builtin ID. If the function is not a memory function,
2553 /// returns 0.
2554 unsigned getMemoryFunctionKind() const;
2555
2556 /// Returns ODRHash of the function. This value is calculated and
2557 /// stored on first call, then the stored value returned on the other calls.
2558 unsigned getODRHash();
2559
2560 /// Returns cached ODRHash of the function. This must have been previously
2561 /// computed and stored.
2562 unsigned getODRHash() const;
2563
2564 // Implement isa/cast/dyncast/etc.
2565 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2566 static bool classofKind(Kind K) {
2567 return K >= firstFunction && K <= lastFunction;
2568 }
2569 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2570 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2571 }
2572 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2573 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2574 }
2575};
2576
2577/// Represents a member of a struct/union/class.
2578class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2579 unsigned BitField : 1;
2580 unsigned Mutable : 1;
2581 mutable unsigned CachedFieldIndex : 30;
2582
2583 /// The kinds of value we can store in InitializerOrBitWidth.
2584 ///
2585 /// Note that this is compatible with InClassInitStyle except for
2586 /// ISK_CapturedVLAType.
2587 enum InitStorageKind {
2588 /// If the pointer is null, there's nothing special. Otherwise,
2589 /// this is a bitfield and the pointer is the Expr* storing the
2590 /// bit-width.
2591 ISK_NoInit = (unsigned) ICIS_NoInit,
2592
2593 /// The pointer is an (optional due to delayed parsing) Expr*
2594 /// holding the copy-initializer.
2595 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2596
2597 /// The pointer is an (optional due to delayed parsing) Expr*
2598 /// holding the list-initializer.
2599 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2600
2601 /// The pointer is a VariableArrayType* that's been captured;
2602 /// the enclosing context is a lambda or captured statement.
2603 ISK_CapturedVLAType,
2604 };
2605
2606 /// If this is a bitfield with a default member initializer, this
2607 /// structure is used to represent the two expressions.
2608 struct InitAndBitWidth {
2609 Expr *Init;
2610 Expr *BitWidth;
2611 };
2612
2613 /// Storage for either the bit-width, the in-class initializer, or
2614 /// both (via InitAndBitWidth), or the captured variable length array bound.
2615 ///
2616 /// If the storage kind is ISK_InClassCopyInit or
2617 /// ISK_InClassListInit, but the initializer is null, then this
2618 /// field has an in-class initializer that has not yet been parsed
2619 /// and attached.
2620 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2621 // overwhelmingly common case that we have none of these things.
2622 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2623
2624protected:
2625 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2626 SourceLocation IdLoc, IdentifierInfo *Id,
2627 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2628 InClassInitStyle InitStyle)
2629 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2630 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2631 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2632 if (BW)
2633 setBitWidth(BW);
2634 }
2635
2636public:
2637 friend class ASTDeclReader;
2638 friend class ASTDeclWriter;
2639
2640 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2641 SourceLocation StartLoc, SourceLocation IdLoc,
2642 IdentifierInfo *Id, QualType T,
2643 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2644 InClassInitStyle InitStyle);
2645
2646 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2647
2648 /// Returns the index of this field within its record,
2649 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2650 unsigned getFieldIndex() const;
2651
2652 /// Determines whether this field is mutable (C++ only).
2653 bool isMutable() const { return Mutable; }
2654
2655 /// Determines whether this field is a bitfield.
2656 bool isBitField() const { return BitField; }
2657
2658 /// Determines whether this is an unnamed bitfield.
2659 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2660
2661 /// Determines whether this field is a
2662 /// representative for an anonymous struct or union. Such fields are
2663 /// unnamed and are implicitly generated by the implementation to
2664 /// store the data for the anonymous union or struct.
2665 bool isAnonymousStructOrUnion() const;
2666
2667 Expr *getBitWidth() const {
2668 if (!BitField)
2669 return nullptr;
2670 void *Ptr = InitStorage.getPointer();
2671 if (getInClassInitStyle())
2672 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2673 return static_cast<Expr*>(Ptr);
2674 }
2675
2676 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2677
2678 /// Set the bit-field width for this member.
2679 // Note: used by some clients (i.e., do not remove it).
2680 void setBitWidth(Expr *Width) {
2681 assert(!hasCapturedVLAType() && !BitField &&((!hasCapturedVLAType() && !BitField && "bit width or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 2682, __PRETTY_FUNCTION__))
2682 "bit width or captured type already set")((!hasCapturedVLAType() && !BitField && "bit width or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 2682, __PRETTY_FUNCTION__))
;
2683 assert(Width && "no bit width specified")((Width && "no bit width specified") ? static_cast<
void> (0) : __assert_fail ("Width && \"no bit width specified\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 2683, __PRETTY_FUNCTION__))
;
2684 InitStorage.setPointer(
2685 InitStorage.getInt()
2686 ? new (getASTContext())
2687 InitAndBitWidth{getInClassInitializer(), Width}
2688 : static_cast<void*>(Width));
2689 BitField = true;
2690 }
2691
2692 /// Remove the bit-field width from this member.
2693 // Note: used by some clients (i.e., do not remove it).
2694 void removeBitWidth() {
2695 assert(isBitField() && "no bitfield width to remove")((isBitField() && "no bitfield width to remove") ? static_cast
<void> (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 2695, __PRETTY_FUNCTION__))
;
2696 InitStorage.setPointer(getInClassInitializer());
2697 BitField = false;
2698 }
2699
2700 /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
2701 /// at all and instead act as a separator between contiguous runs of other
2702 /// bit-fields.
2703 bool isZeroLengthBitField(const ASTContext &Ctx) const;
2704
2705 /// Get the kind of (C++11) default member initializer that this field has.
2706 InClassInitStyle getInClassInitStyle() const {
2707 InitStorageKind storageKind = InitStorage.getInt();
2708 return (storageKind == ISK_CapturedVLAType
2709 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2710 }
2711
2712 /// Determine whether this member has a C++11 default member initializer.
2713 bool hasInClassInitializer() const {
2714 return getInClassInitStyle() != ICIS_NoInit;
2715 }
2716
2717 /// Get the C++11 default member initializer for this member, or null if one
2718 /// has not been set. If a valid declaration has a default member initializer,
2719 /// but this returns null, then we have not parsed and attached it yet.
2720 Expr *getInClassInitializer() const {
2721 if (!hasInClassInitializer())
2722 return nullptr;
2723 void *Ptr = InitStorage.getPointer();
2724 if (BitField)
2725 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2726 return static_cast<Expr*>(Ptr);
2727 }
2728
2729 /// Set the C++11 in-class initializer for this member.
2730 void setInClassInitializer(Expr *Init) {
2731 assert(hasInClassInitializer() && !getInClassInitializer())((hasInClassInitializer() && !getInClassInitializer()
) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 2731, __PRETTY_FUNCTION__))
;
2732 if (BitField)
2733 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2734 else
2735 InitStorage.setPointer(Init);
2736 }
2737
2738 /// Remove the C++11 in-class initializer from this member.
2739 void removeInClassInitializer() {
2740 assert(hasInClassInitializer() && "no initializer to remove")((hasInClassInitializer() && "no initializer to remove"
) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 2740, __PRETTY_FUNCTION__))
;
2741 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2742 }
2743
2744 /// Determine whether this member captures the variable length array
2745 /// type.
2746 bool hasCapturedVLAType() const {
2747 return InitStorage.getInt() == ISK_CapturedVLAType;
2748 }
2749
2750 /// Get the captured variable length array type.
2751 const VariableArrayType *getCapturedVLAType() const {
2752 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2753 InitStorage.getPointer())
2754 : nullptr;
2755 }
2756
2757 /// Set the captured variable length array type for this field.
2758 void setCapturedVLAType(const VariableArrayType *VLAType);
2759
2760 /// Returns the parent of this field declaration, which
2761 /// is the struct in which this field is defined.
2762 const RecordDecl *getParent() const {
2763 return cast<RecordDecl>(getDeclContext());
2764 }
2765
2766 RecordDecl *getParent() {
2767 return cast<RecordDecl>(getDeclContext());
2768 }
2769
2770 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2771
2772 /// Retrieves the canonical declaration of this field.
2773 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2774 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2775
2776 // Implement isa/cast/dyncast/etc.
2777 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2778 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2779};
2780
2781/// An instance of this object exists for each enum constant
2782/// that is defined. For example, in "enum X {a,b}", each of a/b are
2783/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2784/// TagType for the X EnumDecl.
2785class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2786 Stmt *Init; // an integer constant expression
2787 llvm::APSInt Val; // The value.
2788
2789protected:
2790 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2791 IdentifierInfo *Id, QualType T, Expr *E,
2792 const llvm::APSInt &V)
2793 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2794
2795public:
2796 friend class StmtIteratorBase;
2797
2798 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2799 SourceLocation L, IdentifierInfo *Id,
2800 QualType T, Expr *E,
2801 const llvm::APSInt &V);
2802 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2803
2804 const Expr *getInitExpr() const { return (const Expr*) Init; }
2805 Expr *getInitExpr() { return (Expr*) Init; }
2806 const llvm::APSInt &getInitVal() const { return Val; }
2807
2808 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2809 void setInitVal(const llvm::APSInt &V) { Val = V; }
2810
2811 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2812
2813 /// Retrieves the canonical declaration of this enumerator.
2814 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2815 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2816
2817 // Implement isa/cast/dyncast/etc.
2818 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2819 static bool classofKind(Kind K) { return K == EnumConstant; }
2820};
2821
2822/// Represents a field injected from an anonymous union/struct into the parent
2823/// scope. These are always implicit.
2824class IndirectFieldDecl : public ValueDecl,
2825 public Mergeable<IndirectFieldDecl> {
2826 NamedDecl **Chaining;
2827 unsigned ChainingSize;
2828
2829 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2830 DeclarationName N, QualType T,
2831 MutableArrayRef<NamedDecl *> CH);
2832
2833 void anchor() override;
2834
2835public:
2836 friend class ASTDeclReader;
2837
2838 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2839 SourceLocation L, IdentifierInfo *Id,
2840 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2841
2842 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2843
2844 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2845
2846 ArrayRef<NamedDecl *> chain() const {
2847 return llvm::makeArrayRef(Chaining, ChainingSize);
2848 }
2849 chain_iterator chain_begin() const { return chain().begin(); }
2850 chain_iterator chain_end() const { return chain().end(); }
2851
2852 unsigned getChainingSize() const { return ChainingSize; }
2853
2854 FieldDecl *getAnonField() const {
2855 assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail
("chain().size() >= 2", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 2855, __PRETTY_FUNCTION__))
;
2856 return cast<FieldDecl>(chain().back());
2857 }
2858
2859 VarDecl *getVarDecl() const {
2860 assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail
("chain().size() >= 2", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 2860, __PRETTY_FUNCTION__))
;
2861 return dyn_cast<VarDecl>(chain().front());
2862 }
2863
2864 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2865 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2866
2867 // Implement isa/cast/dyncast/etc.
2868 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2869 static bool classofKind(Kind K) { return K == IndirectField; }
2870};
2871
2872/// Represents a declaration of a type.
2873class TypeDecl : public NamedDecl {
2874 friend class ASTContext;
2875
2876 /// This indicates the Type object that represents
2877 /// this TypeDecl. It is a cache maintained by
2878 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2879 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2880 mutable const Type *TypeForDecl = nullptr;
2881
2882 /// The start of the source range for this declaration.
2883 SourceLocation LocStart;
2884
2885 void anchor() override;
2886
2887protected:
2888 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2889 SourceLocation StartL = SourceLocation())
2890 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2891
2892public:
2893 // Low-level accessor. If you just want the type defined by this node,
2894 // check out ASTContext::getTypeDeclType or one of
2895 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2896 // already know the specific kind of node this is.
2897 const Type *getTypeForDecl() const { return TypeForDecl; }
2898 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2899
2900 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
2901 void setLocStart(SourceLocation L) { LocStart = L; }
2902 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2903 if (LocStart.isValid())
2904 return SourceRange(LocStart, getLocation());
2905 else
2906 return SourceRange(getLocation());
2907 }
2908
2909 // Implement isa/cast/dyncast/etc.
2910 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2911 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2912};
2913
2914/// Base class for declarations which introduce a typedef-name.
2915class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2916 struct alignas(8) ModedTInfo {
2917 TypeSourceInfo *first;
2918 QualType second;
2919 };
2920
2921 /// If int part is 0, we have not computed IsTransparentTag.
2922 /// Otherwise, IsTransparentTag is (getInt() >> 1).
2923 mutable llvm::PointerIntPair<
2924 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
2925 MaybeModedTInfo;
2926
2927 void anchor() override;
2928
2929protected:
2930 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2931 SourceLocation StartLoc, SourceLocation IdLoc,
2932 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2933 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2934 MaybeModedTInfo(TInfo, 0) {}
2935
2936 using redeclarable_base = Redeclarable<TypedefNameDecl>;
2937
2938 TypedefNameDecl *getNextRedeclarationImpl() override {
2939 return getNextRedeclaration();
2940 }
2941
2942 TypedefNameDecl *getPreviousDeclImpl() override {
2943 return getPreviousDecl();
2944 }
2945
2946 TypedefNameDecl *getMostRecentDeclImpl() override {
2947 return getMostRecentDecl();
2948 }
2949
2950public:
2951 using redecl_range = redeclarable_base::redecl_range;
2952 using redecl_iterator = redeclarable_base::redecl_iterator;
2953
2954 using redeclarable_base::redecls_begin;
2955 using redeclarable_base::redecls_end;
2956 using redeclarable_base::redecls;
2957 using redeclarable_base::getPreviousDecl;
2958 using redeclarable_base::getMostRecentDecl;
2959 using redeclarable_base::isFirstDecl;
2960
2961 bool isModed() const {
2962 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
2963 }
2964
2965 TypeSourceInfo *getTypeSourceInfo() const {
2966 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
2967 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
2968 }
2969
2970 QualType getUnderlyingType() const {
2971 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
2972 : MaybeModedTInfo.getPointer()
2973 .get<TypeSourceInfo *>()
2974 ->getType();
2975 }
2976
2977 void setTypeSourceInfo(TypeSourceInfo *newType) {
2978 MaybeModedTInfo.setPointer(newType);
2979 }
2980
2981 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2982 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
2983 ModedTInfo({unmodedTSI, modedTy}));
2984 }
2985
2986 /// Retrieves the canonical declaration of this typedef-name.
2987 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2988 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2989
2990 /// Retrieves the tag declaration for which this is the typedef name for
2991 /// linkage purposes, if any.
2992 ///
2993 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2994 /// this typedef declaration.
2995 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2996
2997 /// Determines if this typedef shares a name and spelling location with its
2998 /// underlying tag type, as is the case with the NS_ENUM macro.
2999 bool isTransparentTag() const {
3000 if (MaybeModedTInfo.getInt())
3001 return MaybeModedTInfo.getInt() & 0x2;
3002 return isTransparentTagSlow();
3003 }
3004
3005 // Implement isa/cast/dyncast/etc.
3006 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3007 static bool classofKind(Kind K) {
3008 return K >= firstTypedefName && K <= lastTypedefName;
3009 }
3010
3011private:
3012 bool isTransparentTagSlow() const;
3013};
3014
3015/// Represents the declaration of a typedef-name via the 'typedef'
3016/// type specifier.
3017class TypedefDecl : public TypedefNameDecl {
3018 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3019 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3020 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
3021
3022public:
3023 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
3024 SourceLocation StartLoc, SourceLocation IdLoc,
3025 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3026 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3027
3028 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3029
3030 // Implement isa/cast/dyncast/etc.
3031 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3032 static bool classofKind(Kind K) { return K == Typedef; }
3033};
3034
3035/// Represents the declaration of a typedef-name via a C++11
3036/// alias-declaration.
3037class TypeAliasDecl : public TypedefNameDecl {
3038 /// The template for which this is the pattern, if any.
3039 TypeAliasTemplateDecl *Template;
3040
3041 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3042 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3043 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
3044 Template(nullptr) {}
3045
3046public:
3047 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
3048 SourceLocation StartLoc, SourceLocation IdLoc,
3049 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3050 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3051
3052 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3053
3054 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
3055 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
3056
3057 // Implement isa/cast/dyncast/etc.
3058 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3059 static bool classofKind(Kind K) { return K == TypeAlias; }
3060};
3061
3062/// Represents the declaration of a struct/union/class/enum.
3063class TagDecl : public TypeDecl,
3064 public DeclContext,
3065 public Redeclarable<TagDecl> {
3066 // This class stores some data in DeclContext::TagDeclBits
3067 // to save some space. Use the provided accessors to access it.
3068public:
3069 // This is really ugly.
3070 using TagKind = TagTypeKind;
3071
3072private:
3073 SourceRange BraceRange;
3074
3075 // A struct representing syntactic qualifier info,
3076 // to be used for the (uncommon) case of out-of-line declarations.
3077 using ExtInfo = QualifierInfo;
3078
3079 /// If the (out-of-line) tag declaration name
3080 /// is qualified, it points to the qualifier info (nns and range);
3081 /// otherwise, if the tag declaration is anonymous and it is part of
3082 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3083 /// otherwise, if the tag declaration is anonymous and it is used as a
3084 /// declaration specifier for variables, it points to the first VarDecl (used
3085 /// for mangling);
3086 /// otherwise, it is a null (TypedefNameDecl) pointer.
3087 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3088
3089 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3090 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3091 const ExtInfo *getExtInfo() const {
3092 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3093 }
3094
3095protected:
3096 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3097 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3098 SourceLocation StartL);
3099
3100 using redeclarable_base = Redeclarable<TagDecl>;
3101
3102 TagDecl *getNextRedeclarationImpl() override {
3103 return getNextRedeclaration();
3104 }
3105
3106 TagDecl *getPreviousDeclImpl() override {
3107 return getPreviousDecl();
3108 }
3109
3110 TagDecl *getMostRecentDeclImpl() override {
3111 return getMostRecentDecl();
3112 }
3113
3114 /// Completes the definition of this tag declaration.
3115 ///
3116 /// This is a helper function for derived classes.
3117 void completeDefinition();
3118
3119 /// True if this decl is currently being defined.
3120 void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
3121
3122 /// Indicates whether it is possible for declarations of this kind
3123 /// to have an out-of-date definition.
3124 ///
3125 /// This option is only enabled when modules are enabled.
3126 void setMayHaveOutOfDateDef(bool V = true) {
3127 TagDeclBits.MayHaveOutOfDateDef = V;
3128 }
3129
3130public:
3131 friend class ASTDeclReader;
3132 friend class ASTDeclWriter;
3133
3134 using redecl_range = redeclarable_base::redecl_range;
3135 using redecl_iterator = redeclarable_base::redecl_iterator;
3136
3137 using redeclarable_base::redecls_begin;
3138 using redeclarable_base::redecls_end;
3139 using redeclarable_base::redecls;
3140 using redeclarable_base::getPreviousDecl;
3141 using redeclarable_base::getMostRecentDecl;
3142 using redeclarable_base::isFirstDecl;
3143
3144 SourceRange getBraceRange() const { return BraceRange; }
3145 void setBraceRange(SourceRange R) { BraceRange = R; }
3146
3147 /// Return SourceLocation representing start of source
3148 /// range ignoring outer template declarations.
3149 SourceLocation getInnerLocStart() const { return getBeginLoc(); }
3150
3151 /// Return SourceLocation representing start of source
3152 /// range taking into account any outer template declarations.
3153 SourceLocation getOuterLocStart() const;
3154 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3155
3156 TagDecl *getCanonicalDecl() override;
3157 const TagDecl *getCanonicalDecl() const {
3158 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3159 }
3160
3161 /// Return true if this declaration is a completion definition of the type.
3162 /// Provided for consistency.
3163 bool isThisDeclarationADefinition() const {
3164 return isCompleteDefinition();
3165 }
3166
3167 /// Return true if this decl has its body fully specified.
3168 bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
3169
3170 /// True if this decl has its body fully specified.
3171 void setCompleteDefinition(bool V = true) {
3172 TagDeclBits.IsCompleteDefinition = V;
3173 }
3174
3175 /// Return true if this complete decl is
3176 /// required to be complete for some existing use.
3177 bool isCompleteDefinitionRequired() const {
3178 return TagDeclBits.IsCompleteDefinitionRequired;
3179 }
3180
3181 /// True if this complete decl is
3182 /// required to be complete for some existing use.
3183 void setCompleteDefinitionRequired(bool V = true) {
3184 TagDeclBits.IsCompleteDefinitionRequired = V;
3185 }
3186
3187 /// Return true if this decl is currently being defined.
3188 bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
3189
3190 /// True if this tag declaration is "embedded" (i.e., defined or declared
3191 /// for the very first time) in the syntax of a declarator.
3192 bool isEmbeddedInDeclarator() const {
3193 return TagDeclBits.IsEmbeddedInDeclarator;
3194 }
3195
3196 /// True if this tag declaration is "embedded" (i.e., defined or declared
3197 /// for the very first time) in the syntax of a declarator.
3198 void setEmbeddedInDeclarator(bool isInDeclarator) {
3199 TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
3200 }
3201
3202 /// True if this tag is free standing, e.g. "struct foo;".
3203 bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
3204
3205 /// True if this tag is free standing, e.g. "struct foo;".
3206 void setFreeStanding(bool isFreeStanding = true) {
3207 TagDeclBits.IsFreeStanding = isFreeStanding;
3208 }
3209
3210 /// Indicates whether it is possible for declarations of this kind
3211 /// to have an out-of-date definition.
3212 ///
3213 /// This option is only enabled when modules are enabled.
3214 bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
3215
3216 /// Whether this declaration declares a type that is
3217 /// dependent, i.e., a type that somehow depends on template
3218 /// parameters.
3219 bool isDependentType() const { return isDependentContext(); }
3220
3221 /// Starts the definition of this tag declaration.
3222 ///
3223 /// This method should be invoked at the beginning of the definition
3224 /// of this tag declaration. It will set the tag type into a state
3225 /// where it is in the process of being defined.
3226 void startDefinition();
3227
3228 /// Returns the TagDecl that actually defines this
3229 /// struct/union/class/enum. When determining whether or not a
3230 /// struct/union/class/enum has a definition, one should use this
3231 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3232 /// whether or not a specific TagDecl is defining declaration, not
3233 /// whether or not the struct/union/class/enum type is defined.
3234 /// This method returns NULL if there is no TagDecl that defines
3235 /// the struct/union/class/enum.
3236 TagDecl *getDefinition() const;
3237
3238 StringRef getKindName() const {
3239 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3240 }
3241
3242 TagKind getTagKind() const {
3243 return static_cast<TagKind>(TagDeclBits.TagDeclKind);
3244 }
3245
3246 void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; }
3247
3248 bool isStruct() const { return getTagKind() == TTK_Struct; }
3249 bool isInterface() const { return getTagKind() == TTK_Interface; }
3250 bool isClass() const { return getTagKind() == TTK_Class; }
3251 bool isUnion() const { return getTagKind() == TTK_Union; }
3252 bool isEnum() const { return getTagKind() == TTK_Enum; }
3253
3254 /// Is this tag type named, either directly or via being defined in
3255 /// a typedef of this type?
3256 ///
3257 /// C++11 [basic.link]p8:
3258 /// A type is said to have linkage if and only if:
3259 /// - it is a class or enumeration type that is named (or has a
3260 /// name for linkage purposes) and the name has linkage; ...
3261 /// C++11 [dcl.typedef]p9:
3262 /// If the typedef declaration defines an unnamed class (or enum),
3263 /// the first typedef-name declared by the declaration to be that
3264 /// class type (or enum type) is used to denote the class type (or
3265 /// enum type) for linkage purposes only.
3266 ///
3267 /// C does not have an analogous rule, but the same concept is
3268 /// nonetheless useful in some places.
3269 bool hasNameForLinkage() const {
3270 return (getDeclName() || getTypedefNameForAnonDecl());
3271 }
3272
3273 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3274 return hasExtInfo() ? nullptr
3275 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3276 }
3277
3278 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3279
3280 /// Retrieve the nested-name-specifier that qualifies the name of this
3281 /// declaration, if it was present in the source.
3282 NestedNameSpecifier *getQualifier() const {
3283 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3284 : nullptr;
3285 }
3286
3287 /// Retrieve the nested-name-specifier (with source-location
3288 /// information) that qualifies the name of this declaration, if it was
3289 /// present in the source.
3290 NestedNameSpecifierLoc getQualifierLoc() const {
3291 return hasExtInfo() ? getExtInfo()->QualifierLoc
3292 : NestedNameSpecifierLoc();
3293 }
3294
3295 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3296
3297 unsigned getNumTemplateParameterLists() const {
3298 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3299 }
3300
3301 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3302 assert(i < getNumTemplateParameterLists())((i < getNumTemplateParameterLists()) ? static_cast<void
> (0) : __assert_fail ("i < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 3302, __PRETTY_FUNCTION__))
;
3303 return getExtInfo()->TemplParamLists[i];
3304 }
3305
3306 void setTemplateParameterListsInfo(ASTContext &Context,
3307 ArrayRef<TemplateParameterList *> TPLists);
3308
3309 // Implement isa/cast/dyncast/etc.
3310 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3311 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3312
3313 static DeclContext *castToDeclContext(const TagDecl *D) {
3314 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3315 }
3316
3317 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3318 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3319 }
3320};
3321
3322/// Represents an enum. In C++11, enums can be forward-declared
3323/// with a fixed underlying type, and in C we allow them to be forward-declared
3324/// with no underlying type as an extension.
3325class EnumDecl : public TagDecl {
3326 // This class stores some data in DeclContext::EnumDeclBits
3327 // to save some space. Use the provided accessors to access it.
3328
3329 /// This represent the integer type that the enum corresponds
3330 /// to for code generation purposes. Note that the enumerator constants may
3331 /// have a different type than this does.
3332 ///
3333 /// If the underlying integer type was explicitly stated in the source
3334 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3335 /// was automatically deduced somehow, and this is a Type*.
3336 ///
3337 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3338 /// some cases it won't.
3339 ///
3340 /// The underlying type of an enumeration never has any qualifiers, so
3341 /// we can get away with just storing a raw Type*, and thus save an
3342 /// extra pointer when TypeSourceInfo is needed.
3343 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3344
3345 /// The integer type that values of this type should
3346 /// promote to. In C, enumerators are generally of an integer type
3347 /// directly, but gcc-style large enumerators (and all enumerators
3348 /// in C++) are of the enum type instead.
3349 QualType PromotionType;
3350
3351 /// If this enumeration is an instantiation of a member enumeration
3352 /// of a class template specialization, this is the member specialization
3353 /// information.
3354 MemberSpecializationInfo *SpecializationInfo = nullptr;
3355
3356 /// Store the ODRHash after first calculation.
3357 /// The corresponding flag HasODRHash is in EnumDeclBits
3358 /// and can be accessed with the provided accessors.
3359 unsigned ODRHash;
3360
3361 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3362 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3363 bool Scoped, bool ScopedUsingClassTag, bool Fixed);
3364
3365 void anchor() override;
3366
3367 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3368 TemplateSpecializationKind TSK);
3369
3370 /// Sets the width in bits required to store all the
3371 /// non-negative enumerators of this enum.
3372 void setNumPositiveBits(unsigned Num) {
3373 EnumDeclBits.NumPositiveBits = Num;
3374 assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount")((EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount"
) ? static_cast<void> (0) : __assert_fail ("EnumDeclBits.NumPositiveBits == Num && \"can't store this bitcount\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 3374, __PRETTY_FUNCTION__))
;
3375 }
3376
3377 /// Returns the width in bits required to store all the
3378 /// negative enumerators of this enum. (see getNumNegativeBits)
3379 void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
3380
3381 /// True if this tag declaration is a scoped enumeration. Only
3382 /// possible in C++11 mode.
3383 void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
3384
3385 /// If this tag declaration is a scoped enum,
3386 /// then this is true if the scoped enum was declared using the class
3387 /// tag, false if it was declared with the struct tag. No meaning is
3388 /// associated if this tag declaration is not a scoped enum.
3389 void setScopedUsingClassTag(bool ScopedUCT = true) {
3390 EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
3391 }
3392
3393 /// True if this is an Objective-C, C++11, or
3394 /// Microsoft-style enumeration with a fixed underlying type.
3395 void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
3396
3397 /// True if a valid hash is stored in ODRHash.
3398 bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
3399 void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
3400
3401public:
3402 friend class ASTDeclReader;
3403
3404 EnumDecl *getCanonicalDecl() override {
3405 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3406 }
3407 const EnumDecl *getCanonicalDecl() const {
3408 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3409 }
3410
3411 EnumDecl *getPreviousDecl() {
3412 return cast_or_null<EnumDecl>(
3413 static_cast<TagDecl *>(this)->getPreviousDecl());
3414 }
3415 const EnumDecl *getPreviousDecl() const {
3416 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3417 }
3418
3419 EnumDecl *getMostRecentDecl() {
3420 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3421 }
3422 const EnumDecl *getMostRecentDecl() const {
3423 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3424 }
3425
3426 EnumDecl *getDefinition() const {
3427 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3428 }
3429
3430 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3431 SourceLocation StartLoc, SourceLocation IdLoc,
3432 IdentifierInfo *Id, EnumDecl *PrevDecl,
3433 bool IsScoped, bool IsScopedUsingClassTag,
3434 bool IsFixed);
3435 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3436
3437 /// When created, the EnumDecl corresponds to a
3438 /// forward-declared enum. This method is used to mark the
3439 /// declaration as being defined; its enumerators have already been
3440 /// added (via DeclContext::addDecl). NewType is the new underlying
3441 /// type of the enumeration type.
3442 void completeDefinition(QualType NewType,
3443 QualType PromotionType,
3444 unsigned NumPositiveBits,
3445 unsigned NumNegativeBits);
3446
3447 // Iterates through the enumerators of this enumeration.
3448 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3449 using enumerator_range =
3450 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3451
3452 enumerator_range enumerators() const {
3453 return enumerator_range(enumerator_begin(), enumerator_end());
3454 }
3455
3456 enumerator_iterator enumerator_begin() const {
3457 const EnumDecl *E = getDefinition();
3458 if (!E)
3459 E = this;
3460 return enumerator_iterator(E->decls_begin());
3461 }
3462
3463 enumerator_iterator enumerator_end() const {
3464 const EnumDecl *E = getDefinition();
3465 if (!E)
3466 E = this;
3467 return enumerator_iterator(E->decls_end());
3468 }
3469
3470 /// Return the integer type that enumerators should promote to.
3471 QualType getPromotionType() const { return PromotionType; }
3472
3473 /// Set the promotion type.
3474 void setPromotionType(QualType T) { PromotionType = T; }
3475
3476 /// Return the integer type this enum decl corresponds to.
3477 /// This returns a null QualType for an enum forward definition with no fixed
3478 /// underlying type.
3479 QualType getIntegerType() const {
3480 if (!IntegerType)
3481 return QualType();
3482 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3483 return QualType(T, 0);
3484 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3485 }
3486
3487 /// Set the underlying integer type.
3488 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3489
3490 /// Set the underlying integer type source info.
3491 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3492
3493 /// Return the type source info for the underlying integer type,
3494 /// if no type source info exists, return 0.
3495 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3496 return IntegerType.dyn_cast<TypeSourceInfo*>();
3497 }
3498
3499 /// Retrieve the source range that covers the underlying type if
3500 /// specified.
3501 SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__));
3502
3503 /// Returns the width in bits required to store all the
3504 /// non-negative enumerators of this enum.
3505 unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
3506
3507 /// Returns the width in bits required to store all the
3508 /// negative enumerators of this enum. These widths include
3509 /// the rightmost leading 1; that is:
3510 ///
3511 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3512 /// ------------------------ ------- -----------------
3513 /// -1 1111111 1
3514 /// -10 1110110 5
3515 /// -101 1001011 8
3516 unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
3517
3518 /// Returns true if this is a C++11 scoped enumeration.
3519 bool isScoped() const { return EnumDeclBits.IsScoped; }
3520
3521 /// Returns true if this is a C++11 scoped enumeration.
3522 bool isScopedUsingClassTag() const {
3523 return EnumDeclBits.IsScopedUsingClassTag;
3524 }
3525
3526 /// Returns true if this is an Objective-C, C++11, or
3527 /// Microsoft-style enumeration with a fixed underlying type.
3528 bool isFixed() const { return EnumDeclBits.IsFixed; }
3529
3530 unsigned getODRHash();
3531
3532 /// Returns true if this can be considered a complete type.
3533 bool isComplete() const {
3534 // IntegerType is set for fixed type enums and non-fixed but implicitly
3535 // int-sized Microsoft enums.
3536 return isCompleteDefinition() || IntegerType;
3537 }
3538
3539 /// Returns true if this enum is either annotated with
3540 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3541 bool isClosed() const;
3542
3543 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3544 /// with enum_extensibility(open).
3545 bool isClosedFlag() const;
3546
3547 /// Returns true if this enum is annotated with neither flag_enum nor
3548 /// enum_extensibility(open).
3549 bool isClosedNonFlag() const;
3550
3551 /// Retrieve the enum definition from which this enumeration could
3552 /// be instantiated, if it is an instantiation (rather than a non-template).
3553 EnumDecl *getTemplateInstantiationPattern() const;
3554
3555 /// Returns the enumeration (declared within the template)
3556 /// from which this enumeration type was instantiated, or NULL if
3557 /// this enumeration was not instantiated from any template.
3558 EnumDecl *getInstantiatedFromMemberEnum() const;
3559
3560 /// If this enumeration is a member of a specialization of a
3561 /// templated class, determine what kind of template specialization
3562 /// or instantiation this is.
3563 TemplateSpecializationKind getTemplateSpecializationKind() const;
3564
3565 /// For an enumeration member that was instantiated from a member
3566 /// enumeration of a templated class, set the template specialiation kind.
3567 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3568 SourceLocation PointOfInstantiation = SourceLocation());
3569
3570 /// If this enumeration is an instantiation of a member enumeration of
3571 /// a class template specialization, retrieves the member specialization
3572 /// information.
3573 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3574 return SpecializationInfo;
3575 }
3576
3577 /// Specify that this enumeration is an instantiation of the
3578 /// member enumeration ED.
3579 void setInstantiationOfMemberEnum(EnumDecl *ED,
3580 TemplateSpecializationKind TSK) {
3581 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3582 }
3583
3584 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3585 static bool classofKind(Kind K) { return K == Enum; }
3586};
3587
3588/// Represents a struct/union/class. For example:
3589/// struct X; // Forward declaration, no "body".
3590/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3591/// This decl will be marked invalid if *any* members are invalid.
3592class RecordDecl : public TagDecl {
3593 // This class stores some data in DeclContext::RecordDeclBits
3594 // to save some space. Use the provided accessors to access it.
3595public:
3596 friend class DeclContext;
3597 /// Enum that represents the different ways arguments are passed to and
3598 /// returned from function calls. This takes into account the target-specific
3599 /// and version-specific rules along with the rules determined by the
3600 /// language.
3601 enum ArgPassingKind : unsigned {
3602 /// The argument of this type can be passed directly in registers.
3603 APK_CanPassInRegs,
3604
3605 /// The argument of this type cannot be passed directly in registers.
3606 /// Records containing this type as a subobject are not forced to be passed
3607 /// indirectly. This value is used only in C++. This value is required by
3608 /// C++ because, in uncommon situations, it is possible for a class to have
3609 /// only trivial copy/move constructors even when one of its subobjects has
3610 /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
3611 /// constructor in the derived class is deleted).
3612 APK_CannotPassInRegs,
3613
3614 /// The argument of this type cannot be passed directly in registers.
3615 /// Records containing this type as a subobject are forced to be passed
3616 /// indirectly.
3617 APK_CanNeverPassInRegs
3618 };
3619
3620protected:
3621 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3622 SourceLocation StartLoc, SourceLocation IdLoc,
3623 IdentifierInfo *Id, RecordDecl *PrevDecl);
3624
3625public:
3626 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3627 SourceLocation StartLoc, SourceLocation IdLoc,
3628 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3629 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3630
3631 RecordDecl *getPreviousDecl() {
3632 return cast_or_null<RecordDecl>(
3633 static_cast<TagDecl *>(this)->getPreviousDecl());
3634 }
3635 const RecordDecl *getPreviousDecl() const {
3636 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3637 }
3638
3639 RecordDecl *getMostRecentDecl() {
3640 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3641 }
3642 const RecordDecl *getMostRecentDecl() const {
3643 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3644 }
3645
3646 bool hasFlexibleArrayMember() const {
3647 return RecordDeclBits.HasFlexibleArrayMember;
3648 }
3649
3650 void setHasFlexibleArrayMember(bool V) {
3651 RecordDeclBits.HasFlexibleArrayMember = V;
3652 }
3653
3654 /// Whether this is an anonymous struct or union. To be an anonymous
3655 /// struct or union, it must have been declared without a name and
3656 /// there must be no objects of this type declared, e.g.,
3657 /// @code
3658 /// union { int i; float f; };
3659 /// @endcode
3660 /// is an anonymous union but neither of the following are:
3661 /// @code
3662 /// union X { int i; float f; };
3663 /// union { int i; float f; } obj;
3664 /// @endcode
3665 bool isAnonymousStructOrUnion() const {
3666 return RecordDeclBits.AnonymousStructOrUnion;
3667 }
3668
3669 void setAnonymousStructOrUnion(bool Anon) {
3670 RecordDeclBits.AnonymousStructOrUnion = Anon;
3671 }
3672
3673 bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
3674 void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
3675
3676 bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
3677
3678 void setHasVolatileMember(bool val) {
3679 RecordDeclBits.HasVolatileMember = val;
3680 }
3681
3682 bool hasLoadedFieldsFromExternalStorage() const {
3683 return RecordDeclBits.LoadedFieldsFromExternalStorage;
3684 }
3685
3686 void setHasLoadedFieldsFromExternalStorage(bool val) const {
3687 RecordDeclBits.LoadedFieldsFromExternalStorage = val;
3688 }
3689
3690 /// Functions to query basic properties of non-trivial C structs.
3691 bool isNonTrivialToPrimitiveDefaultInitialize() const {
3692 return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
3693 }
3694
3695 void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
3696 RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
3697 }
3698
3699 bool isNonTrivialToPrimitiveCopy() const {
3700 return RecordDeclBits.NonTrivialToPrimitiveCopy;
3701 }
3702
3703 void setNonTrivialToPrimitiveCopy(bool V) {
3704 RecordDeclBits.NonTrivialToPrimitiveCopy = V;
3705 }
3706
3707 bool isNonTrivialToPrimitiveDestroy() const {
3708 return RecordDeclBits.NonTrivialToPrimitiveDestroy;
3709 }
3710
3711 void setNonTrivialToPrimitiveDestroy(bool V) {
3712 RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
3713 }
3714
3715 /// Determine whether this class can be passed in registers. In C++ mode,
3716 /// it must have at least one trivial, non-deleted copy or move constructor.
3717 /// FIXME: This should be set as part of completeDefinition.
3718 bool canPassInRegisters() const {
3719 return getArgPassingRestrictions() == APK_CanPassInRegs;
3720 }
3721
3722 ArgPassingKind getArgPassingRestrictions() const {
3723 return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions);
3724 }
3725
3726 void setArgPassingRestrictions(ArgPassingKind Kind) {
3727 RecordDeclBits.ArgPassingRestrictions = Kind;
3728 }
3729
3730 bool isParamDestroyedInCallee() const {
3731 return RecordDeclBits.ParamDestroyedInCallee;
3732 }
3733
3734 void setParamDestroyedInCallee(bool V) {
3735 RecordDeclBits.ParamDestroyedInCallee = V;
3736 }
3737
3738 /// Determines whether this declaration represents the
3739 /// injected class name.
3740 ///
3741 /// The injected class name in C++ is the name of the class that
3742 /// appears inside the class itself. For example:
3743 ///
3744 /// \code
3745 /// struct C {
3746 /// // C is implicitly declared here as a synonym for the class name.
3747 /// };
3748 ///
3749 /// C::C c; // same as "C c;"
3750 /// \endcode
3751 bool isInjectedClassName() const;
3752
3753 /// Determine whether this record is a class describing a lambda
3754 /// function object.
3755 bool isLambda() const;
3756
3757 /// Determine whether this record is a record for captured variables in
3758 /// CapturedStmt construct.
3759 bool isCapturedRecord() const;
3760
3761 /// Mark the record as a record for captured variables in CapturedStmt
3762 /// construct.
3763 void setCapturedRecord();
3764
3765 /// Returns the RecordDecl that actually defines
3766 /// this struct/union/class. When determining whether or not a
3767 /// struct/union/class is completely defined, one should use this
3768 /// method as opposed to 'isCompleteDefinition'.
3769 /// 'isCompleteDefinition' indicates whether or not a specific
3770 /// RecordDecl is a completed definition, not whether or not the
3771 /// record type is defined. This method returns NULL if there is
3772 /// no RecordDecl that defines the struct/union/tag.
3773 RecordDecl *getDefinition() const {
3774 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3775 }
3776
3777 // Iterator access to field members. The field iterator only visits
3778 // the non-static data members of this class, ignoring any static
3779 // data members, functions, constructors, destructors, etc.
3780 using field_iterator = specific_decl_iterator<FieldDecl>;
3781 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3782
3783 field_range fields() const { return field_range(field_begin(), field_end()); }
3784 field_iterator field_begin() const;
3785
3786 field_iterator field_end() const {
3787 return field_iterator(decl_iterator());
3788 }
3789
3790 // Whether there are any fields (non-static data members) in this record.
3791 bool field_empty() const {
3792 return field_begin() == field_end();
3793 }
3794
3795 /// Note that the definition of this type is now complete.
3796 virtual void completeDefinition();
3797
3798 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3799 static bool classofKind(Kind K) {
3800 return K >= firstRecord && K <= lastRecord;
3801 }
3802
3803 /// Get whether or not this is an ms_struct which can
3804 /// be turned on with an attribute, pragma, or -mms-bitfields
3805 /// commandline option.
3806 bool isMsStruct(const ASTContext &C) const;
3807
3808 /// Whether we are allowed to insert extra padding between fields.
3809 /// These padding are added to help AddressSanitizer detect
3810 /// intra-object-overflow bugs.
3811 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3812
3813 /// Finds the first data member which has a name.
3814 /// nullptr is returned if no named data member exists.
3815 const FieldDecl *findFirstNamedDataMember() const;
3816
3817private:
3818 /// Deserialize just the fields.
3819 void LoadFieldsFromExternalStorage() const;
3820};
3821
3822class FileScopeAsmDecl : public Decl {
3823 StringLiteral *AsmString;
3824 SourceLocation RParenLoc;
3825
3826 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3827 SourceLocation StartL, SourceLocation EndL)
3828 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3829
3830 virtual void anchor();
3831
3832public:
3833 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3834 StringLiteral *Str, SourceLocation AsmLoc,
3835 SourceLocation RParenLoc);
3836
3837 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3838
3839 SourceLocation getAsmLoc() const { return getLocation(); }
3840 SourceLocation getRParenLoc() const { return RParenLoc; }
3841 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3842 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3843 return SourceRange(getAsmLoc(), getRParenLoc());
3844 }
3845
3846 const StringLiteral *getAsmString() const { return AsmString; }
3847 StringLiteral *getAsmString() { return AsmString; }
3848 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3849
3850 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3851 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3852};
3853
3854/// Represents a block literal declaration, which is like an
3855/// unnamed FunctionDecl. For example:
3856/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3857class BlockDecl : public Decl, public DeclContext {
3858 // This class stores some data in DeclContext::BlockDeclBits
3859 // to save some space. Use the provided accessors to access it.
3860public:
3861 /// A class which contains all the information about a particular
3862 /// captured value.
3863 class Capture {
3864 enum {
3865 flag_isByRef = 0x1,
3866 flag_isNested = 0x2
3867 };
3868
3869 /// The variable being captured.
3870 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3871
3872 /// The copy expression, expressed in terms of a DeclRef (or
3873 /// BlockDeclRef) to the captured variable. Only required if the
3874 /// variable has a C++ class type.
3875 Expr *CopyExpr;
3876
3877 public:
3878 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3879 : VariableAndFlags(variable,
3880 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3881 CopyExpr(copy) {}
3882
3883 /// The variable being captured.
3884 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3885
3886 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3887 /// variable.
3888 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3889
3890 bool isEscapingByref() const {
3891 return getVariable()->isEscapingByref();
3892 }
3893
3894 bool isNonEscapingByref() const {
3895 return getVariable()->isNonEscapingByref();
3896 }
3897
3898 /// Whether this is a nested capture, i.e. the variable captured
3899 /// is not from outside the immediately enclosing function/block.
3900 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3901
3902 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3903 Expr *getCopyExpr() const { return CopyExpr; }
3904 void setCopyExpr(Expr *e) { CopyExpr = e; }
3905 };
3906
3907private:
3908 /// A new[]'d array of pointers to ParmVarDecls for the formal
3909 /// parameters of this function. This is null if a prototype or if there are
3910 /// no formals.
3911 ParmVarDecl **ParamInfo = nullptr;
3912 unsigned NumParams = 0;
3913
3914 Stmt *Body = nullptr;
3915 TypeSourceInfo *SignatureAsWritten = nullptr;
3916
3917 const Capture *Captures = nullptr;
3918 unsigned NumCaptures = 0;
3919
3920 unsigned ManglingNumber = 0;
3921 Decl *ManglingContextDecl = nullptr;
3922
3923protected:
3924 BlockDecl(DeclContext *DC, SourceLocation CaretLoc);
3925
3926public:
3927 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3928 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3929
3930 SourceLocation getCaretLocation() const { return getLocation(); }
3931
3932 bool isVariadic() const { return BlockDeclBits.IsVariadic; }
3933 void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; }
3934
3935 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3936 Stmt *getBody() const override { return (Stmt*) Body; }
3937 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3938
3939 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3940 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3941
3942 // ArrayRef access to formal parameters.
3943 ArrayRef<ParmVarDecl *> parameters() const {
3944 return {ParamInfo, getNumParams()};
3945 }
3946 MutableArrayRef<ParmVarDecl *> parameters() {
3947 return {ParamInfo, getNumParams()};
3948 }
3949
3950 // Iterator access to formal parameters.
3951 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
3952 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
3953
3954 bool param_empty() const { return parameters().empty(); }
3955 param_iterator param_begin() { return parameters().begin(); }
3956 param_iterator param_end() { return parameters().end(); }
3957 param_const_iterator param_begin() const { return parameters().begin(); }
3958 param_const_iterator param_end() const { return parameters().end(); }
3959 size_t param_size() const { return parameters().size(); }
3960
3961 unsigned getNumParams() const { return NumParams; }
3962
3963 const ParmVarDecl *getParamDecl(unsigned i) const {
3964 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 3964, __PRETTY_FUNCTION__))
;
3965 return ParamInfo[i];
3966 }
3967 ParmVarDecl *getParamDecl(unsigned i) {
3968 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 3968, __PRETTY_FUNCTION__))
;
3969 return ParamInfo[i];
3970 }
3971
3972 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3973
3974 /// True if this block (or its nested blocks) captures
3975 /// anything of local storage from its enclosing scopes.
3976 bool hasCaptures() const { return NumCaptures || capturesCXXThis(); }
3977
3978 /// Returns the number of captured variables.
3979 /// Does not include an entry for 'this'.
3980 unsigned getNumCaptures() const { return NumCaptures; }
3981
3982 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
3983
3984 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3985
3986 capture_const_iterator capture_begin() const { return captures().begin(); }
3987 capture_const_iterator capture_end() const { return captures().end(); }
3988
3989 bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; }
3990 void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; }
3991
3992 bool blockMissingReturnType() const {
3993 return BlockDeclBits.BlockMissingReturnType;
3994 }
3995
3996 void setBlockMissingReturnType(bool val = true) {
3997 BlockDeclBits.BlockMissingReturnType = val;
3998 }
3999
4000 bool isConversionFromLambda() const {
4001 return BlockDeclBits.IsConversionFromLambda;
4002 }
4003
4004 void setIsConversionFromLambda(bool val = true) {
4005 BlockDeclBits.IsConversionFromLambda = val;
4006 }
4007
4008 bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; }
4009 void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; }
4010
4011 bool canAvoidCopyToHeap() const {
4012 return BlockDeclBits.CanAvoidCopyToHeap;
4013 }
4014 void setCanAvoidCopyToHeap(bool B = true) {
4015 BlockDeclBits.CanAvoidCopyToHeap = B;
4016 }
4017
4018 bool capturesVariable(const VarDecl *var) const;
4019
4020 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4021 bool CapturesCXXThis);
4022
4023 unsigned getBlockManglingNumber() const {
4024 return ManglingNumber;
4025 }
4026
4027 Decl *getBlockManglingContextDecl() const {
4028 return ManglingContextDecl;
4029 }
4030
4031 void setBlockMangling(unsigned Number, Decl *Ctx) {
4032 ManglingNumber = Number;
4033 ManglingContextDecl = Ctx;
4034 }
4035
4036 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4037
4038 // Implement isa/cast/dyncast/etc.
4039 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4040 static bool classofKind(Kind K) { return K == Block; }
4041 static DeclContext *castToDeclContext(const BlockDecl *D) {
4042 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
4043 }
4044 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
4045 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
4046 }
4047};
4048
4049/// Represents the body of a CapturedStmt, and serves as its DeclContext.
4050class CapturedDecl final
4051 : public Decl,
4052 public DeclContext,
4053 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
4054protected:
4055 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
4056 return NumParams;
4057 }
4058
4059private:
4060 /// The number of parameters to the outlined function.
4061 unsigned NumParams;
4062
4063 /// The position of context parameter in list of parameters.
4064 unsigned ContextParam;
4065
4066 /// The body of the outlined function.
4067 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
4068
4069 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
4070
4071 ImplicitParamDecl *const *getParams() const {
4072 return getTrailingObjects<ImplicitParamDecl *>();
4073 }
4074
4075 ImplicitParamDecl **getParams() {
4076 return getTrailingObjects<ImplicitParamDecl *>();
4077 }
4078
4079public:
4080 friend class ASTDeclReader;
4081 friend class ASTDeclWriter;
4082 friend TrailingObjects;
4083
4084 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
4085 unsigned NumParams);
4086 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4087 unsigned NumParams);
4088
4089 Stmt *getBody() const override;
4090 void setBody(Stmt *B);
4091
4092 bool isNothrow() const;
4093 void setNothrow(bool Nothrow = true);
4094
4095 unsigned getNumParams() const { return NumParams; }
4096
4097 ImplicitParamDecl *getParam(unsigned i) const {
4098 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 4098, __PRETTY_FUNCTION__))
;
4099 return getParams()[i];
4100 }
4101 void setParam(unsigned i, ImplicitParamDecl *P) {
4102 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 4102, __PRETTY_FUNCTION__))
;
4103 getParams()[i] = P;
4104 }
4105
4106 // ArrayRef interface to parameters.
4107 ArrayRef<ImplicitParamDecl *> parameters() const {
4108 return {getParams(), getNumParams()};
4109 }
4110 MutableArrayRef<ImplicitParamDecl *> parameters() {
4111 return {getParams(), getNumParams()};
4112 }
4113
4114 /// Retrieve the parameter containing captured variables.
4115 ImplicitParamDecl *getContextParam() const {
4116 assert(ContextParam < NumParams)((ContextParam < NumParams) ? static_cast<void> (0) :
__assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 4116, __PRETTY_FUNCTION__))
;
4117 return getParam(ContextParam);
4118 }
4119 void setContextParam(unsigned i, ImplicitParamDecl *P) {
4120 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 4120, __PRETTY_FUNCTION__))
;
4121 ContextParam = i;
4122 setParam(i, P);
4123 }
4124 unsigned getContextParamPosition() const { return ContextParam; }
4125
4126 using param_iterator = ImplicitParamDecl *const *;
4127 using param_range = llvm::iterator_range<param_iterator>;
4128
4129 /// Retrieve an iterator pointing to the first parameter decl.
4130 param_iterator param_begin() const { return getParams(); }
4131 /// Retrieve an iterator one past the last parameter decl.
4132 param_iterator param_end() const { return getParams() + NumParams; }
4133
4134 // Implement isa/cast/dyncast/etc.
4135 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4136 static bool classofKind(Kind K) { return K == Captured; }
4137 static DeclContext *castToDeclContext(const CapturedDecl *D) {
4138 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4139 }
4140 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4141 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4142 }
4143};
4144
4145/// Describes a module import declaration, which makes the contents
4146/// of the named module visible in the current translation unit.
4147///
4148/// An import declaration imports the named module (or submodule). For example:
4149/// \code
4150/// @import std.vector;
4151/// \endcode
4152///
4153/// Import declarations can also be implicitly generated from
4154/// \#include/\#import directives.
4155class ImportDecl final : public Decl,
4156 llvm::TrailingObjects<ImportDecl, SourceLocation> {
4157 friend class ASTContext;
4158 friend class ASTDeclReader;
4159 friend class ASTReader;
4160 friend TrailingObjects;
4161
4162 /// The imported module, along with a bit that indicates whether
4163 /// we have source-location information for each identifier in the module
4164 /// name.
4165 ///
4166 /// When the bit is false, we only have a single source location for the
4167 /// end of the import declaration.
4168 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
4169
4170 /// The next import in the list of imports local to the translation
4171 /// unit being parsed (not loaded from an AST file).
4172 ImportDecl *NextLocalImport = nullptr;
4173
4174 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4175 ArrayRef<SourceLocation> IdentifierLocs);
4176
4177 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4178 SourceLocation EndLoc);
4179
4180 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4181
4182public:
4183 /// Create a new module import declaration.
4184 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4185 SourceLocation StartLoc, Module *Imported,
4186 ArrayRef<SourceLocation> IdentifierLocs);
4187
4188 /// Create a new module import declaration for an implicitly-generated
4189 /// import.
4190 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4191 SourceLocation StartLoc, Module *Imported,
4192 SourceLocation EndLoc);
4193
4194 /// Create a new, deserialized module import declaration.
4195 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4196 unsigned NumLocations);
4197
4198 /// Retrieve the module that was imported by the import declaration.
4199 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4200
4201 /// Retrieves the locations of each of the identifiers that make up
4202 /// the complete module name in the import declaration.
4203 ///
4204 /// This will return an empty array if the locations of the individual
4205 /// identifiers aren't available.
4206 ArrayRef<SourceLocation> getIdentifierLocs() const;
4207
4208 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4209
4210 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4211 static bool classofKind(Kind K) { return K == Import; }
4212};
4213
4214/// Represents a C++ Modules TS module export declaration.
4215///
4216/// For example:
4217/// \code
4218/// export void foo();
4219/// \endcode
4220class ExportDecl final : public Decl, public DeclContext {
4221 virtual void anchor();
4222
4223private:
4224 friend class ASTDeclReader;
4225
4226 /// The source location for the right brace (if valid).
4227 SourceLocation RBraceLoc;
4228
4229 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4230 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4231 RBraceLoc(SourceLocation()) {}
4232
4233public:
4234 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4235 SourceLocation ExportLoc);
4236 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4237
4238 SourceLocation getExportLoc() const { return getLocation(); }
4239 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4240 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4241
4242 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4243 if (RBraceLoc.isValid())
4244 return RBraceLoc;
4245 // No braces: get the end location of the (only) declaration in context
4246 // (if present).
4247 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
4248 }
4249
4250 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
4251 return SourceRange(getLocation(), getEndLoc());
4252 }
4253
4254 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4255 static bool classofKind(Kind K) { return K == Export; }
4256 static DeclContext *castToDeclContext(const ExportDecl *D) {
4257 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4258 }
4259 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4260 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4261 }
4262};
4263
4264/// Represents an empty-declaration.
4265class EmptyDecl : public Decl {
4266 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4267
4268 virtual void anchor();
4269
4270public:
4271 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4272 SourceLocation L);
4273 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4274
4275 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4276 static bool classofKind(Kind K) { return K == Empty; }
4277};
4278
4279/// Insertion operator for diagnostics. This allows sending NamedDecl's
4280/// into a diagnostic with <<.
4281inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4282 const NamedDecl* ND) {
4283 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4284 DiagnosticsEngine::ak_nameddecl);
4285 return DB;
4286}
4287inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4288 const NamedDecl* ND) {
4289 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4290 DiagnosticsEngine::ak_nameddecl);
4291 return PD;
4292}
4293
4294template<typename decl_type>
4295void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4296 // Note: This routine is implemented here because we need both NamedDecl
4297 // and Redeclarable to be defined.
4298 assert(RedeclLink.isFirst() &&((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 4299, __PRETTY_FUNCTION__))
4299 "setPreviousDecl on a decl already in a redeclaration chain")((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 4299, __PRETTY_FUNCTION__))
;
4300
4301 if (PrevDecl) {
4302 // Point to previous. Make sure that this is actually the most recent
4303 // redeclaration, or we can build invalid chains. If the most recent
4304 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4305 First = PrevDecl->getFirstDecl();
4306 assert(First->RedeclLink.isFirst() && "Expected first")((First->RedeclLink.isFirst() && "Expected first")
? static_cast<void> (0) : __assert_fail ("First->RedeclLink.isFirst() && \"Expected first\""
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 4306, __PRETTY_FUNCTION__))
;
4307 decl_type *MostRecent = First->getNextRedeclaration();
4308 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4309
4310 // If the declaration was previously visible, a redeclaration of it remains
4311 // visible even if it wouldn't be visible by itself.
4312 static_cast<decl_type*>(this)->IdentifierNamespace |=
4313 MostRecent->getIdentifierNamespace() &
4314 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4315 } else {
4316 // Make this first.
4317 First = static_cast<decl_type*>(this);
4318 }
4319
4320 // First one will point to this one as latest.
4321 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4322
4323 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||((!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
cast<NamedDecl>(static_cast<decl_type*>(this))->
isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 4324, __PRETTY_FUNCTION__))
4324 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())((!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
cast<NamedDecl>(static_cast<decl_type*>(this))->
isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include/clang/AST/Decl.h"
, 4324, __PRETTY_FUNCTION__))
;
4325}
4326
4327// Inline function definitions.
4328
4329/// Check if the given decl is complete.
4330///
4331/// We use this function to break a cycle between the inline definitions in
4332/// Type.h and Decl.h.
4333inline bool IsEnumDeclComplete(EnumDecl *ED) {
4334 return ED->isComplete();
4335}
4336
4337/// Check if the given decl is scoped.
4338///
4339/// We use this function to break a cycle between the inline definitions in
4340/// Type.h and Decl.h.
4341inline bool IsEnumDeclScoped(EnumDecl *ED) {
4342 return ED->isScoped();
4343}
4344
4345} // namespace clang
4346
4347#endif // LLVM_CLANG_AST_DECL_H